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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13,206 |
Bug 13206 Missing resource
|
20020409: Package View>Context Menu>OpenNewWindowAction.text
|
resolved fixed
|
5ba0c30
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-11T08:34:36Z | 2002-04-10T12:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/PatchedOpenNewWindowAction.java
| |
13,206 |
Bug 13206 Missing resource
|
20020409: Package View>Context Menu>OpenNewWindowAction.text
|
resolved fixed
|
5ba0c30
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-11T08:34:36Z | 2002-04-10T12:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.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 implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.AddBookmarkAction;
import org.eclipse.ui.actions.NewWizardMenu;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.actions.RefreshAction;
import org.eclipse.ui.dialogs.PropertyDialogAction;
import org.eclipse.ui.internal.OpenNewWindowAction;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ViewPart;
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.search.ui.IWorkingSet;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GenerateGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage;
import org.eclipse.jdt.internal.ui.refactoring.actions.IRefactoringAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup;
import org.eclipse.jdt.internal.ui.reorg.ReorgGroup;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.MemberFilterActionGroup;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.OpenActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
/**
* The ViewPart for the ProjectExplorer. It listens to part activation events.
* When selection linking with the editor is enabled the view selection tracks
* the active editor page. Similarly when a resource is selected in the packages
* view the corresponding editor is activated.
*/
public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IPackagesViewPart, IPropertyChangeListener {
public final static String VIEW_ID= JavaUI.ID_PACKAGES;
// Persistance tags.
static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$
static final String TAG_ELEMENT= "element"; //$NON-NLS-1$
static final String TAG_PATH= "path"; //$NON-NLS-1$
static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$
static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$
static final String TAG_FILTERS = "filters"; //$NON-NLS-1$
static final String TAG_FILTER = "filter"; //$NON-NLS-1$
static final String TAG_SHOWLIBRARIES = "showLibraries"; //$NON-NLS-1$
static final String TAG_SHOWBINARIES = "showBinaries"; //$NON-NLS-1$
static final String TAG_WORKINGSET = "workingset"; //$NON-NLS-1$
private JavaElementPatternFilter fPatternFilter= new JavaElementPatternFilter();
private LibraryFilter fLibraryFilter= new LibraryFilter();
private BinaryProjectFilter fBinaryFilter= new BinaryProjectFilter();
private WorkingSetFilter fWorkingSetFilter= new WorkingSetFilter();
private MemberFilterActionGroup fMemberFilterActionGroup;
private ProblemTreeViewer fViewer;
private StandardJavaUILabelProvider fJavaElementLabelProvider;
private PackagesFrameSource fFrameSource;
private FrameList fFrameList;
private ContextMenuGroup[] fStandardGroups;
private Menu fContextMenu;
private OpenResourceAction fOpenCUAction;
private Action fOpenToAction;
private OpenNewWindowAction fOpenNewWindowAction;
private Action fShowTypeHierarchyAction;
private Action fShowNavigatorAction;
private PropertyDialogAction fPropertyDialogAction;
private IRefactoringAction fDeleteAction;
private RefreshAction fRefreshAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private GoIntoAction fZoomInAction;
private UpAction fUpAction;
private GotoTypeAction fGotoTypeAction;
private GotoPackageAction fGotoPackageAction;
private AddBookmarkAction fAddBookmarkAction;
private FilterSelectionAction fFilterAction;
private ShowLibrariesAction fShowLibrariesAction;
private ShowBinariesAction fShowBinariesAction;
private FilterWorkingSetAction fFilterWorkingSetAction;
private RemoveWorkingSetFilterAction fRemoveWorkingSetAction;
private IMemento fMemento;
private ISelectionChangedListener fSelectionListener;
private ActionGroup fStandardActionGroups;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
private ITreeViewerListener fExpansionListener= new ITreeViewerListener() {
public void treeCollapsed(TreeExpansionEvent event) {
}
public void treeExpanded(TreeExpansionEvent event) {
Object element= event.getElement();
if (element instanceof ICompilationUnit ||
element instanceof IClassFile)
expandMainType(element);
}
};
public PackageExplorerPart() {
}
/* (non-Javadoc)
* Method declared on IViewPart.
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/**
* Initializes the default preferences
*/
public static void initDefaults(IPreferenceStore store) {
store.setDefault(TAG_SHOWLIBRARIES, true);
store.setDefault(TAG_SHOWBINARIES, true);
}
/**
* Returns the package explorer part of the active perspective. If
* there isn't any package explorer part <code>null</code> is returned.
*/
public static PackageExplorerPart getFromActivePerspective() {
IViewPart view= JavaPlugin.getActivePage().findView(VIEW_ID);
if (view instanceof PackageExplorerPart)
return (PackageExplorerPart)view;
return null;
}
/**
* Makes the package explorer part visible in the active perspective. If there
* isn't a package explorer part registered <code>null</code> is returned.
* Otherwise the opened view part is returned.
*/
public static PackageExplorerPart openInActivePerspective() {
try {
return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID);
} catch(PartInitException pe) {
return null;
}
}
public void dispose() {
if (fViewer != null)
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fViewer);
if (fContextMenu != null && !fContextMenu.isDisposed())
fContextMenu.dispose();
getSite().getPage().removePartListener(fPartListener);
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
if (fViewer != null)
fViewer.removeTreeListener(fExpansionListener);
super.dispose();
}
/**
* Implementation of IWorkbenchPart.createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fViewer= new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
boolean showCUChildren= JavaBasePreferencePage.showCompilationUnitChildren();
fViewer.setContentProvider(new JavaElementContentProvider(showCUChildren, false));
JavaPlugin.getDefault().getProblemMarkerManager().addListener(fViewer);
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fJavaElementLabelProvider=
new StandardJavaUILabelProvider(
StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED,
StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
StandardJavaUILabelProvider.getAdornmentProviders(true, null)
);
fViewer.setLabelProvider(new DecoratingLabelProvider(
fJavaElementLabelProvider, PlatformUI.getWorkbench().getDecoratorManager())
);
fViewer.setSorter(new JavaElementSorter());
fViewer.addFilter(new EmptyInnerPackageFilter());
fViewer.setUseHashlookup(true);
fViewer.addFilter(fPatternFilter);
fViewer.addFilter(fLibraryFilter);
fMemberFilterActionGroup= new MemberFilterActionGroup(fViewer, "PackageView"); // adds filter
fViewer.addFilter(fWorkingSetFilter);
if(fMemento != null)
restoreFilters();
else
initFilterFromPreferences();
// Set input after filter and sorter has been set. This avoids resorting
// and refiltering.
fViewer.setInput(findInputElement());
initDragAndDrop();
initFrameList();
initKeyListener();
updateTitle();
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getTree());
fViewer.getTree().setMenu(fContextMenu);
// Register viewer with site. This must be done before making the actions.
IWorkbenchPartSite site= getSite();
site.registerContextMenu(menuMgr, fViewer);
site.setSelectionProvider(fViewer);
site.getPage().addPartListener(fPartListener);
makeActions(); // call before registering for selection changes
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
handleSelectionChanged(event);
}
};
fViewer.addSelectionChangedListener(fSelectionListener);
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
handleDoubleClick(event);
}
});
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
fViewer.addTreeListener(fExpansionListener);
if (fMemento != null)
restoreState(fMemento);
fMemento= null;
// Set help for the view
JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW);
fillActionBars();
}
private void fillActionBars() {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
fillToolBar(toolBar);
actionBars.updateActionBars();
IMenuManager menu= actionBars.getMenuManager();
menu.add(fFilterAction);
menu.add(fShowLibrariesAction);
//menu.add(fShowBinariesAction);
menu.add(fFilterWorkingSetAction);
menu.add(fRemoveWorkingSetAction);
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
fStandardActionGroups.fillActionBars(actionBars);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, fDeleteAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.REFRESH, fRefreshAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.BOOKMARK, fAddBookmarkAction);
// 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);
ReorgGroup.addGlobalReorgActions(actionBars, getSelectionProvider());
}
private void fillToolBar(IToolBarManager toolBar) {
toolBar.removeAll();
toolBar.add(fBackAction);
toolBar.add(fForwardAction);
toolBar.add(fUpAction);
if (JavaBasePreferencePage.showCompilationUnitChildren()) {
toolBar.add(new Separator());
fMemberFilterActionGroup.contributeToToolBar(toolBar);
}
}
private Object findInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IWorkspace) {
return JavaCore.create(((IWorkspace)input).getRoot());
} else if (input instanceof IContainer) {
return JavaCore.create((IContainer)input);
}
//1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
// we can't handle the input
// fall back to show the workspace
return JavaCore.create(JavaPlugin.getWorkspace().getRoot());
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key.equals(ISelectionProvider.class))
return fViewer;
return super.getAdapter(key);
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
result= JavaElementLabels.getTextLabel(element, StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
IWorkingSet ws= fWorkingSetFilter.getWorkingSet();
if (ws == null)
return result;
String wsstr= "Working Set: "+ws.getName();
if (result.length() == 0)
return wsstr;
return result + " - " + wsstr;
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
/**
* @see IWorkbenchPart#setFocus()
*/
public void setFocus() {
fViewer.getTree().setFocus();
}
/**
* Sets the working set to be used for filtering this part
*/
public void setWorkingSet(IWorkingSet ws) {
fWorkingSetFilter.setWorkingSet(ws);
firePropertyChange(IWorkbenchPart.PROP_TITLE);
fFilterWorkingSetAction.setChecked(ws != null);
fRemoveWorkingSetAction.setEnabled(ws != null);
}
/**
* Returns the shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
private Shell getShell() {
return fViewer.getTree().getShell();
}
/**
* Returns the selection provider.
*/
private ISelectionProvider getSelectionProvider() {
return fViewer;
}
/**
* Returns the current selection.
*/
private ISelection getSelection() {
return fViewer.getSelection();
}
//---- Action handling ----------------------------------------------------------
/**
* Called when the context menu is about to open. Override
* to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection();
int size= selection.size();
Object element= selection.getFirstElement();
fPropertyDialogAction.selectionChanged(selection);
MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu);
new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false);
// updateActions(selection);
if (size == 1 && fViewer.isExpandable(element))
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
addGotoMenu(menu);
fOpenCUAction.update();
if (fOpenCUAction.isEnabled())
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpenCUAction);
addOpenWithMenu(menu, selection);
if (size == 1)
addOpenNewWindowAction(menu, element);
addRefactoring(menu);
ContextMenuGroup.add(menu, fStandardGroups, fViewer);
if (onlyFilesSelected(selection)) {
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddBookmarkAction);
}
menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fRefreshAction);
menu.add(new Separator());
if (fPropertyDialogAction.isApplicableForSelection())
menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fPropertyDialogAction);
}
void addGotoMenu(IMenuManager menu) {
MenuManager gotoMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.gotoTitle")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, gotoMenu);
gotoMenu.add(fBackAction);
gotoMenu.add(fForwardAction);
gotoMenu.add(fUpAction);
gotoMenu.add(fGotoTypeAction);
gotoMenu.add(fGotoPackageAction);
}
private void 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 OpenNewWindowAction(getSite().getWorkbenchWindow(), (IContainer)element));
}
private boolean onlyFilesSelected(IStructuredSelection selection) {
if (selection.isEmpty())
return false;
for (Iterator enum= selection.iterator(); enum.hasNext();) {
Object o= enum.next();
if (o instanceof IFile)
continue;
if (o instanceof IAdaptable) {
Object resource= ((IAdaptable)o).getAdapter(IResource.class);
if (!(resource instanceof IFile))
return false;
} else {
return false;
}
}
return true;
}
private void makeActions() {
ISelectionProvider provider= getSelectionProvider();
fOpenCUAction= new OpenResourceAction(provider);
fPropertyDialogAction= new PropertyDialogAction(getShell(), provider);
// fShowTypeHierarchyAction= new ShowTypeHierarchyAction(provider);
fShowNavigatorAction= new ShowInNavigatorAction(provider);
fAddBookmarkAction= new AddBookmarkAction(getShell());
provider.addSelectionChangedListener(fAddBookmarkAction);
fStandardGroups= new ContextMenuGroup[] {
new BuildGroup(),
new ReorgGroup(),
new GenerateGroup(),
new JavaSearchGroup()
};
fStandardActionGroups= new CompositeActionGroup(new ActionGroup[] {
new OpenActionGroup(this), new ShowActionGroup(this), new GenerateActionGroup(this)});
fDeleteAction= ReorgGroup.createDeleteAction(provider);
fRefreshAction= new RefreshAction(getShell());
provider.addSelectionChangedListener(fRefreshAction);
fFilterAction = new FilterSelectionAction(getShell(), this, PackagesMessages.getString("PackageExplorer.filters")); //$NON-NLS-1$
fShowLibrariesAction = new ShowLibrariesAction(this, PackagesMessages.getString("PackageExplorer.referencedLibs")); //$NON-NLS-1$
fShowBinariesAction = new ShowBinariesAction(getShell(), this, PackagesMessages.getString("PackageExplorer.binaryProjects")); //$NON-NLS-1$
fFilterWorkingSetAction = new FilterWorkingSetAction(getShell(), this, "Filter Working Set..."); //$NON-NLS-1$
fRemoveWorkingSetAction = new RemoveWorkingSetFilterAction(getShell(), this, "Remove Working Set Filter"); //$NON-NLS-1$
fBackAction= new BackAction(fFrameList);
fForwardAction= new ForwardAction(fFrameList);
fZoomInAction= new GoIntoAction(fFrameList);
fUpAction= new UpAction(fFrameList);
fGotoTypeAction= new GotoTypeAction(this);
fGotoPackageAction= new GotoPackageAction(this);
}
private void addRefactoring(IMenuManager menu){
MenuManager refactoring= new MenuManager(PackagesMessages.getString("PackageExplorer.refactoringTitle")); //$NON-NLS-1$
ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fViewer);
if (!refactoring.isEmpty())
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring);
}
private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) {
// If one file is selected get it.
// Otherwise, do not show the "open with" menu.
if (selection.size() != 1)
return;
IAdaptable element= (IAdaptable)selection.getFirstElement();
Object resource= element.getAdapter(IResource.class);
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(PackagesMessages.getString("PackageExplorer.openWith")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
private boolean isSelectionOfType(ISelection s, Class clazz, boolean considerUnderlyingResource) {
if (! (s instanceof IStructuredSelection) || s.isEmpty())
return false;
IStructuredSelection selection= (IStructuredSelection)s;
Iterator iter= selection.iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (clazz.isInstance(o))
return true;
if (considerUnderlyingResource) {
if (! (o instanceof IJavaElement))
return false;
IJavaElement element= (IJavaElement)o;
Object resource= element.getAdapter(IResource.class);
if (! clazz.isInstance(resource))
return false;
}
}
return true;
}
//---- Event handling ----------------------------------------------------------
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE;
final LocalSelectionTransfer lt= LocalSelectionTransfer.getInstance();
Transfer[] transfers= new Transfer[] {
lt,
ResourceTransfer.getInstance(),
FileTransfer.getInstance()};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer),
new FileTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
Control control= fViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(fViewer),
new FileTransferDragAdapter(fViewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
/**
* Handles double clicks in viewer.
* Opens editor if file double-clicked.
*/
private void handleDoubleClick(DoubleClickEvent event) {
IStructuredSelection s= (IStructuredSelection) event.getSelection();
Object element= s.getFirstElement();
if (fOpenCUAction.isEnabled()) {
fOpenCUAction.run();
return;
}
if (fViewer.isExpandable(element)) {
if (JavaBasePreferencePage.doubleClickGoesInto()) {
// don't zoom into compilation units and class files
if (element instanceof IOpenable &&
!(element instanceof ICompilationUnit) &&
!(element instanceof IClassFile)) {
fZoomInAction.run();
}
} else {
fViewer.setExpandedState(element, !fViewer.getExpandedState(element));
//expandMainType(element);
}
}
}
/**
* Handles selection changed in viewer.
* Updates global actions.
* Links to editor (if option enabled)
*/
private void handleSelectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection= (IStructuredSelection) event.getSelection();
//updateGlobalActions(sel);
fZoomInAction.update();
linkToEditor(selection);
}
public void selectReveal(ISelection selection) {
ISelection javaSelection= convertSelection(selection);
fViewer.setSelection(javaSelection, true);
}
private ISelection convertSelection(ISelection s) {
List converted= new ArrayList();
if (s instanceof StructuredSelection) {
Object[] elements= ((StructuredSelection)s).toArray();
for (int i= 0; i < elements.length; i++) {
Object e= elements[i];
if (e instanceof IJavaElement)
converted.add(e);
else if (e instanceof IResource) {
IJavaElement element= JavaCore.create((IResource)e);
if (element != null)
converted.add(element);
else
converted.add(e);
}
}
}
return new StructuredSelection(converted.toArray());
}
public void selectAndReveal(Object element) {
selectReveal(new StructuredSelection(element));
}
/**
* Returns whether the preference to link selection to active editor is enabled.
*/
boolean isLinkingEnabled() {
return JavaBasePreferencePage.linkPackageSelectionToEditor();
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
//if (!isLinkingEnabled())
// return;
Object obj= selection.getFirstElement();
Object element= null;
if (selection.size() == 1) {
if (obj instanceof IJavaElement) {
IJavaElement cu= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.COMPILATION_UNIT);
if (cu != null)
element= getResourceFor(cu);
if (element == null)
element= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.CLASS_FILE);
}
else if (obj instanceof IFile)
element= obj;
if (element == null)
return;
IWorkbenchPage page= getSite().getPage();
IEditorPart editorArray[]= page.getEditors();
for (int i= 0; i < editorArray.length; ++i) {
IEditorPart editor= editorArray[i];
Object input= getElementOfInput(editor.getEditorInput());
if (input != null && input.equals(element)) {
page.bringToTop(editor);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(editor, (IJavaElement) obj);
return;
}
}
}
}
private IResource getResourceFor(Object element) {
if (element instanceof IJavaElement) {
if (element instanceof IWorkingCopy) {
IWorkingCopy wc= (IWorkingCopy)element;
IJavaElement original= wc.getOriginalElement();
if (original != null)
element= original;
}
try {
element= ((IJavaElement)element).getUnderlyingResource();
} catch (JavaModelException e) {
return null;
}
}
if (!(element instanceof IResource) || ((IResource)element).isPhantom()) {
return null;
}
return (IResource)element;
}
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
saveExpansionState(memento);
saveSelectionState(memento);
saveScrollState(memento, fViewer.getTree());
savePatternFilterState(memento);
saveFilterState(memento);
saveWorkingSetState(memento);
saveMemberFilterState(memento);
}
protected void saveFilterState(IMemento memento) {
boolean showLibraries= getLibraryFilter().getShowLibraries();
String show= "true"; //$NON-NLS-1$
if (!showLibraries)
show= "false"; //$NON-NLS-1$
memento.putString(TAG_SHOWLIBRARIES, show);
//save binary filter
boolean showBinaries= getBinaryFilter().getShowBinaries();
String showBinString= "true"; //$NON-NLS-1$
if (!showBinaries)
showBinString= "false"; //$NON-NLS-1$
memento.putString(TAG_SHOWBINARIES, showBinString);
}
protected void savePatternFilterState(IMemento memento) {
String filters[] = getPatternFilter().getPatterns();
if(filters.length > 0) {
IMemento filtersMem = memento.createChild(TAG_FILTERS);
for (int i = 0; i < filters.length; i++){
IMemento child = filtersMem.createChild(TAG_FILTER);
child.putString(TAG_ELEMENT,filters[i]);
}
}
}
protected void saveScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position));
//save horizontal position
bar= tree.getHorizontalBar();
position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position));
}
protected void saveSelectionState(IMemento memento) {
Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
if (elements.length > 0) {
IMemento selectionMem= memento.createChild(TAG_SELECTION);
for (int i= 0; i < elements.length; i++) {
IMemento elementMem= selectionMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= elements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier());
}
}
}
protected void saveExpansionState(IMemento memento) {
Object expandedElements[]= fViewer.getExpandedElements();
if (expandedElements.length > 0) {
IMemento expandedMem= memento.createChild(TAG_EXPANDED);
for (int i= 0; i < expandedElements.length; i++) {
IMemento elementMem= expandedMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= expandedElements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier());
}
}
}
protected void saveWorkingSetState(IMemento memento) {
IWorkingSet ws= getWorkingSetFilter().getWorkingSet();
if (ws != null) {
memento.putString(TAG_WORKINGSET, ws.getName());
}
}
/**
* Saves the state of the filter actions
*/
public void saveMemberFilterState(IMemento memento) {
fMemberFilterActionGroup.saveState(memento);
}
void restoreState(IMemento memento) {
restoreExpansionState(memento);
restoreSelectionState(memento);
restoreScrollState(memento, fViewer.getTree());
}
protected void restoreScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_VERTICAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore, don't set scrollposition
}
}
bar= tree.getHorizontalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_HORIZONTAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore don't set scroll position
}
}
}
protected void restoreSelectionState(IMemento memento) {
IMemento childMem;
childMem= memento.getChild(TAG_SELECTION);
if (childMem != null) {
ArrayList list= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
list.add(element);
}
fViewer.setSelection(new StructuredSelection(list));
}
}
protected void restoreExpansionState(IMemento memento) {
IMemento childMem= memento.getChild(TAG_EXPANDED);
if (childMem != null) {
ArrayList elements= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
elements.add(element);
}
fViewer.setExpandedElements(elements.toArray());
}
}
/**
* Create the KeyListener for doing the refresh on the viewer.
*/
private void initKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
doKeyPressed(event);
}
});
}
private void doKeyPressed(KeyEvent event) {
if (event.stateMask != 0)
return;
int key= event.keyCode;
if (key == SWT.F5) {
fRefreshAction.selectionChanged(
(IStructuredSelection) fViewer.getSelection());
if (fRefreshAction.isEnabled())
fRefreshAction.run();
} if (event.character == SWT.DEL){
fDeleteAction.update();
if (fDeleteAction.isEnabled())
fDeleteAction.run();
}
}
void initFrameList() {
fFrameSource= new PackagesFrameSource(this);
fFrameList= new FrameList(fFrameSource);
fFrameSource.connectTo(fFrameList);
}
/**
* An editor has been activated. Set the selection in this Packages Viewer
* to be the editor's input, if linking is enabled.
*/
void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled())
return;
Object input= getElementOfInput(editor.getEditorInput());
Object element= null;
if (input instanceof IFile)
element= JavaCore.create((IFile)input);
if (element == null) // try a non Java resource
element= input;
if (element != null) {
// if the current selection is a child of the new
// selection then ignore it.
IStructuredSelection oldSelection= (IStructuredSelection)getSelection();
if (oldSelection.size() == 1) {
Object o= oldSelection.getFirstElement();
if (o instanceof IMember) {
IMember m= (IMember)o;
if (element.equals(m.getCompilationUnit()))
return;
if (element.equals(m.getClassFile()))
return;
}
}
ISelection newSelection= new StructuredSelection(element);
if (!fViewer.getSelection().equals(newSelection)) {
try {
fViewer.removeSelectionChangedListener(fSelectionListener);
fViewer.setSelection(newSelection);
} finally {
fViewer.addSelectionChangedListener(fSelectionListener);
}
}
}
}
/**
* A compilation unit or class was expanded, expand
* the main type.
*/
void expandMainType(Object element) {
try {
IType type= null;
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
IType[] types= cu.getTypes();
if (types.length > 0)
type= types[0];
}
else if (element instanceof IClassFile) {
IClassFile cf= (IClassFile)element;
type= cf.getType();
}
if (type != null) {
final IType type2= type;
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.expandToLevel(type2, 1);
}
});
}
}
} catch(JavaModelException e) {
// no reveal
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
/**
* Returns the Viewer.
*/
TreeViewer getViewer() {
return fViewer;
}
/**
* Returns the pattern filter for this view.
* @return the pattern filter
*/
JavaElementPatternFilter getPatternFilter() {
return fPatternFilter;
}
/**
* Returns the library filter for this view.
* @return the library filter
*/
LibraryFilter getLibraryFilter() {
return fLibraryFilter;
}
/**
* Returns the working set filter for this view.
* @return the working set filter
*/
WorkingSetFilter getWorkingSetFilter() {
return fWorkingSetFilter;
}
/**
* Returns the Binary filter for this view.
* @return the binary filter
*/
BinaryProjectFilter getBinaryFilter() {
return fBinaryFilter;
}
void restoreFilters() {
IMemento filtersMem= fMemento.getChild(TAG_FILTERS);
if(filtersMem != null) {
IMemento children[]= filtersMem.getChildren(TAG_FILTER);
String filters[]= new String[children.length];
for (int i = 0; i < children.length; i++) {
filters[i]= children[i].getString(TAG_ELEMENT);
}
getPatternFilter().setPatterns(filters);
} else {
getPatternFilter().setPatterns(new String[0]);
}
//restore library
String show= fMemento.getString(TAG_SHOWLIBRARIES);
if (show != null)
getLibraryFilter().setShowLibraries(show.equals("true")); //$NON-NLS-1$
else
initLibraryFilterFromPreferences();
//restore binary fileter
String showbin= fMemento.getString(TAG_SHOWBINARIES);
if (showbin != null)
getBinaryFilter().setShowBinaries(showbin.equals("true")); //$NON-NLS-1$
else
initBinaryFilterFromPreferences();
//restore working set
String workingSetName= fMemento.getString(TAG_WORKINGSET);
if (workingSetName != null) {
IWorkingSet ws= SearchUI.findWorkingSet(workingSetName);
if (ws != null) {
getWorkingSetFilter().setWorkingSet(ws);
}
}
fMemberFilterActionGroup.restoreState(fMemento);
}
void initFilterFromPreferences() {
initBinaryFilterFromPreferences();
initLibraryFilterFromPreferences();
}
void initLibraryFilterFromPreferences() {
JavaPlugin plugin= JavaPlugin.getDefault();
boolean show= plugin.getPreferenceStore().getBoolean(TAG_SHOWLIBRARIES);
getLibraryFilter().setShowLibraries(show);
}
void initBinaryFilterFromPreferences() {
JavaPlugin plugin= JavaPlugin.getDefault();
boolean showbin= plugin.getPreferenceStore().getBoolean(TAG_SHOWBINARIES);
getBinaryFilter().setShowBinaries(showbin);
}
boolean isExpandable(Object element) {
if (fViewer == null)
return false;
return fViewer.isExpandable(element);
}
/**
* Updates the title text and title tool tip.
* Called whenever the input of the viewer changes.
*/
void updateTitle() {
Object input= getViewer().getInput();
String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
if (input == null
|| (input instanceof IJavaModel)) {
setTitle(viewName);
setTitleToolTip(""); //$NON-NLS-1$
} else {
String inputText= JavaElementLabels.getTextLabel(input, StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS);
String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$
setTitle(title);
setTitleToolTip(getToolTipText(input));
}
}
/**
* Sets the decorator for the package explorer.
*
* @param decorator a label decorator or <code>null</code> for no decorations.
* @deprecated To be removed
*/
public void setLabelDecorator(ILabelDecorator decorator) {
if (decorator == null)
fViewer.setLabelProvider(fJavaElementLabelProvider);
else
fViewer.setLabelProvider(new DecoratingLabelProvider(fJavaElementLabelProvider, decorator));
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
boolean refreshViewer= false;
if (event.getProperty() == JavaBasePreferencePage.SHOW_CU_CHILDREN) {
IActionBars actionBars= getViewSite().getActionBars();
fillToolBar(actionBars.getToolBarManager());
actionBars.updateActionBars();
boolean showCUChildren= JavaBasePreferencePage.showCompilationUnitChildren();
((JavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren);
refreshViewer= true;
}
if (refreshViewer)
fViewer.refresh();
}
}
|
13,303 |
Bug 13303 Create New Class: Too many comments
|
Now both type- and file- comment contain a message that thay can be configured in the pref page: /** * Created on 10.04.2002 * * To change this generated comment edit the template variable "filecomment": * Workbench>Preferences>Java>Templates. */ /** * @author maeschlimann * * To change this generated comment edit the template variable "typecomment": * Workbench>Preferences>Java>Templates. */ public class A { -> We should disable the option CodeGeneration->create file comment -> Path should be Window>Preferences>Java>Templates
|
resolved fixed
|
a2a8c97
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-11T08:36:56Z | 2002-04-10T14:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeGenerationPreferencePage.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.util.StringTokenizer;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
public class CodeGenerationPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String PREF_USE_GETTERSETTER_PREFIX= JavaUI.ID_PLUGIN + ".gettersetter.prefix.enable"; //$NON-NLS-1$
private static final String PREF_GETTERSETTER_PREFIX= JavaUI.ID_PLUGIN + ".gettersetter.prefix.list"; //$NON-NLS-1$
private static final String PREF_USE_GETTERSETTER_SUFFIX= JavaUI.ID_PLUGIN + ".gettersetter.suffix.enable"; //$NON-NLS-1$
private static final String PREF_GETTERSETTER_SUFFIX= JavaUI.ID_PLUGIN + ".gettersetter.suffix.list"; //$NON-NLS-1$
private static final String PREF_JAVADOC_STUBS= JavaUI.ID_PLUGIN + ".javadoc"; //$NON-NLS-1$
private static final String PREF_NON_JAVADOC_COMMENTS= JavaUI.ID_PLUGIN + ".seecomments"; //$NON-NLS-1$
private static final String PREF_FILE_COMMENTS= JavaUI.ID_PLUGIN + ".filecomments"; //$NON-NLS-1$
public static String[] getGetterStetterPrefixes() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
if (prefs.getBoolean(PREF_USE_GETTERSETTER_PREFIX)) {
String str= prefs.getString(PREF_GETTERSETTER_PREFIX);
if (str != null) {
return unpackOrderList(str);
}
}
return new String[0];
}
public static String[] getGetterStetterSuffixes() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
if (prefs.getBoolean(PREF_USE_GETTERSETTER_SUFFIX)) {
String str= prefs.getString(PREF_GETTERSETTER_SUFFIX);
if (str != null) {
return unpackOrderList(str);
}
}
return new String[0];
}
public static boolean doCreateComments() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_JAVADOC_STUBS);
}
public static boolean doNonJavaDocSeeComments() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_NON_JAVADOC_COMMENTS);
}
public static boolean doFileComments() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_FILE_COMMENTS);
}
private static String[] unpackOrderList(String str) {
StringTokenizer tok= new StringTokenizer(str, ","); //$NON-NLS-1$
int nTokens= tok.countTokens();
String[] res= new String[nTokens];
for (int i= 0; i < nTokens; i++) {
res[i]= tok.nextToken().trim();
}
return res;
}
/**
* Initializes the current options (read from preference store)
*/
public static void initDefaults(IPreferenceStore prefs) {
prefs.setDefault(PREF_USE_GETTERSETTER_PREFIX, false);
prefs.setDefault(PREF_USE_GETTERSETTER_SUFFIX, false);
prefs.setDefault(PREF_GETTERSETTER_PREFIX, "f, fg, _, m_"); //$NON-NLS-1$
prefs.setDefault(PREF_GETTERSETTER_SUFFIX, "_"); //$NON-NLS-1$
prefs.setDefault(PREF_JAVADOC_STUBS, true);
prefs.setDefault(PREF_NON_JAVADOC_COMMENTS, false);
prefs.setDefault(PREF_FILE_COMMENTS, true);
}
private SelectionButtonDialogField fUseGetterSetterPrefix;
private SelectionButtonDialogField fUseGetterSetterSuffix;
private StringDialogField fGetterSetterPrefix;
private StringDialogField fGetterSetterSuffix;
private SelectionButtonDialogField fCreateJavaDocComments;
private SelectionButtonDialogField fCreateNonJavadocComments;
private SelectionButtonDialogField fCreateFileComments;
private IStatus fGetterSetterPrefixStatus;
private IStatus fGetterSetterSuffixStatus;
public CodeGenerationPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("CodeGenerationPreferencePage.description")); //$NON-NLS-1$
IDialogFieldListener listener= new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
doDialogFieldChanged(field);
}
};
fGetterSetterPrefixStatus= new StatusInfo();
fGetterSetterSuffixStatus= new StatusInfo();
fUseGetterSetterPrefix= new SelectionButtonDialogField(SWT.CHECK);
fUseGetterSetterPrefix.setDialogFieldListener(listener);
fUseGetterSetterPrefix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.prefix.checkbox")); //$NON-NLS-1$
fGetterSetterPrefix= new StringDialogField();
fGetterSetterPrefix.setDialogFieldListener(listener);
fGetterSetterPrefix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.prefix.list")); //$NON-NLS-1$
fUseGetterSetterSuffix= new SelectionButtonDialogField(SWT.CHECK);
fUseGetterSetterSuffix.setDialogFieldListener(listener);
fUseGetterSetterSuffix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.suffix.checkbox")); //$NON-NLS-1$
fGetterSetterSuffix= new StringDialogField();
fGetterSetterSuffix.setDialogFieldListener(listener);
fGetterSetterSuffix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.suffix.list")); //$NON-NLS-1$
fCreateJavaDocComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateJavaDocComments.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.javadoc_comment.label")); //$NON-NLS-1$
fCreateNonJavadocComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateNonJavadocComments.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.see_comment.label")); //$NON-NLS-1$
fCreateFileComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateFileComments.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.file_comment.label")); //$NON-NLS-1$
}
private void initFields() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fUseGetterSetterSuffix.setSelection(prefs.getBoolean(PREF_USE_GETTERSETTER_SUFFIX));
String str= prefs.getString(PREF_GETTERSETTER_SUFFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterSuffix.setText(str);
fUseGetterSetterPrefix.setSelection(prefs.getBoolean(PREF_USE_GETTERSETTER_PREFIX));
str= prefs.getString(PREF_GETTERSETTER_PREFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterPrefix.setText(str);
fCreateJavaDocComments.setSelection(prefs.getBoolean(PREF_JAVADOC_STUBS));
fCreateNonJavadocComments.setSelection(prefs.getBoolean(PREF_NON_JAVADOC_COMMENTS));
fCreateFileComments.setSelection(prefs.getBoolean(PREF_FILE_COMMENTS));
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.CODE_MANIPULATION_PREFERENCE_PAGE);
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
int horizontalIndent= convertWidthInCharsToPixels(4);
(new Separator()).doFillIntoGrid(composite, 2, 4);
DialogField javaDocLabel= new DialogField();
javaDocLabel.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.comments.label")); //$NON-NLS-1$
javaDocLabel.doFillIntoGrid(composite, 2);
fCreateJavaDocComments.doFillIntoGrid(composite, 2);
fCreateNonJavadocComments.doFillIntoGrid(composite, 2);
fCreateFileComments.doFillIntoGrid(composite, 2);
(new Separator()).doFillIntoGrid(composite, 2, 4);
DialogField getterSetterLabel= new DialogField();
getterSetterLabel.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.label")); //$NON-NLS-1$
getterSetterLabel.doFillIntoGrid(composite, 2);
fUseGetterSetterPrefix.doFillIntoGrid(composite, 2);
fGetterSetterPrefix.doFillIntoGrid(composite, 2);
LayoutUtil.setHorizontalIndent(fGetterSetterPrefix.getLabelControl(null), horizontalIndent);
LayoutUtil.setHorizontalGrabbing(fGetterSetterPrefix.getTextControl(null));
fUseGetterSetterSuffix.doFillIntoGrid(composite, 2);
fGetterSetterSuffix.doFillIntoGrid(composite, 2);
LayoutUtil.setHorizontalIndent(fGetterSetterSuffix.getLabelControl(null), horizontalIndent);
initFields();
return composite;
}
private void doDialogFieldChanged(DialogField field) {
if (field == fGetterSetterPrefix || field == fUseGetterSetterPrefix) {
fGetterSetterPrefix.setEnabled(fUseGetterSetterPrefix.isSelected());
if (fUseGetterSetterPrefix.isSelected()) {
String[] prefixes= unpackOrderList(fGetterSetterPrefix.getText());
fGetterSetterPrefixStatus= validateIdentifiers(prefixes, true);
} else {
fGetterSetterPrefixStatus= new StatusInfo();
}
}
if (field == fGetterSetterSuffix || field == fUseGetterSetterSuffix) {
fGetterSetterSuffix.setEnabled(fUseGetterSetterSuffix.isSelected());
if (fUseGetterSetterSuffix.isSelected()) {
String[] prefixes= unpackOrderList(fGetterSetterSuffix.getText());
fGetterSetterSuffixStatus= validateIdentifiers(prefixes, false);
} else {
fGetterSetterSuffixStatus= new StatusInfo();
}
}
updateStatus(StatusUtil.getMoreSevere(fGetterSetterPrefixStatus, fGetterSetterSuffixStatus));
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
private IStatus validateIdentifiers(String[] values, boolean prefix) {
for (int i= 0; i < values.length; i++) {
String val= values[i];
if (val.length() == 0) {
if (prefix) {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.error.emptyprefix")); //$NON-NLS-1$
} else {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.error.emptysuffix")); //$NON-NLS-1$
}
}
String name= prefix ? val + "x" : "x" + val; //$NON-NLS-2$ //$NON-NLS-1$
IStatus status= JavaConventions.validateFieldName(name);
if (status.matches(IStatus.ERROR)) {
if (prefix) {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getFormattedString("CodeGenerationPreferencePage.gettersetter.error.invalidprefix", val)); //$NON-NLS-1$
} else {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getFormattedString("CodeGenerationPreferencePage.gettersetter.error.invalidsuffix", val)); //$NON-NLS-1$
}
}
}
return new StatusInfo();
}
/*
* @see IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
prefs.setValue(PREF_USE_GETTERSETTER_SUFFIX, fUseGetterSetterSuffix.isSelected());
prefs.setValue(PREF_GETTERSETTER_SUFFIX, fGetterSetterSuffix.getText());
prefs.setValue(PREF_USE_GETTERSETTER_PREFIX, fUseGetterSetterPrefix.isSelected());
prefs.setValue(PREF_GETTERSETTER_PREFIX, fGetterSetterPrefix.getText());
prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected());
prefs.setValue(PREF_NON_JAVADOC_COMMENTS, fCreateNonJavadocComments.isSelected());
prefs.setValue(PREF_FILE_COMMENTS, fCreateFileComments.isSelected());
return super.performOk();
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fUseGetterSetterSuffix.setSelection(prefs.getDefaultBoolean(PREF_USE_GETTERSETTER_SUFFIX));
String str= prefs.getDefaultString(PREF_GETTERSETTER_SUFFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterSuffix.setText(str);
fUseGetterSetterPrefix.setSelection(prefs.getDefaultBoolean(PREF_USE_GETTERSETTER_PREFIX));
str= prefs.getDefaultString(PREF_GETTERSETTER_PREFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterPrefix.setText(str);
fCreateJavaDocComments.setSelection(prefs.getDefaultBoolean(PREF_JAVADOC_STUBS));
fCreateNonJavadocComments.setSelection(prefs.getDefaultBoolean(PREF_NON_JAVADOC_COMMENTS));
fCreateFileComments.setSelection(prefs.getDefaultBoolean(PREF_FILE_COMMENTS));
super.performDefaults();
}
}
|
13,189 |
Bug 13189 Refactoring - deleting fields - context menu is overriden by message dialog
|
20020409-I on Linux-Motif and w2k: 1. Setup JUnit 2. Enable option 'Code Generator->Remove prefix from field names' 3. Open TestCase.java 4. In the outliner, right click on 'fName'. 5. Observe: No context menu is shown, instead, it asks me right away if I want to delete the getter/setter as well.
|
resolved fixed
|
e23a6cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-11T09:52:56Z | 2002-04-10T09:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/DeleteSourceReferencesAction.java
|
package org.eclipse.jdt.internal.ui.reorg;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
import org.eclipse.jdt.internal.corext.refactoring.Assert;
import org.eclipse.jdt.internal.corext.refactoring.reorg.DeleteSourceReferenceEdit;
import org.eclipse.jdt.internal.corext.refactoring.reorg.SourceReferenceUtil;
import org.eclipse.jdt.internal.corext.refactoring.util.WorkingCopyUtil;
import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer;
import org.eclipse.jdt.internal.corext.textmanipulation.TextBufferEditor;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class DeleteSourceReferencesAction extends SourceReferenceAction{
public DeleteSourceReferencesAction(ISelectionProvider provider) {
super(ReorgMessages.getString("DeleteSourceReferencesAction.delete"), provider); //$NON-NLS-1$
}
protected void perform() throws CoreException {
if (!confirmDelete())
return;
Map mapping= SourceReferenceUtil.groupByFile(getElementsToProcess()); //IFile -> List of ISourceReference (elements from that file)
List emptyCuList= Arrays.asList(getCusLeftEmpty(mapping));
for (Iterator iter= mapping.keySet().iterator(); iter.hasNext();) {
IFile file= (IFile)iter.next();
if (emptyCuList.contains(JavaCore.create(file))) //do not delete in these files
continue;
if (isReadOnly(file))
continue;
deleteAll(mapping, file);
}
ICompilationUnit[] notDeleted= deleteEmptyCus(mapping);
for (int i= 0; i < notDeleted.length; i++) {
IFile file= (IFile)notDeleted[i].getUnderlyingResource();
if (isReadOnly(file))
continue;
deleteAll(mapping, file);
}
}
private static boolean isReadOnly(IFile file){
if (! file.isReadOnly())
return false;
if (ResourcesPlugin.getWorkspace().validateEdit(new IFile[]{file}, null).isOK())
return false;
return true;
}
private static boolean areAllFilesReadOnly(Map mapping){
for (Iterator iter= mapping.keySet().iterator(); iter.hasNext();) {
if (! isReadOnly((IFile)iter.next()))
return false;
}
return true;
}
/*
* @see RefactoringAction#canOperateOn(IStructuredSelection)
*/
public boolean canOperateOn(IStructuredSelection selection) {
if (! super.canOperateOn(selection))
return false;
try {
Map mapping= SourceReferenceUtil.groupByFile(getElementsToProcess()); //IFile -> List of ISourceReference (elements from that file)
return ! areAllFilesReadOnly(mapping);
} catch(JavaModelException e) {
//ignore
return false;
}
}
private static void deleteAll(Map mapping, IFile file) throws CoreException {
List l= (List)mapping.get(file);
ISourceReference[] refs= (ISourceReference[]) l.toArray(new ISourceReference[l.size()]);
delete(file, getNonFields(refs));
delete(getFields(refs));
}
private static void delete(IFile file, ISourceReference[] nonFields) throws CoreException{
TextBuffer tb= TextBuffer.acquire(file);
try{
TextBufferEditor tbe= new TextBufferEditor(tb);
for (int i= 0; i < nonFields.length; i++) {
Assert.isTrue(! (nonFields[i] instanceof IField));
tbe.add(createDeleteEdit(nonFields[i]));
}
if (! tbe.canPerformEdits())
return; ///XXX can i assert here?
tbe.performEdits(new NullProgressMonitor());
TextBuffer.commitChanges(tb, false, new NullProgressMonitor());
} finally{
if (tb != null)
TextBuffer.release(tb);
}
}
private static void delete(IField[] fields) throws JavaModelException{
for (int i= 0; i < fields.length; i++) {
fields[i].delete(false, new NullProgressMonitor());
}
}
private static TextEdit createDeleteEdit(ISourceReference ref) throws JavaModelException{
ICompilationUnit cu= SourceReferenceUtil.getCompilationUnit(ref);
cu.reconcile();
return new DeleteSourceReferenceEdit(ref, cu);
}
/**
* returns cus that have <b>not</b> been deleted
*/
private ICompilationUnit[] deleteEmptyCus(Map mapping) throws JavaModelException {
ICompilationUnit[] cusToDelete= getCusLeftEmpty(mapping);
if (cusToDelete.length == 0)
return cusToDelete;
if (! confirmCusDelete(cusToDelete))
return cusToDelete;
List notDeletedCus= new ArrayList();
notDeletedCus.addAll(Arrays.asList(cusToDelete));
for (int i= 0; i < cusToDelete.length; i++) {
if (isReadOnly(cusToDelete[i]) && (! isOkToDeleteReadOnly(cusToDelete[i])))
continue;
cusToDelete[i].delete(false, new NullProgressMonitor());
notDeletedCus.remove(cusToDelete[i]);
}
return (ICompilationUnit[]) notDeletedCus.toArray(new ICompilationUnit[notDeletedCus.size()]);
}
private static boolean isReadOnly(ICompilationUnit cu) throws JavaModelException{
if (cu.isReadOnly())
return true;
if (cu.getUnderlyingResource() != null && cu.getUnderlyingResource().isReadOnly())
return true;
return false;
}
private static boolean isOkToDeleteReadOnly(ICompilationUnit cu){
String message= "Compilation unit \'" + cu.getElementName() + "\' is read-only. Do you still want to delete it?";
return MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), ReorgMessages.getString("DeleteSourceReferencesAction.delete1"), message); //$NON-NLS-1$
}
/*
* @param Map mapping //IFile -> List of ISourceReference (elements from that file)
*/
private static ICompilationUnit[] getCusLeftEmpty(Map mapping) throws JavaModelException{
List cuList= new ArrayList();
for (Iterator iter= mapping.keySet().iterator(); iter.hasNext();) {
IFile file= (IFile) iter.next();
IJavaElement el= JavaCore.create(file);
if (el == null || el.getElementType() != IJavaElement.COMPILATION_UNIT)
continue;
ICompilationUnit cu= (ICompilationUnit)el;
List sourceReferences= (List)mapping.get(file);
if (willBeLeftEmpty(cu, sourceReferences))
cuList.add(cu);
}
return (ICompilationUnit[]) cuList.toArray(new ICompilationUnit[cuList.size()]);
}
private static boolean willBeLeftEmpty(ICompilationUnit cu, List sourceReferences) throws JavaModelException{
IType[] cuTypes= WorkingCopyUtil.getWorkingCopyIfExists(cu).getTypes();
for (int i= 0; i < cuTypes.length; i++) {
if (! sourceReferences.contains(cuTypes[i]))
return false;
}
return true;
}
//overridden to add getters/setters
protected ISourceReference[] getElementsToProcess() {
ISourceReference[] elements= super.getElementsToProcess();
IField[] fields= getFields(elements);
if (fields.length == 0)
return elements;
IMethod[] gettersSetters= getGettersSettersForFields(fields);
if (gettersSetters.length == 0)
return elements;
Set getterSetterSet= new HashSet(Arrays.asList(gettersSetters));
getterSetterSet.removeAll(Arrays.asList(elements));
if (getterSetterSet.isEmpty())
return elements;
if (! confirmGetterSetterDelete())
return elements;
Set newElementSet= new HashSet(Arrays.asList(elements));
newElementSet.addAll(getterSetterSet);
return (ISourceReference[]) newElementSet.toArray(new ISourceReference[newElementSet.size()]);
}
private static ISourceReference[] getNonFields(ISourceReference[] elements){
List nonFields= new ArrayList();
for (int i= 0; i < elements.length; i++) {
if (! (elements[i] instanceof IField))
nonFields.add(elements[i]);
}
return (ISourceReference[]) nonFields.toArray(new ISourceReference[nonFields.size()]);
}
private static IField[] getFields(ISourceReference[] elements){
List fields= new ArrayList();
for (int i= 0; i < elements.length; i++) {
if (elements[i] instanceof IField)
fields.add(elements[i]);
}
return (IField[]) fields.toArray(new IField[fields.size()]);
}
private static IMethod[] getGettersSettersForFields(IField[] fields) {
try {
String[] namePrefixes= CodeGenerationPreferencePage.getGetterStetterPrefixes();
String[] nameSuffixes= CodeGenerationPreferencePage.getGetterStetterSuffixes();
List gettersSetters= new ArrayList();
for (int i= 0; i < fields.length; i++) {
IMethod getter= GetterSetterUtil.getGetter(fields[i], namePrefixes, nameSuffixes);
if (getter != null && getter.exists())
gettersSetters.add(getter);
IMethod setter= GetterSetterUtil.getSetter(fields[i], namePrefixes, nameSuffixes);
if (setter != null && setter.exists())
gettersSetters.add(setter);
}
return (IMethod[]) gettersSetters.toArray(new IMethod[gettersSetters.size()]);
} catch(JavaModelException e) {
ExceptionHandler.handle(e, JavaPlugin.getActiveWorkbenchShell(), ReorgMessages.getString("DeleteSourceReferencesAction.delete_elements"), ReorgMessages.getString("DeleteSourceReferencesAction.exception")); //$NON-NLS-1$ //$NON-NLS-2$
return new IMethod[0];
}
}
//made protected for ui-less testing
protected boolean confirmDelete() {
String title= ReorgMessages.getString("deleteAction.confirm.title"); //$NON-NLS-1$
String label= ReorgMessages.getString("deleteAction.confirm.message"); //$NON-NLS-1$
Shell parent= JavaPlugin.getActiveWorkbenchShell();
return MessageDialog.openQuestion(parent, title, label);
}
//made protected for ui-less testing
protected boolean confirmCusDelete(ICompilationUnit[] cusToDelete) {
String message;
if (cusToDelete.length == 1)
message= "After the delete operation the compilation unit \'" + cusToDelete[0].getElementName() + "\' contains no types. \nOK to delete it as well?";
else
message= "After the delete operation " + cusToDelete.length + " compilation units contain no types. \nOK to delete them as well?";
return MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), ReorgMessages.getString("DeleteSourceReferencesAction.delete1"), message); //$NON-NLS-1$
}
//made protected for ui-less testing
protected boolean confirmGetterSetterDelete() {
String title= ReorgMessages.getString("DeleteSourceReferencesAction.confirm_gs_delete"); //$NON-NLS-1$
String label= ReorgMessages.getString("DeleteSourceReferencesAction.delete_gs"); //$NON-NLS-1$
Shell parent= JavaPlugin.getActiveWorkbenchShell();
return MessageDialog.openQuestion(parent, title, label);
}
}
|
13,301 |
Bug 13301 Next Problem action goes to the previous problem
|
build: 20020409 Next Problem action [CTRL+E] doesn't go to the next problem but to the previous problem, it behaves like Previous Problem action [CTRL+SHIFT+E] (which works fine).
|
resolved fixed
|
173a297
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-11T11:40:13Z | 2002-04-10T14:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/RetargetActionIDs.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.actions;
public class RetargetActionIDs {
// Navigate menu
public static String OPEN= "org.eclipse.jdt.ui.OpenAction";
public static String OPEN_SUPER_IMPLEMENTATION= "org.eclipse.jdt.ui.actions.OpenSuperImplementation";
public static String OPEN_TYPE_HIERARCHY= "org.eclipse.jdt.ui.actions.OpenTypeHierarchy";
public static String OPEN_EXTERNAL_JAVA_DOC= "org.eclipse.jdt.ui.actions.OpenExternalJavaDoc";
public static String SHOW_IN_PACKAGE_VIEW= "org.eclipse.jdt.ui.actions.ShowInPackagesView";
public static String SHOW_IN_NAVIGATOR_VIEW= "org.eclipse.jdt.ui.actions.ShowInNaviagtorView";
public static String SHOW_NEXT_PROBLEM= "org.eclipse.jdt.ui.actions.NextProblem";
public static String SHOW_PREVIOUS_PROBLEM= "org.eclipse.jdt.ui.actions.NextProblem";
// Source menu
public static String CONTENT_ASSIST= "org.eclipse.jdt.ui.actions.ContentAssist";
public static String CORRECTION_ASSIST= "org.eclipse.jdt.ui.actions.CorrectionAssist";
public static String CONTENT_ASSIST_CONTEXT_INFORMATION= "org.eclipse.jdt.ui.actions.ContentAssistContentInformation";
public static String SHOW_JAVA_DOC= "org.eclipse.jdt.ui.actions.ShowJavaDoc";
public static String COMMENT= "org.eclipse.jdt.ui.actions.Comment";
public static String UNCOMMENT= "org.eclipse.jdt.ui.actions.Uncomment";
public static String SHIFT_RIGHT= "org.eclipse.jdt.ui.actions.ShiftRight";
public static String SHIFT_LEFT= "org.eclipse.jdt.ui.actions.ShiftLeft";
public static String FORMAT= "org.eclipse.jdt.ui.actions.Format";
public static String ADD_IMPORT= "org.eclipse.jdt.ui.actions.AddImport";
public static String ORGANIZE_IMPORTS= "org.eclipse.jdt.ui.actions.OrganizeInports";
public static String SURROUND_WITH_TRY_CATCH= "org.eclipse.jdt.ui.actions.SurroundWithTryCatch";
public static String OVERRIDE_METHODS= "org.eclipse.jdt.ui.actions.OverrideMethods";
public static String GENERATE_GETTER_SETTER= "org.eclipse.jdt.ui.actions.GenerateGetterSetter";
public static String ADD_CONSTRUCTOR_FROM_SUPERCLASS= "org.eclipse.jdt.ui.actions.AddConstructorFromSuperclass";
public static String ADD_JAVA_DOC_COMMENT= "org.eclipse.jdt.ui.actions.AddJavaDocComment";
public static String FIND_STRINGS_TO_EXTERNALIZE= "org.eclipse.jdt.ui.actions.FindStringsToExternalize";
public static String EXTERNALIZE_STRINGS= "org.eclipse.jdt.ui.actions.ExternalizeStrings";
// Expand selection menu
public static String SELECT_ENCLOSING_ELEMENT= "org.eclipse.jdt.ui.actions.SelectEnclosingElement";
public static String SELECT_NEXT_ELEMENT= "org.eclipse.jdt.ui.actions.SelectNextElement";
public static String SELECT_PREVIOUS_ELEMENT= "org.eclipse.jdt.ui.actions.SelectPreviousElement";
public static String RESTORE_LAST_SELECTION= "org.eclipse.jdt.ui.actions.RestoreLastSelection";
}
|
13,161 |
Bug 13161 Javadoc wizard: Message on Export wizard page not conforming to others
|
Build 20020409 All other export operations tell the user what the wizard does. Javadoc wizard says that it's a wizard ("Javadoc Generation Wizard"). It should tell the user what it is going to do.
|
resolved fixed
|
a23dfd9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-11T11:54:34Z | 2002-04-10T09:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocTreeWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.javadocexport;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
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.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.core.JavaProject;
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.jarpackager.CheckboxTreeAndListGroup;
import org.eclipse.jdt.internal.ui.javadocexport.JavadocWizardPage.EnableSelectionAdapter;
import org.eclipse.jdt.internal.ui.preferences.JavadocPreferencePage;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
public class JavadocTreeWizardPage extends JavadocWizardPage {
private JavadocProjectContentProvider fProjectContentProvider;
private JavaElementLabelProvider fProjectLabelProvider;
private CheckboxTreeAndListGroup fInputGroup;
protected IWorkspaceRoot fRoot;
protected String fWorkspace;
private final String DOCUMENT_DIRECTORY= "doc"; //$NON-NLS-1$
private File fTempFile;
//private JavadocTreeViewerFilter fFilter;
protected Text fDestinationText;
protected Text fDocletText;
protected Text fDocletTypeText;
protected Button fStandardButton;
protected Button fDestinationBrowserButton;
protected Button fCustomButton;
protected Button fPrivateVisibility;
protected Button fProtectedVisibility;
protected Button fPackageVisibility;
protected Button fPublicVisibility;
private Label fDocletLabel;
private Label fDocletTypeLabel;
private Label fDestinationLabel;
private String fDialogSectionName;
protected String fVisibilitySelection;
protected boolean docletselected;
private JavadocOptionsManager fStore;
private List resources;
protected StatusInfo fDestinationStatus;
protected StatusInfo fDocletStatus;
protected StatusInfo fTreeStatus;
protected StatusInfo fPreferenceStatus;
protected StatusInfo fWizardStatus;
private final int PREFERENCESTATUS= 0;
private final int CUSTOMSTATUS= 1;
private final int STANDARDSTATUS= 2;
private final int TREESTATUS= 3;
/**
* Constructor for JavadocTreeWizardPage.
* @param pageName
*/
protected JavadocTreeWizardPage(String pageName, JavadocOptionsManager store) {
super(pageName);
setDescription(JavadocExportMessages.getString("JavadocTreeWizardPage.javadoctreewizardpage.description")); //$NON-NLS-1$
fStore= store;
// Status variables
fDestinationStatus= new StatusInfo();
fDocletStatus= new StatusInfo();
fTreeStatus= new StatusInfo();
fPreferenceStatus= new StatusInfo();
fWizardStatus= store.getWizardStatus();
}
/*
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NONE);
GridLayout compositeGridLayout= new GridLayout();
composite.setLayoutData(createGridData(GridData.FILL_BOTH, 0, 0));
compositeGridLayout.numColumns= 6;
composite.setLayout(compositeGridLayout);
createInputGroup(composite);
createVisibilitySet(composite);
createOptionsSet(composite);
setControl(composite);
}
protected void createInputGroup(Composite composite) {
Label treeLabel= createLabel(composite, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.checkboxtreeandlistgroup.label"), createGridData(6)); //$NON-NLS-1$
Composite c= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 1;
layout.makeColumnsEqualWidth= true;
c.setLayout(layout);
c.setLayoutData(createGridData(GridData.FILL_BOTH, 6, 0));
ITreeContentProvider treeContentProvider= new JavadocProjectContentProvider();
ITreeContentProvider listContentProvider= new JavadocMemberContentProvider();
fInputGroup=
new CheckboxTreeAndListGroup(
c,
fStore.getRoot(),
treeContentProvider,
new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT),
listContentProvider,
new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT),
SWT.NONE,
convertWidthInCharsToPixels(60),
convertHeightInCharsToPixels(10));
fInputGroup.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent e) {
doValidation(TREESTATUS);
}
});
//fFilter= new JavadocTreeViewerFilter();
//fInputGroup.getTableViewer().addFilter(fFilter);
try {
setTreeChecked(fStore.getPackagenames().toArray(), fStore.getJavaProject());
} catch(JavaModelException e) {
JavaPlugin.logErrorMessage(e.getMessage());
}
if (fStore.getJavaProject() != null) {
fInputGroup.expandTreeToLevel(fStore.getJavaProject(), 4);
}
fInputGroup.aboutToOpen();
}
private void createVisibilitySet(Composite composite) {
GridLayout visibilityLayout= createGridLayout(4);
visibilityLayout.marginHeight= 0;
visibilityLayout.marginWidth= 0;
Composite visibilityGroup= new Composite(composite, SWT.NONE);
visibilityGroup.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 6, 0));
visibilityGroup.setLayout(visibilityLayout);
Label visibilityLabel= createLabel(visibilityGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.visibilitygroup.label"), createGridData(GridData.FILL_HORIZONTAL, 4, 0)); //$NON-NLS-1$
fPrivateVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.privatebutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$
fPackageVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.packagebutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$
fProtectedVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.protectedbutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$
fPublicVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.publicbutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$
fPrivateVisibility.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (((Button) e.widget).getSelection()) {
fVisibilitySelection = fStore.PRIVATE;
//fFilter.setVisibility(fVisibilitySelection);
//fInputGroup.refresh();
}
}
});
fPackageVisibility.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (((Button) e.widget).getSelection()) {
fVisibilitySelection = fStore.PACKAGE;
//fFilter.setVisibility(fVisibilitySelection);
//fInputGroup.refresh();
}
}
});
fProtectedVisibility.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (((Button) e.widget).getSelection()) {
fVisibilitySelection = fStore.PROTECTED;
//fFilter.setVisibility(fVisibilitySelection);
//fInputGroup.refresh();
}
}
});
fPublicVisibility.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (((Button) e.widget).getSelection()) {
fVisibilitySelection = fStore.PUBLIC;
//fFilter.setVisibility(fVisibilitySelection);
//fInputGroup.refresh();
}
}
});
setVisibilitySettings();
}
protected void setVisibilitySettings() {
fVisibilitySelection = fStore.getAccess();
fPrivateVisibility.setSelection(
fVisibilitySelection.equals(fStore.PRIVATE));
fProtectedVisibility.setSelection(
fVisibilitySelection.equals(fStore.PROTECTED));
fPackageVisibility.setSelection(
fVisibilitySelection.equals(fStore.PACKAGE));
fPublicVisibility.setSelection(
fVisibilitySelection.equals(fStore.PUBLIC));
//fFilter.setVisibility(fVisibilitySelection);
}
private void createOptionsSet(Composite composite) {
GridLayout optionSetLayout= createGridLayout(3);
optionSetLayout.marginHeight= 0;
optionSetLayout.marginWidth= 0;
Composite optionSetGroup= new Composite(composite, SWT.NONE);
optionSetGroup.setLayoutData(createGridData(GridData.FILL_BOTH, 6, 0));
optionSetGroup.setLayout(optionSetLayout);
fStandardButton= createButton(optionSetGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.standarddocletbutton.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 3, 0)); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 1;
fDestinationLabel= createLabel(optionSetGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.destinationfield.label"), createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1, convertWidthInCharsToPixels(3))); //$NON-NLS-1$
fDestinationText= createText(optionSetGroup, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0));
fDestinationText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation(STANDARDSTATUS);
}
});
fDestinationBrowserButton= createButton(optionSetGroup, SWT.PUSH, JavadocExportMessages.getString("JavadocTreeWizardPage.destinationbrowse.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, 0)); //$NON-NLS-1$
SWTUtil.setButtonDimensionHint(fDestinationBrowserButton);
//Option to use custom doclet
fCustomButton= createButton(optionSetGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.customdocletbutton.label"), createGridData(3)); //$NON-NLS-1$
//For Entering location of custom doclet
fDocletTypeLabel= createLabel(optionSetGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.docletnamefield.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, convertWidthInCharsToPixels(3))); //$NON-NLS-1$
fDocletTypeText= createText(optionSetGroup, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL, 2, 0));
fDocletTypeText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation(CUSTOMSTATUS);
}
});
fDocletLabel= createLabel(optionSetGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.docletpathfield.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, convertWidthInCharsToPixels(3))); //$NON-NLS-1$
fDocletText= createText(optionSetGroup, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL, 2, 0));
fDocletText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation(CUSTOMSTATUS);
}
});
//Add Listeners
fCustomButton.addSelectionListener(
new EnableSelectionAdapter(new Control[] { fDocletLabel, fDocletText, fDocletTypeLabel, fDocletTypeText }, new Control[] { fDestinationLabel, fDestinationText, fDestinationBrowserButton }));
fCustomButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
doValidation(CUSTOMSTATUS);
}
});
fStandardButton.addSelectionListener(
new EnableSelectionAdapter(new Control[] { fDestinationLabel, fDestinationText, fDestinationBrowserButton }, new Control[] { fDocletLabel, fDocletText, fDocletTypeLabel, fDocletTypeText }));
fStandardButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
doValidation(STANDARDSTATUS);
}
});
fDestinationBrowserButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
String text= handleFolderBrowseButtonPressed(
fDestinationText.getText(), fDestinationText.getShell(),
JavadocExportMessages.getString("JavadocTreeWizardPage.destinationbrowsedialog.title"), //$NON-NLS-1$
JavadocExportMessages.getString("JavadocTreeWizardPage.destinationbrowsedialog.label")); //$NON-NLS-1$
fDestinationText.setText(text);
}
});
setOptionSetSettings();
}
public boolean getCustom(){
return fCustomButton.getSelection();
}
private String getDestinationText() {
Object[] els= fInputGroup.getAllCheckedTreeItems().toArray();
try {
for (int i= 0; i < els.length; i++) {
if (els[i] instanceof IJavaProject) {
IJavaProject iJavaProject= (IJavaProject) els[i];
return iJavaProject.getUnderlyingResource().getLocation().addTrailingSeparator().append(DOCUMENT_DIRECTORY).toOSString();
}
}
} catch (JavaModelException e) {
return ""; //$NON-NLS-1$
} catch (NullPointerException e) {
return ""; //$NON-NLS-1$
}
return ""; //$NON-NLS-1$
}
private void setOptionSetSettings() {
if(!fStore.fromStandard()) {
fCustomButton.setSelection(true);
fDocletText.setText(fStore.getDocletPath());
fDocletTypeText.setText(fStore.getDocletName());
fDestinationText.setText(fStore.getDestination());
fDestinationText.setEnabled(false);
fDestinationBrowserButton.setEnabled(false);
fDestinationLabel.setEnabled(false);
} else {
fStandardButton.setSelection(true);
fDestinationText.setText(fStore.getDestination());
fDocletText.setText(fStore.getDocletPath());
fDocletTypeText.setText(fStore.getDocletName());
fDocletText.setEnabled(false);
fDocletLabel.setEnabled(false);
fDocletTypeText.setEnabled(false);
fDocletTypeLabel.setEnabled(false);
}
}
protected void setTreeChecked(Object[] packagenames, IJavaProject project) throws JavaModelException{
if(project==null)
return;
for (int i = 0; i < packagenames.length; i++) {
if(packagenames[i] instanceof IJavaElement) {
IJavaElement element = (IJavaElement)packagenames[i];
if (element instanceof ICompilationUnit) {
fInputGroup.initialCheckListItem(element);
} else
fInputGroup.initialCheckTreeItem(element);
}
}
}
private String getSourcePath(IJavaProject project) {
StringBuffer buf= new StringBuffer();
try {
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
int nAdded= 0;
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot curr= roots[i];
if (curr.getKind() == IPackageFragmentRoot.K_SOURCE) {
if (nAdded != 0) {
buf.append(File.pathSeparatorChar);
}
buf.append(curr.getUnderlyingResource().getLocation().toOSString());
nAdded++;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return buf.toString();
}
private String getClassPath(IJavaProject javaProject) {
StringBuffer buf= new StringBuffer();
try {
IPath outputLocation= javaProject.getProject().getLocation().append(javaProject.getOutputLocation());
String[] classPath= JavaRuntime.computeDefaultRuntimeClassPath(javaProject);
int nAdded= 0;
for (int i= 0; i < classPath.length; i++) {
String curr= classPath[i];
if (outputLocation.equals(new Path(curr))) {
continue;
}
if (nAdded != 0) {
buf.append(File.pathSeparatorChar);
}
buf.append(curr);
nAdded++;
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return buf.toString();
}
//Returns the path were the doclet file will be created
private List getPackagenames() {
Iterator checkedElements= fInputGroup.getAllCheckedListItems();
List list= new ArrayList();
this.resources= new ArrayList();
while (checkedElements.hasNext()) {
Object element = checkedElements.next();
if (element instanceof ICompilationUnit) {
ICompilationUnit unit = (ICompilationUnit) element;
IJavaElement el = unit.getParent();
if (el instanceof IPackageFragment) {
IPackageFragment pack= (IPackageFragment)el;
if (fInputGroup.isTreeItemGreyChecked(pack) || pack.isDefaultPackage()) {
try {
IResource re = unit.getCorrespondingResource();
//Create a list of resources for which Javadoc will be generated
this.resources.add(re);
IPath p = re.getLocation();
String qn = p.toOSString();
list.add(qn);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
}
}
}
Object[] checkedTreeElements= fInputGroup.getAllCheckedTreeItems().toArray();
for (int i= 0; i < checkedTreeElements.length; i++) {
Object element= checkedTreeElements[i];
if (element instanceof IPackageFragment) {
IPackageFragment pack= (IPackageFragment) element;
if (!fInputGroup.isTreeItemGreyChecked(pack) && !pack.isDefaultPackage()) {
try {
ICompilationUnit[] units= pack.getCompilationUnits();
for (int j = 0; j < units.length; j++) {
ICompilationUnit un= units[j];
IResource re= un.getCorrespondingResource();
resources.add(re);
}
} catch(JavaModelException e) {
JavaPlugin.log(e);
}
String en= pack.getElementName();
list.add(en);
}
}
}
return list;
}
protected void finish() {
//I have made the assumption that preserve settings will not be
//called on an ANT file, which is evident...
if (fCustomButton.getSelection()) {
fStore.setDocletName(fDocletTypeText.getText());
fStore.setDocletPath(fDocletText.getText());
fStore.setFromStandard(false);
}
if(fStandardButton.getSelection()){
fStore.setFromStandard(true);
fStore.setDestination(fDestinationText.getText());
}
IJavaProject project= getCurrentProject();
fStore.setProject(project);
fStore.setSourcepath(getSourcePath(project));
fStore.setClasspath(getClassPath(project));
fStore.setAccess(fVisibilitySelection);
fStore.setPackagenames(getPackagenames());
}
private void doValidation(int validate) {
switch (validate) {
case PREFERENCESTATUS :
fPreferenceStatus = new StatusInfo();
fDocletStatus= new StatusInfo();
if (JavadocPreferencePage.getJavaDocCommand().length() == 0) {
fPreferenceStatus.setError(
JavadocExportMessages.getString("JavadocTreeWizardPage.javadoccommand.error")); //$NON-NLS-1$
}
updateStatus(findMostSevereStatus());
break;
case CUSTOMSTATUS :
if (fCustomButton.getSelection()) {
fDestinationStatus = new StatusInfo();
fDocletStatus = new StatusInfo();
String doclet = fDocletTypeText.getText();
String docletPath = fDocletText.getText();
if (doclet.length() == 0) {
fDocletStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.nodocletname.error")); //$NON-NLS-1$
} else if (
JavaConventions.validateJavaTypeName(doclet).matches(IStatus.ERROR)) {
fDocletStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invaliddocletname.error")); //$NON-NLS-1$
} else if ((docletPath.length() == 0) || !validDocletPath(docletPath)) {
fDocletStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invaliddocletpath.error")); //$NON-NLS-1$
}
updateStatus(findMostSevereStatus());
}
break;
case STANDARDSTATUS :
if (fStandardButton.getSelection()) {
fDestinationStatus = new StatusInfo();
fDocletStatus= new StatusInfo();
IPath path = new Path(fDestinationText.getText());
if (Path.ROOT.equals(path) || Path.EMPTY.equals(path)) {
fDestinationStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.nodestination.error")); //$NON-NLS-1$
}
File file = new File(path.toOSString());
if (!path.isValidPath(path.toOSString()) || file.isFile()) {
fDestinationStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invaliddestination.error")); //$NON-NLS-1$
}
updateStatus(findMostSevereStatus());
}
break;
case TREESTATUS :
fTreeStatus = new StatusInfo();
boolean empty = fInputGroup.getAllCheckedTreeItems().isEmpty();
if (empty)
fTreeStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invalidtreeselection.error")); //$NON-NLS-1$
else {
int projCount = 0;
Object[] items = fInputGroup.getAllCheckedTreeItems().toArray();
for (int i = 0; i < items.length; i++) {
IJavaElement element = (IJavaElement) items[i];
if (element instanceof IJavaProject) {
projCount++;
if (projCount > 1)
fTreeStatus.setError(
JavadocExportMessages.getString("JavadocTreeWizardPage.multipleprojectselected.error")); //$NON-NLS-1$
}
}
}
updateStatus(findMostSevereStatus());
break;
} //end switch
}
/**
* looks at the currently selected projects and returns the current project
* returns null if more than one project is checked
*/
private IJavaProject getCurrentProject() {
Object[] items= fInputGroup.getAllCheckedTreeItems().toArray();
IJavaProject project= null;
for (int i= 0; i < items.length; i++) {
if (items[i] instanceof JavaProject) {
if (project != null) {
return null;
}
project= (JavaProject)items[i];
}
}
return project;
}
private boolean validDocletPath(String docletPath) {
StringTokenizer tokens= new StringTokenizer(docletPath, ";"); //$NON-NLS-1$
while (tokens.hasMoreTokens()) {
File file= new File(tokens.nextToken());
if (!file.exists())
return false;
}
return true;
}
/**
* Finds the most severe error (if there is one)
*/
private IStatus findMostSevereStatus() {
return StatusUtil.getMostSevere(new IStatus[] {fPreferenceStatus, fDestinationStatus, fDocletStatus, fTreeStatus, fWizardStatus });
}
public void init() {
updateStatus(new StatusInfo());
}
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
doValidation(STANDARDSTATUS);
doValidation(CUSTOMSTATUS);
doValidation(TREESTATUS);
doValidation(PREFERENCESTATUS);
}
}
public IPath getDestination() {
if (fStandardButton.getSelection()) {
return new Path(fDestinationText.getText());
}
return null;
}
public List getResources() {
return resources;
}
} //end Class
|
13,161 |
Bug 13161 Javadoc wizard: Message on Export wizard page not conforming to others
|
Build 20020409 All other export operations tell the user what the wizard does. Javadoc wizard says that it's a wizard ("Javadoc Generation Wizard"). It should tell the user what it is going to do.
|
resolved fixed
|
a23dfd9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-11T11:54:34Z | 2002-04-10T09:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocWizard.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.javadocexport;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
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.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IDebugEventSetListener;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.Launch;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IExportWizard;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbench;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.OpenExternalJavadocAction;
import org.eclipse.jdt.internal.ui.jarpackager.ConfirmSaveModifiedResourcesDialog;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class JavadocWizard extends Wizard implements IExportWizard {
private JavadocTreeWizardPage fJTWPage;
private JavadocSpecificsWizardPage fJSWPage;
private IPath fDestination;
private IJavaProject fCurrentProject;
private boolean fWriteCustom;
private boolean fFromAnt;
private boolean fOpenInBrowser;
protected final String TreePageDesc= "JavadocTreePage"; //$NON-NLS-1$
protected final String SpecificsPageDesc= "JavadocSpecificsPage"; //$NON-NLS-1$
private JavadocOptionsManager fStore;
private IWorkspaceRoot fRoot;
private IFile fXmlJavadocFile;
//private ILaunchConfiguration fConfig;
public JavadocWizard() {
this(null);
}
public JavadocWizard(IFile xmlJavadocFile) {
super();
setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_REFACTOR);
setWindowTitle(JavadocExportMessages.getString("JavadocWizard.javadocwizard.title")); //$NON-NLS-1$
setDialogSettings(JavaPlugin.getDefault().getDialogSettings());
fRoot= ResourcesPlugin.getWorkspace().getRoot();
fXmlJavadocFile= xmlJavadocFile;
fCurrentProject= null;
fWriteCustom= false;
fFromAnt= (xmlJavadocFile != null);
}
/*
* @see IWizard#performFinish()
*/
public boolean performFinish() {
//writes the new settings to store
fJTWPage.finish();
fJSWPage.finish();
if (!checkPreconditions(fJTWPage.getResources())) {
return false;
}
fDestination= new Path(fStore.getDestination());
fDestination.toFile().mkdirs();
if (fJSWPage.openInBrowser()) {
this.fOpenInBrowser= true;
}
try {
URL currURL= JavaDocLocations.getProjectJavadocLocation(fStore.getJavaProject());
URL newURL= fDestination.toFile().toURL();
if (fStore.fromStandard() && ((currURL == null) || !(currURL.equals(newURL)))) {
String message= JavadocExportMessages.getString("JavadocWizard.updatejavadoclocation.message"); //$NON-NLS-1$
if (MessageDialog.openQuestion(getShell(), JavadocExportMessages.getString("JavadocWizard.updatejavadocdialog.label"), MessageFormat.format(message, new String[] { fStore.getJavaProject().getElementName(), fStore.getDestination() }))) { //$NON-NLS-1$
JavaDocLocations.setProjectJavadocLocation(fStore.getJavaProject(), newURL);
}
}
} catch (MalformedURLException e) {
JavaPlugin.log(e);
}
if (fJSWPage.generateAnt()) {
fStore.createXML();
refresh(new Path(fStore.getAntpath()));
}
if (!fFromAnt) {
getDialogSettings().addSection(fStore.createDialogSettings());
}
String[] args= fStore.createArgumentArray();
if (!executeJavadocGeneration(args))
return false;
return true;
}
private boolean executeJavadocGeneration(String[] args) {
Process process= null;
try {
process= Runtime.getRuntime().exec(args);
if (process != null) {
// contruct a formatted command line for the process properties
StringBuffer buf= new StringBuffer();
for (int i= 0; i < args.length; i++) {
buf.append(args[i]);
buf.append(' ');
}
IDebugEventSetListener listener= new JavadocDebugEventListener();
DebugPlugin.getDefault().addDebugEventListener(listener);
ILaunchConfigurationWorkingCopy wc= null;
try {
ILaunchConfigurationType lcType= DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION);
String name= "Javadoc Export Wizard";// + System.currentTimeMillis(); //$NON-NLS-1$
wc= lcType.newInstance(null, name);
wc.setAttribute(IDebugUIConstants.ATTR_TARGET_RUN_PERSPECTIVE, (String) null);
wc.setAttribute(IDebugUIConstants.ATTR_PRIVATE, true);
ILaunch newLaunch= new Launch(wc, ILaunchManager.RUN_MODE, null);
IProcess iprocess= DebugPlugin.newProcess(newLaunch, process, JavadocExportMessages.getString("JavadocWizard.javadocprocess.label")); //$NON-NLS-1$
iprocess.setAttribute(JavaRuntime.ATTR_CMDLINE, buf.toString());
DebugPlugin.getDefault().getLaunchManager().addLaunch(newLaunch);
} catch (CoreException e) {
JavaPlugin.logErrorMessage(e.getMessage());
}
return true;
}
} catch (IOException e) {
JavaPlugin.log(e);
return false;
}
return false;
}
private boolean checkPreconditions(List resources) {
//message could be null
IFile[] unSavedFiles = getUnsavedFiles(resources);
return saveModifiedResourcesIfUserConfirms(unSavedFiles);
}
/**
* Returns the files which are not saved and which are
* part of the files being exported.
*
* @return an array of unsaved files
*/
private IFile[] getUnsavedFiles(List resources) {
IEditorPart[] dirtyEditors = JavaPlugin.getDirtyEditors();
Set unsavedFiles = new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
for (int i = 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile =
((IFileEditorInput) dirtyEditors[i].getEditorInput()).getFile();
if (resources.contains(dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[]) unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed. Must be run in the display thread.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles)) {
try {
if (saveModifiedResources(dirtyFiles))
return true;
} catch(CoreException e) {
ExceptionHandler.handle(e, getShell(), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogCE.title"), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogCE.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch(InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogITE.title"), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogITE.message")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
return false;
}
/**
* Asks the user to confirm to save the modified resources.
*
* @return true if user pressed OK.
*/
private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) {
if (dirtyFiles == null || dirtyFiles.length == 0)
return true;
// Get display for further UI operations
Display display= getShell().getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(getShell(), dirtyFiles);
final int[] intResult= new int[1];
Runnable runnable= new Runnable() {
public void run() {
intResult[0]= dlg.open();
}
};
display.syncExec(runnable);
return intResult[0] == IDialogConstants.OK_ID;
}
/**
* Save all of the editors in the workbench. Must be run in the display thread.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) throws CoreException, InvocationTargetException {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IWorkspaceDescription description= workspace.getDescription();
boolean autoBuild= description.isAutoBuilding();
description.setAutoBuilding(false);
try {
workspace.setDescription(description);
// This save operation can not be canceled.
try {
new ProgressMonitorDialog(getShell()).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
} finally {
description.setAutoBuilding(autoBuild);
workspace.setDescription(description);
}
} catch (InterruptedException ex) {
return false;
}
return true;
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= JavaPlugin.getDirtyEditors();
pm.beginTask("Saving modified resources", editorsToSave.length); //$NON-NLS-1$
try {
List dirtyFilesList= Arrays.asList(dirtyFiles);
for (int i= 0; i < editorsToSave.length; i++) {
if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)editorsToSave[i].getEditorInput()).getFile();
if (dirtyFilesList.contains((dirtyFile)))
editorsToSave[i].doSave(new SubProgressMonitor(pm, 1));
}
pm.worked(1);
}
} finally {
pm.done();
}
}
};
}
/*
* @see IWizard#addPages()
*/
public void addPages() {
fJTWPage= new JavadocTreeWizardPage(TreePageDesc, fStore);
fJSWPage= new JavadocSpecificsWizardPage(SpecificsPageDesc, fStore, fJTWPage);
super.addPage(fJTWPage);
super.addPage(fJSWPage);
fJTWPage.init();
fJSWPage.init();
}
public void init(IWorkbench workbench, IStructuredSelection structuredSelection) {
IDialogSettings settings= getDialogSettings();
if (fXmlJavadocFile == null) {
fStore= new JavadocOptionsManager(settings.getSection("javadoc"), fRoot, structuredSelection); //$NON-NLS-1$
} else {
fStore= new JavadocOptionsManager(fXmlJavadocFile, settings, fRoot, structuredSelection);
}
}
private void refresh(IPath path) {
if (fRoot.getContainerForLocation(path) != null) {
try {
fRoot.refreshLocal(fJTWPage.fRoot.DEPTH_INFINITE, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
private void spawnInBrowser() {
if (fOpenInBrowser) {
try {
IPath indexFile= fDestination.append("index.html"); //$NON-NLS-1$
URL url= indexFile.toFile().toURL();
OpenExternalJavadocAction.openInBrowser(url, getShell());
} catch (MalformedURLException e) {
JavaPlugin.log(e);
}
}
}
private class JavadocDebugEventListener implements IDebugEventSetListener {
public void handleDebugEvents(DebugEvent[] events) {
for (int i= 0; i < events.length; i++) {
if (events[i].getKind() == DebugEvent.TERMINATE) {
try {
if (!fWriteCustom) {
refresh(fDestination); //If destination of javadoc is in workspace then refresh workspace
spawnInBrowser();
}
} finally {
DebugPlugin.getDefault().removeDebugEventListener(this);
}
return;
}
}
}
}
}
|
13,226 |
Bug 13226 Quick Fix: unclear why nothing gets proposed
|
Build 20020409 - create CU public class QuickFixTest { public static class TT { } public void foo(TTT t) { } } - try to quick fix foo(TTT t) All you get is the bell. This is surprising since foo(String2 s) can be fixed.
|
resolved fixed
|
dabb5f0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-11T15:26:23Z | 2002-04-10T12:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectPackageDeclarationProposal.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 org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
import org.eclipse.jdt.internal.corext.textmanipulation.SimpleTextEdit;
import org.eclipse.jdt.internal.ui.JavaPlugin;
public class CorrectPackageDeclarationProposal extends CUCorrectionProposal {
private ProblemPosition fProblemPosition;
public CorrectPackageDeclarationProposal(ProblemPosition problemPos, int relevance) throws CoreException {
super(CorrectionMessages.getString("CorrectPackageDeclarationProposal.name"), problemPos.getCompilationUnit(), relevance); //$NON-NLS-1$
fProblemPosition= problemPos;
}
/*
* @see CUCorrectionProposal#addEdits(CompilationUnitChange)
*/
protected void addEdits(CompilationUnitChange change) throws CoreException {
ICompilationUnit cu= change.getCompilationUnit();
IPackageFragment parentPack= (IPackageFragment) cu.getParent();
IPackageDeclaration[] decls= cu.getPackageDeclarations();
if (parentPack.isDefaultPackage() && decls.length > 0) {
for (int i= 0; i < decls.length; i++) {
ISourceRange range= decls[i].getSourceRange();
change.addTextEdit(CorrectionMessages.getString("CorrectPackageDeclarationProposal.removeedit.label"), SimpleTextEdit.createDelete(range.getOffset(), range.getLength())); //$NON-NLS-1$
}
return;
}
if (!parentPack.isDefaultPackage() && decls.length == 0) {
String lineDelim= StubUtility.getLineDelimiterUsed(cu);
String str= "package " + parentPack.getElementName() + ";" + lineDelim + lineDelim; //$NON-NLS-1$ //$NON-NLS-2$
change.addTextEdit(CorrectionMessages.getString("CorrectPackageDeclarationProposal.addedit.label"), SimpleTextEdit.createInsert(0, str)); //$NON-NLS-1$
return;
}
ProblemPosition pos= fProblemPosition;
change.addTextEdit(CorrectionMessages.getString("CorrectPackageDeclarationProposal.changenameedit.label"), SimpleTextEdit.createReplace(pos.getOffset(), pos.getLength(), parentPack.getElementName())); //$NON-NLS-1$
}
/*
* @see ICompletionProposal#getDisplayString()
*/
public String getDisplayString() {
ICompilationUnit cu= fProblemPosition.getCompilationUnit();
IPackageFragment parentPack= (IPackageFragment) cu.getParent();
try {
IPackageDeclaration[] decls= cu.getPackageDeclarations();
if (parentPack.isDefaultPackage() && decls.length > 0) {
return CorrectionMessages.getString("CorrectPackageDeclarationProposal.remove.description") + decls[0].getElementName() + ";'"; //$NON-NLS-1$ //$NON-NLS-2$
}
if (!parentPack.isDefaultPackage() && decls.length == 0) {
return (CorrectionMessages.getString("CorrectPackageDeclarationProposal.add.description") + parentPack.getElementName() + "'"); //$NON-NLS-1$ //$NON-NLS-2$
}
} catch(JavaModelException e) {
JavaPlugin.log(e);
}
return (CorrectionMessages.getString("CorrectPackageDeclarationProposal.change.description") + parentPack.getElementName() + "'"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
|
13,226 |
Bug 13226 Quick Fix: unclear why nothing gets proposed
|
Build 20020409 - create CU public class QuickFixTest { public static class TT { } public void foo(TTT t) { } } - try to quick fix foo(TTT t) All you get is the bell. This is surprising since foo(String2 s) can be fixed.
|
resolved fixed
|
dabb5f0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-11T15:26:23Z | 2002-04-10T12:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavaCorrectionProcessor.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.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.IProblemAnnotation;
import org.eclipse.jdt.internal.ui.javaeditor.ProblemAnnotationIterator;
public class JavaCorrectionProcessor implements IContentAssistProcessor {
public static boolean hasCorrections(int problemId) {
switch (problemId) {
case IProblem.UnterminatedString:
case IProblem.UnterminatedComment:
case IProblem.UndefinedMethod:
case IProblem.UndefinedField:
case IProblem.UndefinedName:
case IProblem.PublicClassMustMatchFileName:
case IProblem.PackageIsNotExpectedPackage:
case IProblem.UndefinedType:
case IProblem.FieldTypeNotFound:
case IProblem.ArgumentTypeNotFound:
case IProblem.ReturnTypeNotFound:
case IProblem.SuperclassNotFound:
case IProblem.ExceptionTypeNotFound:
case IProblem.InterfaceNotFound:
case IProblem.TypeMismatch:
return true;
default:
return false;
}
}
private static class CorrectionsComparator implements Comparator {
private static Collator fgCollator= Collator.getInstance();
public int compare(Object o1, Object o2) {
ChangeCorrectionProposal e1= (ChangeCorrectionProposal) o1;
ChangeCorrectionProposal e2= (ChangeCorrectionProposal) o2;
int del= e2.getRelevance() - e1.getRelevance();
if (del != 0) {
return del;
}
return fgCollator.compare(e1.getDisplayString(), e2.getDisplayString());
}
}
private IEditorPart fEditor;
/**
* Constructor for JavaCorrectionProcessor.
*/
public JavaCorrectionProcessor(IEditorPart editor) {
fEditor= editor;
}
/*
* @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int)
*/
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit cu= manager.getWorkingCopy(fEditor.getEditorInput());
IDocumentProvider provider= JavaPlugin.getDefault().getCompilationUnitDocumentProvider();
IAnnotationModel model= provider.getAnnotationModel(fEditor.getEditorInput());
ArrayList proposals= new ArrayList();
HashSet idsProcessed= new HashSet();
for (Iterator iter= new ProblemAnnotationIterator(model); iter.hasNext();) {
IProblemAnnotation annot= (IProblemAnnotation) iter.next();
Position pos= model.getPosition((Annotation) annot);
ProblemPosition pp = new ProblemPosition(pos, annot, cu);
int start= pp.getOffset();
if (documentOffset >= start && documentOffset <= (start + pp.getLength())) {
Integer probId= new Integer(annot.getId());
if (!idsProcessed.contains(probId)) {
idsProcessed.add(probId);
collectCorrections(pp, proposals);
}
}
}
if (proposals.isEmpty()) {
return null;
}
ICompletionProposal[] res= (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]);
Arrays.sort(res, new CorrectionsComparator());
return res;
}
private void collectCorrections(ProblemPosition problemPos, ArrayList proposals) {
try {
int id= problemPos.getId();
switch (id) {
case IProblem.UnterminatedString:
int pos= InsertCorrectionProposal.moveBack(problemPos.getOffset() + problemPos.getLength(), problemPos.getOffset(), "\n\r", problemPos.getCompilationUnit()); //$NON-NLS-1$
proposals.add(new InsertCorrectionProposal(problemPos, CorrectionMessages.getString("JavaCorrectionProcessor.addquote.description"), pos, "\"", 0)); //$NON-NLS-1$ //$NON-NLS-2$
break;
case IProblem.UnterminatedComment:
proposals.add(new InsertCorrectionProposal(problemPos, CorrectionMessages.getString("JavaCorrectionProcessor.addcomment.description"), problemPos.getOffset() + problemPos.getLength(), "*/", 0)); //$NON-NLS-1$ //$NON-NLS-2$
break;
case IProblem.UndefinedMethod:
UnresolvedElementsSubProcessor.getMethodProposals(problemPos, proposals);
break;
case IProblem.UndefinedField:
case IProblem.UndefinedName:
UnresolvedElementsSubProcessor.getVariableProposals(problemPos, proposals);
break;
case IProblem.PublicClassMustMatchFileName:
ReorgCorrectionsSubProcessor.getWrongTypeNameProposals(problemPos, proposals);
break;
case IProblem.PackageIsNotExpectedPackage:
ReorgCorrectionsSubProcessor.getWrongPackageDeclNameProposals(problemPos, proposals);
break;
case IProblem.UndefinedType:
case IProblem.FieldTypeNotFound:
case IProblem.ArgumentTypeNotFound:
case IProblem.ReturnTypeNotFound:
UnresolvedElementsSubProcessor.getTypeProposals(problemPos, SimilarElementsRequestor.TYPES, proposals);
break;
case IProblem.SuperclassNotFound:
case IProblem.ExceptionTypeNotFound:
UnresolvedElementsSubProcessor.getTypeProposals(problemPos, SimilarElementsRequestor.CLASSES, proposals);
break;
case IProblem.InterfaceNotFound:
UnresolvedElementsSubProcessor.getTypeProposals(problemPos, SimilarElementsRequestor.INTERFACES, proposals);
break;
case IProblem.TypeMismatch:
ReorgCorrectionsSubProcessor.addCastProposal(problemPos, proposals);
break;
default:
//proposals.add(new NoCorrectionProposal(problemPos));
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
/*
* @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
*/
public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
return null;
}
/*
* @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
*/
public char[] getCompletionProposalAutoActivationCharacters() {
return null;
}
/*
* @see IContentAssistProcessor#getContextInformationAutoActivationCharacters()
*/
public char[] getContextInformationAutoActivationCharacters() {
return null;
}
/*
* @see IContentAssistProcessor#getContextInformationValidator()
*/
public IContextInformationValidator getContextInformationValidator() {
return null;
}
/*
* @see IContentAssistProcessor#getErrorMessage()
*/
public String getErrorMessage() {
return null;
}
}
|
13,226 |
Bug 13226 Quick Fix: unclear why nothing gets proposed
|
Build 20020409 - create CU public class QuickFixTest { public static class TT { } public void foo(TTT t) { } } - try to quick fix foo(TTT t) All you get is the bell. This is surprising since foo(String2 s) can be fixed.
|
resolved fixed
|
dabb5f0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-11T15:26:23Z | 2002-04-10T12:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NoCorrectionProposal.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 org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.corext.refactoring.NullChange;
public class NoCorrectionProposal extends ChangeCorrectionProposal {
private ProblemPosition fProblemPosition;
public NoCorrectionProposal(ProblemPosition problemPosition) {
super("No correction available", new NullChange(), 0);
fProblemPosition= problemPosition;
}
/*
* @see ICompletionProposal#getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo() {
StringBuffer buf= new StringBuffer();
buf.append("<p><b>"); //$NON-NLS-1$
buf.append(getErrorCode(fProblemPosition.getId()));
buf.append("</b></p>"); //$NON-NLS-1$
buf.append("<p>"); //$NON-NLS-1$
buf.append(fProblemPosition.getMessage());
buf.append("</p>"); //$NON-NLS-1$
String[] arg= fProblemPosition.getArguments();
if (arg != null) {
for (int i= 0; i < arg.length; i++) {
buf.append("<p>"); //$NON-NLS-1$
buf.append(arg[i]);
buf.append("</p>"); //$NON-NLS-1$
}
}
return buf.toString();
}
private String getErrorCode(int code) {
StringBuffer buf= new StringBuffer();
if ((code & IProblem.TypeRelated) != 0) {
buf.append("TypeRelated + "); //$NON-NLS-1$
}
if ((code & IProblem.FieldRelated) != 0) {
buf.append("FieldRelated + "); //$NON-NLS-1$
}
if ((code & IProblem.ConstructorRelated) != 0) {
buf.append("ConstructorRelated + "); //$NON-NLS-1$
}
if ((code & IProblem.MethodRelated) != 0) {
buf.append("MethodRelated + "); //$NON-NLS-1$
}
if ((code & IProblem.ImportRelated) != 0) {
buf.append("ImportRelated + "); //$NON-NLS-1$
}
if ((code & IProblem.Internal) != 0) {
buf.append("Internal + "); //$NON-NLS-1$
}
if ((code & IProblem.Syntax) != 0) {
buf.append("Syntax + "); //$NON-NLS-1$
}
buf.append(code & IProblem.IgnoreCategoriesMask);
return buf.toString();
}
}
|
13,066 |
Bug 13066 Mainfest File Corrupt
|
Hello! I have been trying to export my code, specifying a manifest, into a jar file. However, my manifest file is not placed in the jar. A blank manifest file is inserted instead. I go to File->Export->Jar file I select my project, mark "export generated class files and resources", specify the jar name and check the "compress jar" option. <Next> I check "Save a description of this jar file in the workspace" <Next> I mark, "Use existing manifest from the workspace" and specify the location of my manifest file. <Finish> I couldn't attach my manifest file, but here is it's contents. . . Main-Class: com.sbc.cb.Application Class-Path: . cbhelp.jar jaxb-rt-1.0-ea.jar jhall.jar lumberjack.jar pvjfc60.jar
|
resolved fixed
|
49c27fb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-11T18:40:15Z | 2002-04-09T13:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarManifestWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.ui.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.packageview.EmptyInnerPackageFilter;
import org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.MainMethodSearchEngine;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.viewsupport.LibraryFilter;
/**
* Page 3 of the JAR Package wizard
*/
class JarManifestWizardPage extends WizardPage implements IJarPackageWizardPage {
// Untyped listener
private class UntypedListener implements Listener {
/*
* Implements method from Listener
*/
public void handleEvent(Event e) {
if (getControl() == null)
return;
update();
}
}
private UntypedListener fUntypedListener= new UntypedListener();
// Model
private JarPackageData fJarPackage;
// Cache for main types
private IType[] fMainTypes;
// Widgets
private Composite fManifestGroup;
private Button fGenerateManifestRadioButton;
private Button fSaveManifestCheckbox;
private Button fReuseManifestCheckbox;
private Text fNewManifestFileText;
private Label fNewManifestFileLabel;
private Button fNewManifestFileBrowseButton;
private Button fUseManifestRadioButton;
private Text fManifestFileText;
private Label fManifestFileLabel;
private Button fManifestFileBrowseButton;
private Label fSealingHeaderLabel;
private Button fSealJarRadioButton;
private Label fSealJarLabel;
private Button fSealedPackagesDetailsButton;
private Button fSealPackagesRadioButton;
private Label fSealPackagesLabel;
private Button fUnSealedPackagesDetailsButton;
private Label fMainClassHeaderLabel;
private Label fMainClassLabel;
private Text fMainClassText;
private Button fMainClassBrowseButton;
// Dialog store id constants
private final static String PAGE_NAME= "JarManifestWizardPage"; //$NON-NLS-1$
// Manifest creation
private final static String STORE_GENERATE_MANIFEST= PAGE_NAME + ".GENERATE_MANIFEST"; //$NON-NLS-1$
private final static String STORE_SAVE_MANIFEST= PAGE_NAME + ".SAVE_MANIFEST"; //$NON-NLS-1$
private final static String STORE_REUSE_MANIFEST= PAGE_NAME + ".REUSE_MANIFEST"; //$NON-NLS-1$
private final static String STORE_MANIFEST_LOCATION= PAGE_NAME + ".MANIFEST_LOCATION"; //$NON-NLS-1$
// Sealing
private final static String STORE_SEAL_JAR= PAGE_NAME + ".SEAL_JAR"; //$NON-NLS-1$
/**
* Create an instance of this class
*/
public JarManifestWizardPage(JarPackageData jarPackage) {
super(PAGE_NAME);
setTitle(JarPackagerMessages.getString("JarManifestWizardPage.title")); //$NON-NLS-1$
setDescription(JarPackagerMessages.getString("JarManifestWizardPage.description")); //$NON-NLS-1$
fJarPackage= jarPackage;
}
// ----------- Widget creation -----------
/*
* Method declared on IDialogPage.
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout());
composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
createLabel(composite, JarPackagerMessages.getString("JarManifestWizardPage.manifestSource.label"), false); //$NON-NLS-1$
createManifestGroup(composite);
createSpacer(composite);
fSealingHeaderLabel= createLabel(composite, JarPackagerMessages.getString("JarManifestWizardPage.sealingHeader.label"), false); //$NON-NLS-1$
createSealingGroup(composite);
createSpacer(composite);
fMainClassHeaderLabel= createLabel(composite, JarPackagerMessages.getString("JarManifestWizardPage.mainClassHeader.label"), false); //$NON-NLS-1$
createMainClassGroup(composite);
setEqualButtonSizes();
restoreWidgetValues();
setControl(composite);
update();
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.JARMANIFEST_WIZARD_PAGE);
}
/**
* Create the export options specification widgets.
*
* @param parent org.eclipse.swt.widgets.Composite
*/
protected void createManifestGroup(Composite parent) {
fManifestGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
fManifestGroup.setLayout(layout);
fManifestGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
fGenerateManifestRadioButton= new Button(fManifestGroup, SWT.RADIO | SWT.LEFT);
fGenerateManifestRadioButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.genetateManifest.text")); //$NON-NLS-1$
fGenerateManifestRadioButton.addListener(SWT.Selection, fUntypedListener);
Composite saveOptions= new Composite(fManifestGroup, SWT.NONE);
GridLayout saveOptionsLayout= new GridLayout();
saveOptionsLayout.marginWidth= 0;
saveOptions.setLayout(saveOptionsLayout);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.horizontalIndent=20;
saveOptions.setLayoutData(data);
fSaveManifestCheckbox= new Button(saveOptions, SWT.CHECK | SWT.LEFT);
fSaveManifestCheckbox.setText(JarPackagerMessages.getString("JarManifestWizardPage.saveManifest.text")); //$NON-NLS-1$
fSaveManifestCheckbox.addListener(SWT.MouseUp, fUntypedListener);
fReuseManifestCheckbox= new Button(saveOptions, SWT.CHECK | SWT.LEFT);
fReuseManifestCheckbox.setText(JarPackagerMessages.getString("JarManifestWizardPage.reuseManifest.text")); //$NON-NLS-1$
fReuseManifestCheckbox.addListener(SWT.MouseUp, fUntypedListener);
createNewManifestFileGroup(saveOptions);
fUseManifestRadioButton= new Button(fManifestGroup, SWT.RADIO | SWT.LEFT);
fUseManifestRadioButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.useManifest.text")); //$NON-NLS-1$
fUseManifestRadioButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Composite existingManifestGroup= new Composite(fManifestGroup, SWT.NONE);
GridLayout existingManifestLayout= new GridLayout();
existingManifestLayout.marginWidth= 0;
existingManifestGroup.setLayout(existingManifestLayout);
data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.horizontalIndent=20;
existingManifestGroup.setLayoutData(data);
createManifestFileGroup(existingManifestGroup);
}
protected void createNewManifestFileGroup(Composite parent) {
// destination specification group
Composite manifestFileGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.numColumns= 3;
manifestFileGroup.setLayout(layout);
manifestFileGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
fNewManifestFileLabel= new Label(manifestFileGroup, SWT.NONE);
fNewManifestFileLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.newManifestFile.text")); //$NON-NLS-1$
// entry field
fNewManifestFileText= new Text(manifestFileGroup, SWT.SINGLE | SWT.BORDER);
fNewManifestFileText.addListener(SWT.Modify, fUntypedListener);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.widthHint= convertWidthInCharsToPixels(40);
fNewManifestFileText.setLayoutData(data);
// browse button
fNewManifestFileBrowseButton= new Button(manifestFileGroup, SWT.PUSH);
fNewManifestFileBrowseButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.newManifestFileBrowseButton.text")); //$NON-NLS-1$
fNewManifestFileBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fNewManifestFileBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleNewManifestFileBrowseButtonPressed();
}
});
}
protected void createManifestFileGroup(Composite parent) {
// destination specification group
Composite manifestFileGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
layout.marginWidth= 0;
manifestFileGroup.setLayout(layout);
manifestFileGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
fManifestFileLabel= new Label(manifestFileGroup, SWT.NONE);
fManifestFileLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.manifestFile.text")); //$NON-NLS-1$
// entry field
fManifestFileText= new Text(manifestFileGroup, SWT.SINGLE | SWT.BORDER);
fManifestFileText.addListener(SWT.Modify, fUntypedListener);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.widthHint= convertWidthInCharsToPixels(40);
fManifestFileText.setLayoutData(data);
// browse button
fManifestFileBrowseButton= new Button(manifestFileGroup, SWT.PUSH);
fManifestFileBrowseButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.manifestFileBrowse.text")); //$NON-NLS-1$
fManifestFileBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fManifestFileBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleManifestFileBrowseButtonPressed();
}
});
}
/**
* Creates the JAR sealing specification controls.
*
* @param parent the parent control
*/
protected void createSealingGroup(Composite parent) {
// destination specification group
Composite sealingGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
layout.horizontalSpacing += 3;
sealingGroup.setLayout(layout);
sealingGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
createSealJarGroup(sealingGroup);
createSealPackagesGroup(sealingGroup);
}
/**
* Creates the JAR sealing specification controls to seal the whole JAR.
*
* @param parent the parent control
*/
protected void createSealJarGroup(Composite sealGroup) {
fSealJarRadioButton= new Button(sealGroup, SWT.RADIO);
fSealJarRadioButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.sealJar.text")); //$NON-NLS-1$
fSealJarRadioButton.addListener(SWT.Selection, fUntypedListener);
fSealJarLabel= new Label(sealGroup, SWT.RIGHT);
fSealJarLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
fSealJarLabel.setText(""); //$NON-NLS-1$
fUnSealedPackagesDetailsButton= new Button(sealGroup, SWT.PUSH);
fUnSealedPackagesDetailsButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fUnSealedPackagesDetailsButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.unsealPackagesButton.text")); //$NON-NLS-1$
fUnSealedPackagesDetailsButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleUnSealPackagesDetailsButtonPressed();
}
});
}
/**
* Creates the JAR sealing specification controls to seal packages.
*
* @param parent the parent control
*/
protected void createSealPackagesGroup(Composite sealGroup) {
fSealPackagesRadioButton= new Button(sealGroup, SWT.RADIO);
fSealPackagesRadioButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.sealPackagesButton.text")); //$NON-NLS-1$
fSealPackagesLabel= new Label(sealGroup, SWT.RIGHT);
fSealPackagesLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
fSealPackagesLabel.setText(""); //$NON-NLS-1$
fSealedPackagesDetailsButton= new Button(sealGroup, SWT.PUSH);
fSealedPackagesDetailsButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fSealedPackagesDetailsButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.sealedPackagesDetailsButton.text")); //$NON-NLS-1$
fSealedPackagesDetailsButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleSealPackagesDetailsButtonPressed();
}
});
}
protected void createMainClassGroup(Composite parent) {
// main type group
Composite mainClassGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
mainClassGroup.setLayout(layout);
mainClassGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
fMainClassLabel= new Label(mainClassGroup, SWT.NONE);
fMainClassLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.mainClass.label")); //$NON-NLS-1$
// entry field
fMainClassText= new Text(mainClassGroup, SWT.SINGLE | SWT.BORDER);
fMainClassText.addListener(SWT.Modify, fUntypedListener);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.widthHint= convertWidthInCharsToPixels(40);
fMainClassText.setLayoutData(data);
fMainClassText.addKeyListener(new KeyAdapter() {
/*
* @see KeyListener#keyReleased(KeyEvent)
*/
public void keyReleased(KeyEvent e) {
fJarPackage.setManifestMainClass(findMainMethodByName(fMainClassText.getText()));
update();
}
});
// browse button
fMainClassBrowseButton= new Button(mainClassGroup, SWT.PUSH);
fMainClassBrowseButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.mainClassBrowseButton.text")); //$NON-NLS-1$
fMainClassBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fMainClassBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleMainClassBrowseButtonPressed();
}
});
}
// ----------- Event handlers -----------
private void update() {
updateModel();
updateEnableState();
updatePageCompletion();
}
/**
* Open an appropriate dialog so that the user can specify a manifest
* to save
*/
protected void handleNewManifestFileBrowseButtonPressed() {
// Use Save As dialog to select a new file inside the workspace
SaveAsDialog dialog= new SaveAsDialog(getContainer().getShell());
dialog.create();
dialog.getShell().setText(JarPackagerMessages.getString("JarManifestWizardPage.saveAsDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarManifestWizardPage.saveAsDialog.message")); //$NON-NLS-1$
dialog.setOriginalFile(createFileHandle(fJarPackage.getManifestLocation()));
if (dialog.open() == dialog.OK) {
fJarPackage.setManifestLocation(dialog.getResult());
fNewManifestFileText.setText(dialog.getResult().toString());
}
}
protected void handleManifestFileBrowseButtonPressed() {
ElementTreeSelectionDialog dialog= createWorkspaceFileSelectionDialog(JarPackagerMessages.getString("JarManifestWizardPage.manifestSelectionDialog.title"), JarPackagerMessages.getString("JarManifestWizardPage.manifestSelectionDialog.message")); //$NON-NLS-2$ //$NON-NLS-1$
if (fJarPackage.isManifestAccessible())
dialog.setInitialSelections(new IResource[] {fJarPackage.getManifestFile()});
if (dialog.open() == dialog.OK) {
Object[] resources= dialog.getResult();
if (resources.length != 1)
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.onlyOneManifestMustBeSelected")); //$NON-NLS-1$
else {
setErrorMessage(""); //$NON-NLS-1$
fJarPackage.setManifestLocation(((IResource)resources[0]).getFullPath());
fManifestFileText.setText(fJarPackage.getManifestLocation().toString());
}
}
}
private IType findMainMethodByName(String name) {
if (fMainTypes == null) {
List resources= JarPackagerUtil.asResources(fJarPackage.getElements());
if (resources == null)
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.noResourceSelected")); //$NON-NLS-1$
IJavaSearchScope searchScope= JavaSearchScopeFactory.getInstance().createJavaSearchScope((IResource[])resources.toArray(new IResource[resources.size()]));
MainMethodSearchEngine engine= new MainMethodSearchEngine();
try {
fMainTypes= engine.searchMainMethods(getContainer(), searchScope, 0);
} catch (InvocationTargetException ex) {
// null
} catch (InterruptedException e) {
// null
}
}
for (int i= 0; i < fMainTypes.length; i++) {
if (fMainTypes[i].getFullyQualifiedName().equals(name))
return fMainTypes[i];
}
return null;
}
protected void handleMainClassBrowseButtonPressed() {
List resources= JarPackagerUtil.asResources(fJarPackage.getElements());
if (resources == null) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.noResourceSelected")); //$NON-NLS-1$
return;
}
IJavaSearchScope searchScope= JavaSearchScopeFactory.getInstance().createJavaSearchScope((IResource[])resources.toArray(new IResource[resources.size()]));
SelectionDialog dialog= JavaUI.createMainTypeDialog(getContainer().getShell(), getContainer(), searchScope, 0, false, ""); //$NON-NLS-1$
dialog.setTitle(JarPackagerMessages.getString("JarManifestWizardPage.mainTypeSelectionDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarManifestWizardPage.mainTypeSelectionDialog.message")); //$NON-NLS-1$
if (fJarPackage.getManifestMainClass() != null)
dialog.setInitialSelections(new Object[] {fJarPackage.getManifestMainClass()});
if (dialog.open() == dialog.OK) {
fJarPackage.setManifestMainClass((IType)dialog.getResult()[0]);
fMainClassText.setText(JarPackagerUtil.getMainClassName(fJarPackage));
} else if (!fJarPackage.isMainClassValid(getContainer())) {
// user did not cancel: no types were found
fJarPackage.setManifestMainClass(null);
fMainClassText.setText(JarPackagerUtil.getMainClassName(fJarPackage));
}
}
protected void handleSealPackagesDetailsButtonPressed() {
SelectionDialog dialog= createPackageDialog(getPackagesForSelectedResources(fJarPackage));
dialog.setTitle(JarPackagerMessages.getString("JarManifestWizardPage.sealedPackagesSelectionDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarManifestWizardPage.sealedPackagesSelectionDialog.message")); //$NON-NLS-1$
dialog.setInitialSelections(fJarPackage.getPackagesToSeal());
if (dialog.open() == dialog.OK)
fJarPackage.setPackagesToSeal(getPackagesFromDialog(dialog));
updateSealingInfo();
}
protected void handleUnSealPackagesDetailsButtonPressed() {
SelectionDialog dialog= createPackageDialog(getPackagesForSelectedResources(fJarPackage));
dialog.setTitle(JarPackagerMessages.getString("JarManifestWizardPage.unsealedPackagesSelectionDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarManifestWizardPage.unsealedPackagesSelectionDialog.message")); //$NON-NLS-1$
dialog.setInitialSelections(fJarPackage.getPackagesToUnseal());
if (dialog.open() == dialog.OK)
fJarPackage.setPackagesToUnseal(getPackagesFromDialog(dialog));
updateSealingInfo();
}
/**
* Updates the enable state of this page's controls. Subclasses may extend.
*/
protected void updateEnableState() {
boolean generate= fGenerateManifestRadioButton.getSelection();
boolean save= generate && fSaveManifestCheckbox.getSelection();
fSaveManifestCheckbox.setEnabled(generate);
fReuseManifestCheckbox.setEnabled(fJarPackage.isDescriptionSaved() && save);
fNewManifestFileText.setEnabled(save);
fNewManifestFileLabel.setEnabled(save);
fNewManifestFileBrowseButton.setEnabled(save);
fManifestFileText.setEnabled(!generate);
fManifestFileLabel.setEnabled(!generate);
fManifestFileBrowseButton.setEnabled(!generate);
fSealingHeaderLabel.setEnabled(generate);
boolean sealState= fSealJarRadioButton.getSelection();
fSealJarRadioButton.setEnabled(generate);
fSealJarLabel.setEnabled(generate);
fUnSealedPackagesDetailsButton.setEnabled(sealState && generate);
fSealPackagesRadioButton.setEnabled(generate);
fSealPackagesLabel.setEnabled(generate);
fSealedPackagesDetailsButton.setEnabled(!sealState && generate);
fMainClassHeaderLabel.setEnabled(generate);
fMainClassLabel.setEnabled(generate);
fMainClassText.setEnabled(generate);
fMainClassBrowseButton.setEnabled(generate);
updateSealingInfo();
}
protected void updateSealingInfo() {
if (fJarPackage.isJarSealed()) {
fSealPackagesLabel.setText(""); //$NON-NLS-1$
int i= fJarPackage.getPackagesToUnseal().length;
if (i == 0)
fSealJarLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.jarSealed")); //$NON-NLS-1$
else if (i == 1)
fSealJarLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.jarSealedExceptOne")); //$NON-NLS-1$
else
fSealJarLabel.setText(JarPackagerMessages.getFormattedString("JarManifestWizardPage.jarSealedExceptSome", new Integer(i))); //$NON-NLS-1$
}
else {
fSealJarLabel.setText(""); //$NON-NLS-1$
int i= fJarPackage.getPackagesToSeal().length;
if (i == 0)
fSealPackagesLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.nothingSealed")); //$NON-NLS-1$
else if (i == 1)
fSealPackagesLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.onePackageSealed")); //$NON-NLS-1$
else
fSealPackagesLabel.setText(JarPackagerMessages.getFormattedString("JarManifestWizardPage.somePackagesSealed", new Integer(i))); //$NON-NLS-1$
}
}
/*
* Implements method from IJarPackageWizardPage
*/
public boolean isPageComplete() {
boolean incompleteButNotAnError= false;
if (fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
if (fJarPackage.getManifestLocation().toString().length() == 0)
incompleteButNotAnError= true;
else {
IPath location= fJarPackage.getManifestLocation();
if (!location.toString().startsWith("/")) { //$NON-NLS-1$
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.manifestPathMustBeAbsolute")); //$NON-NLS-1$
return false;
}
IResource resource= findResource(location);
if (resource != null && resource.getType() != IResource.FILE) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.manifestMustNotBeExistingContainer")); //$NON-NLS-1$
return false;
}
resource= findResource(location.removeLastSegments(1));
if (resource == null || resource.getType() == IResource.FILE) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.manifestContainerDoesNotExist")); //$NON-NLS-1$
return false;
}
}
}
if (!fJarPackage.isManifestGenerated() && !fJarPackage.isManifestAccessible()) {
if (fJarPackage.getManifestLocation().toString().length() == 0)
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.noManifestFile")); //$NON-NLS-1$
else
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.invalidManifestFile")); //$NON-NLS-1$
return false;
}
Set selectedPackages= getPackagesForSelectedResources(fJarPackage);
if (fJarPackage.isJarSealed()
&& !selectedPackages.containsAll(Arrays.asList(fJarPackage.getPackagesToUnseal()))) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.unsealedPackagesNotInSelection")); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isJarSealed()
&& !selectedPackages.containsAll(Arrays.asList(fJarPackage.getPackagesToSeal()))) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.sealedPackagesNotInSelection")); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(getContainer()) || (fJarPackage.getManifestMainClass() == null && fMainClassText.getText().length() > 0)) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.invalidMainClass")); //$NON-NLS-1$
return false;
}
if (incompleteButNotAnError) {
setErrorMessage(null);
return false;
}
setErrorMessage(null);
return true;
}
/*
* Implements method from IWizardPage.
*/
public void setPreviousPage(IWizardPage page) {
super.setPreviousPage(page);
fMainTypes= null;
updateEnableState();
if (getContainer() != null)
updatePageCompletion();
}
/*
* Implements method from IJarPackageWizardPage.
*/
public void finish() {
saveWidgetValues();
}
// ----------- Model handling -----------
/**
* Persists resource specification control setting that are to be restored
* in the next instance of this page. Subclasses wishing to persist
* settings for their controls should extend the hook method
* <code>internalSaveWidgetValues</code>.
*/
public final void saveWidgetValues() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
// Manifest creation
settings.put(STORE_GENERATE_MANIFEST, fJarPackage.isManifestGenerated());
settings.put(STORE_SAVE_MANIFEST, fJarPackage.isManifestSaved());
settings.put(STORE_REUSE_MANIFEST, fJarPackage.isManifestReused());
settings.put(STORE_MANIFEST_LOCATION, fJarPackage.getManifestLocation().toString());
// Sealing
settings.put(STORE_SEAL_JAR, fJarPackage.isJarSealed());
}
// Allow subclasses to save values
internalSaveWidgetValues();
}
/**
* Hook method for subclasses to persist their settings.
*/
protected void internalSaveWidgetValues() {
}
/**
* Hook method for restoring widget values to the values that they held
* last time this wizard was used to completion.
*/
protected void restoreWidgetValues() {
if (!((JarPackageWizard)getWizard()).isInitializingFromJarPackage())
initializeJarPackage();
// Manifest creation
if (fJarPackage.isManifestGenerated())
fGenerateManifestRadioButton.setSelection(true);
else
fUseManifestRadioButton.setSelection(true);
fSaveManifestCheckbox.setSelection(fJarPackage.isManifestSaved());
fReuseManifestCheckbox.setSelection(fJarPackage.isManifestReused());
fManifestFileText.setText(fJarPackage.getManifestLocation().toString());
fNewManifestFileText.setText(fJarPackage.getManifestLocation().toString());
// Sealing
if (fJarPackage.isJarSealed())
fSealJarRadioButton.setSelection(true);
else
fSealPackagesRadioButton.setSelection(true);
// Main-Class
fMainClassText.setText(JarPackagerUtil.getMainClassName(fJarPackage));
}
/**
* Initializes the JAR package from last used wizard page values.
*/
protected void initializeJarPackage() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
// Manifest creation
fJarPackage.setGenerateManifest(settings.getBoolean(STORE_GENERATE_MANIFEST));
fJarPackage.setSaveManifest(settings.getBoolean(STORE_SAVE_MANIFEST));
fJarPackage.setReuseManifest(settings.getBoolean(STORE_REUSE_MANIFEST));
String pathStr= settings.get(STORE_MANIFEST_LOCATION);
if (pathStr == null)
pathStr= ""; //$NON-NLS-1$
fJarPackage.setManifestLocation(new Path(pathStr));
// Sealing
fJarPackage.setSealJar(settings.getBoolean(STORE_SEAL_JAR));
}
}
/**
* Stores the widget values in the JAR package.
*/
protected void updateModel() {
if (getControl() == null)
return;
// Manifest creation
fJarPackage.setGenerateManifest(fGenerateManifestRadioButton.getSelection());
fJarPackage.setSaveManifest(fSaveManifestCheckbox.getSelection());
fJarPackage.setReuseManifest(fReuseManifestCheckbox.getSelection());
String path;
if (fJarPackage.isManifestGenerated())
path= fNewManifestFileText.getText();
else
path= fManifestFileText.getText();
if (path == null)
path= ""; //$NON-NLS-1$
fJarPackage.setManifestLocation(new Path(path));
// Sealing
fJarPackage.setSealJar(fSealJarRadioButton.getSelection());
}
/**
* Determine if the page is complete and update the page appropriately.
*/
protected void updatePageCompletion() {
boolean pageComplete= isPageComplete();
setPageComplete(pageComplete);
if (pageComplete) {
setErrorMessage(null);
}
}
// ----------- Utility methods -----------
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a new label with a bold font.
*
* @param parent the parent control
* @param text the label text
* @return the new label control
*/
protected Label createLabel(Composite parent, String text, boolean bold) {
Label label= new Label(parent, SWT.NONE);
if (bold)
label.setFont(JFaceResources.getBannerFont());
label.setText(text);
GridData data= new GridData();
data.verticalAlignment= GridData.FILL;
data.horizontalAlignment= GridData.FILL;
label.setLayoutData(data);
return label;
}
/**
* Sets the size of a control.
*
* @param control the control for which to set the size
* @param width the new width of the control
* @param height the new height of the control
*/
protected void setSize(Control control, int width, int height) {
GridData gd= new GridData(GridData.END);
gd.widthHint= width ;
gd.heightHint= height;
control.setLayoutData(gd);
}
/**
* Makes the size of all buttons equal.
*/
protected void setEqualButtonSizes() {
int width= SWTUtil.getButtonWidthHint(fManifestFileBrowseButton);
int height= SWTUtil.getButtonHeigthHint(fManifestFileBrowseButton);
int width2= SWTUtil.getButtonWidthHint(fNewManifestFileBrowseButton);
int height2= SWTUtil.getButtonHeigthHint(fNewManifestFileBrowseButton);
width= Math.max(width, width2);
height= Math.max(height, height2);
width2= SWTUtil.getButtonWidthHint(fSealedPackagesDetailsButton);
height2= SWTUtil.getButtonHeigthHint(fSealedPackagesDetailsButton);
width= Math.max(width, width2);
height= Math.max(height, height2);
width2= SWTUtil.getButtonWidthHint(fUnSealedPackagesDetailsButton);
height2= SWTUtil.getButtonHeigthHint(fUnSealedPackagesDetailsButton);
width= Math.max(width, width2);
height= Math.max(height, height2);
width2= SWTUtil.getButtonWidthHint(fMainClassBrowseButton);
height2= SWTUtil.getButtonHeigthHint(fMainClassBrowseButton);
width= Math.max(width, width2);
height= Math.max(height, height2);
setSize(fManifestFileBrowseButton, width, height);
setSize(fNewManifestFileBrowseButton, width, height);
setSize(fSealedPackagesDetailsButton, width, height);
setSize(fUnSealedPackagesDetailsButton, width, height);
setSize(fMainClassBrowseButton, width, height);
}
/**
* Creates a horizontal spacer line that fills the width of its container.
*
* @param parent the parent control
*/
protected void createSpacer(Composite parent) {
Label spacer= new Label(parent, SWT.NONE);
GridData data= new GridData();
data.horizontalAlignment= GridData.FILL;
data.verticalAlignment= GridData.BEGINNING;
spacer.setLayoutData(data);
}
/**
* Returns the resource for the specified path.
*
* @param path the path for which the resource should be returned
* @return the resource specified by the path or <code>null</code>
*/
protected IResource findResource(IPath path) {
IWorkspace workspace= JavaPlugin.getWorkspace();
IStatus result= workspace.validatePath(
path.toString(),
IResource.ROOT | IResource.PROJECT | IResource.FOLDER | IResource.FILE);
if (result.isOK() && workspace.getRoot().exists(path))
return workspace.getRoot().findMember(path);
return null;
}
protected IPath getPathFromString(String text) {
return new Path(text).makeAbsolute();
}
/**
* Creates a selection dialog that lists all packages under the given package
* fragment root.
* The caller is responsible for opening the dialog with <code>Window.open</code>,
* and subsequently extracting the selected packages (of type
* <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
*
* @param packageFragments the package fragments
* @return a new selection dialog
*/
protected SelectionDialog createPackageDialog(Set packageFragments) {
List packages= new ArrayList(packageFragments.size());
for (Iterator iter= packageFragments.iterator(); iter.hasNext();) {
IPackageFragment fragment= (IPackageFragment)iter.next();
boolean containsJavaElements= false;
int kind;
try {
kind= fragment.getKind();
containsJavaElements= fragment.getChildren().length > 0;
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, getContainer().getShell(), JarPackagerMessages.getString("JarManifestWizardPage.error.jarPackageWizardError.title"), JarPackagerMessages.getFormattedString("JarManifestWizardPage.error.jarPackageWizardError.message", fragment.getElementName())); //$NON-NLS-2$ //$NON-NLS-1$
continue;
}
if (kind != IPackageFragmentRoot.K_BINARY && containsJavaElements)
packages.add(fragment);
}
JavaElementContentProvider cp= new JavaElementContentProvider() {
public boolean hasChildren(Object element) {
// prevent the + from being shown in front of packages
return !(element instanceof IPackageFragment) && super.hasChildren(element);
}
};
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getContainer().getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT), cp);
dialog.setDoubleClickSelects(false);
dialog.setInput(JavaCore.create(JavaPlugin.getDefault().getWorkspace().getRoot()));
dialog.addFilter(new EmptyInnerPackageFilter());
dialog.addFilter(new LibraryFilter());
dialog.addFilter(new SealPackagesFilter(packages));
dialog.setValidator(new ISelectionValidator() {
public IStatus validate(Object[] selection) {
StatusInfo res= new StatusInfo();
for (int i= 0; i < selection.length; i++) {
if (!(selection[i] instanceof IPackageFragment)) {
res.setError(JarPackagerMessages.getString("JarManifestWizardPage.error.mustContainPackages")); //$NON-NLS-1$
return res;
}
}
res.setOK();
return res;
}
});
return dialog;
}
/**
* Converts selection dialog results into an array of IPackageFragments.
* An empty array is returned in case of errors.
* @throws ClassCastException if results are not IPackageFragments
*/
protected IPackageFragment[] getPackagesFromDialog(SelectionDialog dialog) {
if (dialog.getReturnCode() == dialog.OK && dialog.getResult().length > 0)
return (IPackageFragment[])Arrays.asList(dialog.getResult()).toArray(new IPackageFragment[dialog.getResult().length]);
else
return new IPackageFragment[0];
}
/**
* Creates and returns a dialog to choose an existing workspace file.
*/
protected ElementTreeSelectionDialog createWorkspaceFileSelectionDialog(String title, String message) {
int labelFlags= JavaElementLabelProvider.SHOW_BASICS
| JavaElementLabelProvider.SHOW_OVERLAY_ICONS
| JavaElementLabelProvider.SHOW_SMALL_ICONS;
ITreeContentProvider contentProvider= new JavaElementContentProvider();
ILabelProvider labelProvider= new JavaElementLabelProvider(labelFlags);
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, contentProvider);
dialog.setAllowMultiple(false);
dialog.setValidator(new ISelectionValidator() {
public IStatus validate(Object[] selection) {
StatusInfo res= new StatusInfo();
// only single selection
if (selection.length == 1 && (selection[0] instanceof IFile))
res.setOK();
else
res.setError(""); //$NON-NLS-1$
return res;
}
});
dialog.addFilter(new EmptyInnerPackageFilter());
dialog.addFilter(new LibraryFilter());
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setStatusLineAboveButtons(true);
dialog.setInput(JavaCore.create(JavaPlugin.getDefault().getWorkspace().getRoot()));
return dialog;
}
/**
* Returns the minimal set of packages which contain all the selected Java resources.
* @return the Set of IPackageFragments which contain all the selected resources
*/
private Set getPackagesForSelectedResources(JarPackageData jarPackage) {
Set packages= new HashSet();
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
if (element instanceof ICompilationUnit) {
IJavaElement pack= JavaModelUtil.findParentOfKind((IJavaElement)element, org.eclipse.jdt.core.IJavaElement.PACKAGE_FRAGMENT);
if (pack != null)
packages.add(pack);
}
}
return packages;
}
}
|
12,249 |
Bug 12249 Rename "Ant Preferences" to "Ant" in workbench->Preferences
|
"Preferences" is redundant.
|
resolved fixed
|
d273e15
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T08:50:11Z | 2002-03-25T21:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
12,249 |
Bug 12249 Rename "Ant Preferences" to "Ant" in workbench->Preferences
|
"Preferences" is redundant.
|
resolved fixed
|
d273e15
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T08:50:11Z | 2002-03-25T21:00:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractTempTests.java
| |
12,884 |
Bug 12884 find strings to externalize - should be cancelable
|
instead of a busy cursor it should show a progress dialog with cancelation
|
resolved fixed
|
bccd69d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T09:06:44Z | 2002-04-05T18:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/FindStringsToExternalizeAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.internal.corext.refactoring.base.Refactoring;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSLine;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSScanner;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.refactoring.actions.ListDialog;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.ListContentProvider;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
/**
* Find all Strings in a package or project that aren't externalized yet.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class FindStringsToExternalizeAction extends SelectionDispatchAction {
private static final String FIND_STRINGS_CHECKBOX= "FindStringAction.checkbox"; //$NON-NLS-1$
/**
* Creates a new <code>FindStringsToExternalizeAction</code>.
*
* @param site the site providing context information for this action
*/
public FindStringsToExternalizeAction(UnifiedSite site) {
super(site);
setText(ActionMessages.getString("FindStringsToExternalizeAction.label")); //$NON-NLS-1$
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(computeEnablementState(selection));
}
private boolean computeEnablementState(IStructuredSelection selection) {
if (selection.size() == 0)
return false;
for (Iterator iter= selection.iterator(); iter.hasNext();) {
Object element= (Object)iter.next();
if (!(element instanceof IJavaElement))
return false;
int elementType= ((IJavaElement)element).getElementType();
if (elementType != IJavaElement.PACKAGE_FRAGMENT && elementType != IJavaElement.PACKAGE_FRAGMENT_ROOT &&
elementType != IJavaElement.JAVA_PROJECT)
return false;
}
return true;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(final IStructuredSelection selection) {
new BusyIndicator().showWhile(getShell().getDisplay(), new Runnable() {
public void run() {
doRun(selection);
}
});
}
private void doRun(IStructuredSelection selection) {
List elements= getSelectedElementList(selection);
if (elements == null || elements.isEmpty())
return;
try{
List l= new ArrayList();
for (Iterator iter= elements.iterator(); iter.hasNext();) {
IJavaElement element= (IJavaElement) iter.next();
if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
l.addAll(analyze((IPackageFragment) element));
else if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT)
l.addAll(analyze((IPackageFragmentRoot) element));
if (element.getElementType() == IJavaElement.JAVA_PROJECT)
l.addAll(analyze((IJavaProject) element));
}
showResults(l);
} catch(JavaModelException e) {
ExceptionHandler.handle(e,
ActionMessages.getString("FindStringsToExternalizeAction.dialog.title"), //$NON-NLS-1$
ActionMessages.getString("FindStringsToExternalizeAction.error.message")); //$NON-NLS-1$
}
}
private void showResults(List l) {
if (noStrings(l))
MessageDialog.openInformation(getShell(),
ActionMessages.getString("FindStringsToExternalizeAction.dialog.title"), //$NON-NLS-1$
ActionMessages.getString("FindStringsToExternalizeAction.noStrings")); //$NON-NLS-1$
else
new NonNLSListDialog(getShell(), l, countStrings(l)).open();
}
private boolean noStrings(List l) {
for (Iterator iter= l.iterator(); iter.hasNext();) {
NonNLSElement element= (NonNLSElement)iter.next();
if (element.count != 0)
return false;
}
return true;
}
/*
* returns List of Strings
*/
private List analyze(IPackageFragment pack) throws JavaModelException{
if (pack == null)
return new ArrayList(0);
ICompilationUnit[] cus= pack.getCompilationUnits();
List l= new ArrayList(cus.length);
for (int i= 0; i < cus.length; i++)
l.add(analyze(cus[i]));
return l;
}
/*
* returns List of Strings
*/
private List analyze(IPackageFragmentRoot sourceFolder) throws JavaModelException{
IJavaElement[] children= sourceFolder.getChildren();
List result= new ArrayList();
for (int i= 0; i < children.length; i++) {
IJavaElement iJavaElement= children[i];
if (iJavaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT){
IPackageFragment pack= (IPackageFragment)iJavaElement;
if (! pack.isReadOnly())
result.addAll(analyze(pack));
}
}
return result;
}
/*
* returns List of Strings
*/
private List analyze(IJavaProject project) throws JavaModelException{
IPackageFragment[] packs= project.getPackageFragments();
List result= new ArrayList();
for (int i= 0; i < packs.length; i++) {
if (! packs[i].isReadOnly())
result.addAll(analyze(packs[i]));
}
return result;
}
/*
* @param List of NonNLSElements
*/
private static int countStrings(List elements){
int i= 0;
for (Iterator iter= elements.iterator(); iter.hasNext(); )
i += (((NonNLSElement)iter.next()).count);
return i;
}
private NonNLSElement analyze(ICompilationUnit cu) throws JavaModelException{
return new NonNLSElement(cu, countNotExternalizedStrings(cu));
}
private int countNotExternalizedStrings(ICompilationUnit cu){
try{
NLSLine[] lines= NLSScanner.scan(cu);
int result= 0;
for (int i= 0; i < lines.length; i++) {
result += countNotExternalizedStrings(lines[i]);
}
return result;
}catch(JavaModelException e) {
ExceptionHandler.handle(e,
ActionMessages.getString("FindStringsToExternalizeAction.dialog.title"), //$NON-NLS-1$
ActionMessages.getString("FindStringsToExternalizeAction.error.message")); //$NON-NLS-1$
return 0;
}catch(InvalidInputException iie) {
JavaPlugin.log(iie);
return 0;
}
}
private int countNotExternalizedStrings(NLSLine line){
int result= 0;
NLSElement[] elements= line.getElements();
for (int i= 0; i < elements.length; i++){
if (! elements[i].hasTag())
result++;
}
return result;
}
/**
* returns <code>List</code> of <code>IPackageFragments</code>, <code>IPackageFragmentRoots</code> or
* <code>IJavaProjects</code> (all entries are of the same kind)
*/
private static List getSelectedElementList(IStructuredSelection selection) {
if (selection == null)
return null;
return selection.toList();
}
private static LabelProvider createLabelProvider() {
return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT){
public String getText(Object element) {
NonNLSElement nlsel= (NonNLSElement)element;
String elementName= nlsel.cu.getElementName();
try{
elementName= Refactoring.getResource(nlsel.cu).getProjectRelativePath().toString();
}catch (JavaModelException e){
}
return ActionMessages.getFormattedString(
"FindStringsToExternalizeAction.foundStrings", //$NON-NLS-1$
new Object[] {new Integer(nlsel.count), elementName} );
}
public Image getImage(Object element) {
return super.getImage(((NonNLSElement)element).cu);
}
};
}
private static boolean loadCheckboxState(boolean defaultValue){
String res= JavaPlugin.getDefault().getDialogSettings().get(FIND_STRINGS_CHECKBOX);
if (res == null)
return defaultValue;
return Boolean.valueOf(res).booleanValue();
}
private static void storeCheckboxState(boolean selected){
JavaPlugin.getDefault().getDialogSettings().put(FIND_STRINGS_CHECKBOX, selected);
}
//-------private classes --------------
private static class NonNLSListDialog extends ListDialog {
private static final int OPEN_BUTTON_ID= IDialogConstants.CLIENT_ID + 1;
private Button fCheckbox;
private Button fOpenButton;
NonNLSListDialog(Shell parent, Object input, int count) {
super(parent);
setInput(input);
setTitle(ActionMessages.getString("FindStringsToExternalizeAction.dialog.title")); //$NON-NLS-1$
setMessage(ActionMessages.getFormattedString("FindStringsToExternalizeAction.not_externalized", new Object[] {new Integer(count)} )); //$NON-NLS-1$
setContentProvider(new ListContentProvider());
setLabelProvider(createLabelProvider());
}
public void create() {
setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN);
super.create();
}
protected Point getInitialSize() {
return getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
}
protected Control createDialogArea(Composite parent) {
Composite result= (Composite)super.createDialogArea(parent);
addCheckbox(result);
getTableViewer().addSelectionChangedListener(new ISelectionChangedListener(){
public void selectionChanged(SelectionChangedEvent event){
if (fOpenButton != null){
fOpenButton.setEnabled(! getTableViewer().getSelection().isEmpty());
}
}
});
getTableViewer().getTable().addSelectionListener(new SelectionAdapter(){
public void widgetDefaultSelected(SelectionEvent e) {
NonNLSElement element= (NonNLSElement)e.item.getData();
openWizard(element.cu);
}
});
return result;
}
private void addCheckbox(Composite result) {
fCheckbox= new Button(result, SWT.CHECK);
fCheckbox.setText(ActionMessages.getString("FindStringsToExternalizeAction.hide")); //$NON-NLS-1$
fCheckbox.setSelection(loadCheckboxState(true));
if (fCheckbox.getSelection() && ! NonNLSListDialog.this.hasFilters())
getTableViewer().addFilter(new ZeroStringsFilter());
fCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
storeCheckboxState(NonNLSListDialog.this.fCheckbox.getSelection());
boolean showAll= ! NonNLSListDialog.this.fCheckbox.getSelection();
if (showAll && NonNLSListDialog.this.hasFilters())
NonNLSListDialog.this.getTableViewer().resetFilters();
else if (! showAll && ! NonNLSListDialog.this.hasFilters())
NonNLSListDialog.this.getTableViewer().addFilter(new ZeroStringsFilter());
}
});
}
protected void createButtonsForButtonBar(Composite parent) {
fOpenButton= createButton(parent, OPEN_BUTTON_ID, ActionMessages.getString("FindStringsToExternalizeAction.button.label"), true); //$NON-NLS-1$
fOpenButton.setEnabled(false);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
}
protected void buttonPressed(int buttonId) {
if (buttonId != OPEN_BUTTON_ID){
super.buttonPressed(buttonId);
return;
}
ISelection s= getTableViewer().getSelection();
if (s instanceof IStructuredSelection){
IStructuredSelection ss= (IStructuredSelection)s;
if (ss.getFirstElement() instanceof NonNLSElement)
openWizard(((NonNLSElement)ss.getFirstElement()).cu);
}
}
private void openWizard(ICompilationUnit unit) {
try {
ExternalizeStringsAction.openExternalizeStringsWizard(unit);
} catch (JavaModelException e) {
ExceptionHandler.handle(e,
ActionMessages.getString("FindStringsToExternalizeAction.dialog.title"), //$NON-NLS-1$
ActionMessages.getString("FindStringsToExternalizeAction.error.message")); //$NON-NLS-1$
}
}
}
private static class NonNLSElement{
ICompilationUnit cu;
int count;
NonNLSElement(ICompilationUnit cu, int count){
this.cu= cu;
this.count= count;
}
}
private static class ZeroStringsFilter extends ViewerFilter{
public boolean select(Viewer viewer, Object parentElement, Object element) {
return ((NonNLSElement)element).count != 0;
}
}
}
|
13,056 |
Bug 13056 can't delete 2 identical methods
|
class Ad { void f(){}; void f(){}; } you can't delete the 2 f methods (together) it works if you delete them separately
|
resolved fixed
|
5bbb09a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T09:10:09Z | 2002-04-09T11:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/SourceReferenceAction.java
|
package org.eclipse.jdt.internal.ui.reorg;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
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.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.refactoring.reorg.SourceReferenceUtil;
import org.eclipse.jdt.internal.corext.refactoring.util.WorkingCopyUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringAction;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
abstract class SourceReferenceAction extends RefactoringAction {
private ISelectionProvider fSelectionProvider;
protected SourceReferenceAction(String name, ISelectionProvider provider) {
super(name, provider);
fSelectionProvider= provider;
}
protected ISelectionProvider getSelectionProvider(){
return fSelectionProvider;
}
/*
* @see Action#run
*/
public final void run() {
//safety net - fix for: 9528
update();
if (!isEnabled())
return;
new BusyIndicator().showWhile(JavaPlugin.getActiveWorkbenchShell().getDisplay(), new Runnable() {
public void run() {
try {
perform();
} catch (CoreException e) {
ExceptionHandler.handle(e, getText(), ReorgMessages.getString("SourceReferenceAction.exception")); //$NON-NLS-1$
}
}
});
}
protected ISourceReference[] getElementsToProcess() {
return SourceReferenceUtil.removeAllWithParentsSelected(getSelectedElements());
}
protected abstract void perform() throws CoreException;
/*
* @see RefactoringAction#canOperateOn(IStructuredSelection)
*/
public boolean canOperateOn(IStructuredSelection selection) {
try{
if (selection.isEmpty())
return false;
Object[] elems= selection.toArray();
for (int i= 0; i < elems.length; i++) {
Object elem= elems[i];
if (! canWorkOn(elem))
return false;
}
return true;
} catch (JavaModelException e){
JavaPlugin.log(e);
return false;
}
}
private ISourceReference[] getSelectedElements(){
return getWorkingCopyElements(getStructuredSelection().toList());
}
private static boolean canWorkOn(Object elem) throws JavaModelException{
if (elem == null)
return false;
if (! (elem instanceof ISourceReference))
return false;
if (! (elem instanceof IJavaElement))
return false;
if (elem instanceof IClassFile)
return false;
if (elem instanceof ICompilationUnit)
return false;
if ((elem instanceof IMember) && ((IMember)elem).isBinary())
return false;
if (isDeletedFromEditor((ISourceReference)elem))
return false;
if (elem instanceof IMember) //binary excluded before
return true;
if (elem instanceof IImportContainer)
return true;
if (elem instanceof IImportDeclaration)
return true;
if (elem instanceof IPackageDeclaration)
return true;
//we never get here normally
return false;
}
private static boolean isDeletedFromEditor(ISourceReference elem) throws JavaModelException{
ICompilationUnit cu= SourceReferenceUtil.getCompilationUnit(elem);
ICompilationUnit wc= WorkingCopyUtil.getWorkingCopyIfExists(cu);
if (wc.equals(cu))
return false;
IJavaElement element= (IJavaElement)elem;
IJavaElement wcElement= JavaModelUtil.findInCompilationUnit(wc, element);
return wcElement == null || ! wcElement.exists();
}
private static ISourceReference[] getWorkingCopyElements(List l) {
List wcList= new ArrayList(l.size());
for (Iterator iter= l.iterator(); iter.hasNext();) {
ISourceReference element= (ISourceReference) iter.next();
if (! (element instanceof IJavaElement)) //can this happen ?
wcList.add(element);
ICompilationUnit cu= SourceReferenceUtil.getCompilationUnit(element);
ICompilationUnit wc= WorkingCopyUtil.getWorkingCopyIfExists(cu);
try {
IJavaElement wcElement= JavaModelUtil.findInCompilationUnit(wc, (IJavaElement)element);
if (wcElement != null && wcElement.exists())
wcList.add(wcElement);
} catch(JavaModelException e) {
JavaPlugin.log(e); //cannot show dialog here
//do nothing - do not add to selection (?)
}
}
return (ISourceReference[]) wcList.toArray(new ISourceReference[wcList.size()]);
}
}
|
8,082 |
Bug 8082 template pref page: export overwrites without warning
|
export from template pref page overwrites files without warning this is never good - you can lose templates you have saved on your disk somewhere
|
resolved fixed
|
e63e83a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T10:04:23Z | 2002-01-23T12:46:40Z |
org.eclipse.jdt.ui/core
| |
8,082 |
Bug 8082 template pref page: export overwrites without warning
|
export from template pref page overwrites files without warning this is never good - you can lose templates you have saved on your disk somewhere
|
resolved fixed
|
e63e83a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T10:04:23Z | 2002-01-23T12:46:40Z |
extension/org/eclipse/jdt/internal/corext/template/Template.java
| |
8,082 |
Bug 8082 template pref page: export overwrites without warning
|
export from template pref page overwrites files without warning this is never good - you can lose templates you have saved on your disk somewhere
|
resolved fixed
|
e63e83a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T10:04:23Z | 2002-01-23T12:46:40Z |
org.eclipse.jdt.ui/core
| |
8,082 |
Bug 8082 template pref page: export overwrites without warning
|
export from template pref page overwrites files without warning this is never good - you can lose templates you have saved on your disk somewhere
|
resolved fixed
|
e63e83a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T10:04:23Z | 2002-01-23T12:46:40Z |
extension/org/eclipse/jdt/internal/corext/template/TemplateSet.java
| |
8,082 |
Bug 8082 template pref page: export overwrites without warning
|
export from template pref page overwrites files without warning this is never good - you can lose templates you have saved on your disk somewhere
|
resolved fixed
|
e63e83a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T10:04:23Z | 2002-01-23T12:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/EditTemplateDialog.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.corext.template.ContextType;
import org.eclipse.jdt.internal.corext.template.ContextTypeRegistry;
import org.eclipse.jdt.internal.corext.template.Template;
import org.eclipse.jdt.internal.corext.template.TemplateContext;
import org.eclipse.jdt.internal.corext.template.TemplateMessages;
import org.eclipse.jdt.internal.corext.template.TemplateTranslator;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.text.template.TemplateVariableProcessor;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
/**
* Dialog to edit a template.
*/
public class EditTemplateDialog extends StatusDialog {
private static class SimpleJavaSourceViewerConfiguration extends JavaSourceViewerConfiguration {
private final IContentAssistProcessor fProcessor;
SimpleJavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor, IContentAssistProcessor processor) {
super(tools, editor);
fProcessor= processor;
}
/*
* @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
*/
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
ContentAssistant assistant= new ContentAssistant();
assistant.setContentAssistProcessor(fProcessor, IDocument.DEFAULT_CONTENT_TYPE);
assistant.enableAutoActivation(true);
assistant.setAutoActivationDelay(500);
assistant.setProposalPopupOrientation(assistant.PROPOSAL_OVERLAY);
assistant.setContextInformationPopupOrientation(assistant.CONTEXT_INFO_ABOVE);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
Color background= getColorManager().getColor(new RGB(254, 241, 233));
assistant.setContextInformationPopupBackground(background);
assistant.setContextSelectorBackground(background);
assistant.setProposalSelectorBackground(background);
return assistant;
}
}
private static class TextViewerAction extends Action implements IUpdate {
private int fOperationCode= -1;
private ITextOperationTarget fOperationTarget;
public TextViewerAction(ITextViewer viewer, int operationCode) {
fOperationCode= operationCode;
fOperationTarget= viewer.getTextOperationTarget();
update();
}
/**
* Updates the enabled state of the action.
* Fires a property change if the enabled state changes.
*
* @see Action#firePropertyChange(String, Object, Object)
*/
public void update() {
boolean wasEnabled= isEnabled();
boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
setEnabled(isEnabled);
if (wasEnabled != isEnabled) {
firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE);
}
}
/**
* @see Action#run()
*/
public void run() {
if (fOperationCode != -1 && fOperationTarget != null) {
fOperationTarget.doOperation(fOperationCode);
}
}
}
private Template fTemplate;
private Text fNameText;
private Text fDescriptionText;
private Combo fContextCombo;
private SourceViewer fPatternEditor;
private Button fInsertVariableButton;
private TemplateTranslator fTranslator= new TemplateTranslator();
private boolean fSuppressError= true; // #4354
private Map fGlobalActions= new HashMap(10);
private List fSelectionActions = new ArrayList(3);
private Vector fContextTypes= new Vector();
private final TemplateVariableProcessor fProcessor= new TemplateVariableProcessor();
public EditTemplateDialog(Shell parent, Template template, boolean edit) {
super(parent);
setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE);
String title= edit
? TemplateMessages.getString("EditTemplateDialog.title.edit") //$NON-NLS-1$
: TemplateMessages.getString("EditTemplateDialog.title.new"); //$NON-NLS-1$
setTitle(title);
fTemplate= template;
ContextTypeRegistry registry= ContextTypeRegistry.getInstance();
for (Iterator iterator= registry.iterator(); iterator.hasNext(); )
fContextTypes.add(iterator.next());
if (fContextTypes.size() > 0)
fProcessor.setContextType(ContextTypeRegistry.getInstance().getContextType((String) fContextTypes.get(0)));
}
/*
* @see Dialog#createDialogArea(Composite)
*/
protected Control createDialogArea(Composite ancestor) {
Composite parent= new Composite(ancestor, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
parent.setLayout(layout);
parent.setLayoutData(new GridData(GridData.FILL_BOTH));
createLabel(parent, TemplateMessages.getString("EditTemplateDialog.name")); //$NON-NLS-1$
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
layout= new GridLayout();
layout.numColumns= 3;
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
fNameText= createText(composite);
fNameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
if (fSuppressError && (fNameText.getText().trim().length() != 0))
fSuppressError= false;
updateButtons();
}
});
createLabel(composite, TemplateMessages.getString("EditTemplateDialog.context")); //$NON-NLS-1$
fContextCombo= new Combo(composite, SWT.READ_ONLY);
for (Iterator iterator= fContextTypes.iterator(); iterator.hasNext(); )
fContextCombo.add((String) iterator.next());
fContextCombo.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
String name= fContextCombo.getText();
fProcessor.setContextType(ContextTypeRegistry.getInstance().getContextType(name));
}
});
createLabel(parent, TemplateMessages.getString("EditTemplateDialog.description")); //$NON-NLS-1$
fDescriptionText= createText(parent);
composite= new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(GridData.FILL_VERTICAL));
layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
createLabel(composite, TemplateMessages.getString("EditTemplateDialog.pattern")); //$NON-NLS-1$
fPatternEditor= createEditor(parent);
Label filler= new Label(composite, SWT.NONE);
filler.setLayoutData(new GridData(GridData.FILL_VERTICAL));
fInsertVariableButton= new Button(composite, SWT.NONE);
fInsertVariableButton.setLayoutData(getButtonGridData(fInsertVariableButton));
fInsertVariableButton.setText(TemplateMessages.getString("EditTemplateDialog.insert.variable")); //$NON-NLS-1$
fInsertVariableButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
fPatternEditor.getTextWidget().setFocus();
fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
fNameText.setText(fTemplate.getName());
fDescriptionText.setText(fTemplate.getDescription());
fContextCombo.select(getIndex(fTemplate.getContextTypeName()));
initializeActions();
return composite;
}
private static GridData getButtonGridData(Button button) {
GridData data= new GridData(GridData.FILL_HORIZONTAL);
data.heightHint= SWTUtil.getButtonHeigthHint(button);
return data;
}
private static Label createLabel(Composite parent, String name) {
Label label= new Label(parent, SWT.NULL);
label.setText(name);
label.setLayoutData(new GridData());
return label;
}
private static Text createText(Composite parent) {
Text text= new Text(parent, SWT.BORDER);
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
return text;
}
private SourceViewer createEditor(Composite parent) {
SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
viewer.configure(new SimpleJavaSourceViewerConfiguration(tools, null, fProcessor));
viewer.setEditable(true);
viewer.setDocument(new Document(fTemplate.getPattern()));
Font font= JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT);
viewer.getTextWidget().setFont(font);
Control control= viewer.getControl();
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= convertWidthInCharsToPixels(60);
data.heightHint= convertHeightInCharsToPixels(5);
control.setLayoutData(data);
viewer.addTextListener(new ITextListener() {
public void textChanged(TextEvent event) {
try {
fTranslator.translate(event.getDocumentEvent().getDocument().get());
} catch (CoreException e) {
JavaPlugin.log(e);
// XXX dialog
}
updateUndoAction();
updateButtons();
}
});
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateSelectionDependentActions();
}
});
if (viewer instanceof ITextViewerExtension) {
((ITextViewerExtension) viewer).prependVerifyKeyListener(new VerifyKeyListener() {
public void verifyKey(VerifyEvent event) {
handleVerifyKeyPressed(event);
}
});
} else {
viewer.getTextWidget().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
public void keyReleased(KeyEvent e) {}
});
}
return viewer;
}
private void handleKeyPressed(KeyEvent event) {
if (event.stateMask != SWT.CTRL)
return;
switch (event.character) {
case ' ':
fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
break;
// CTRL-Z
case (int) 'z' - (int) 'a' + 1:
fPatternEditor.doOperation(ITextOperationTarget.UNDO);
break;
}
}
private void handleVerifyKeyPressed(VerifyEvent event) {
if (!event.doit)
return;
if (event.stateMask != SWT.CTRL)
return;
switch (event.character) {
case ' ':
fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
event.doit= false;
break;
// CTRL-Z
case (int) 'z' - (int) 'a' + 1:
fPatternEditor.doOperation(ITextOperationTarget.UNDO);
event.doit= false;
break;
}
}
private void initializeActions() {
TextViewerAction action= new TextViewerAction(fPatternEditor, fPatternEditor.UNDO);
action.setText(TemplateMessages.getString("EditTemplateDialog.undo")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.UNDO, action);
action= new TextViewerAction(fPatternEditor, fPatternEditor.CUT);
action.setText(TemplateMessages.getString("EditTemplateDialog.cut")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.CUT, action);
action= new TextViewerAction(fPatternEditor, fPatternEditor.COPY);
action.setText(TemplateMessages.getString("EditTemplateDialog.copy")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.COPY, action);
action= new TextViewerAction(fPatternEditor, fPatternEditor.PASTE);
action.setText(TemplateMessages.getString("EditTemplateDialog.paste")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.PASTE, action);
action= new TextViewerAction(fPatternEditor, fPatternEditor.SELECT_ALL);
action.setText(TemplateMessages.getString("EditTemplateDialog.select.all")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action);
action= new TextViewerAction(fPatternEditor, fPatternEditor.CONTENTASSIST_PROPOSALS);
action.setText(TemplateMessages.getString("EditTemplateDialog.content.assist")); //$NON-NLS-1$
fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$
fSelectionActions.add(ITextEditorActionConstants.CUT);
fSelectionActions.add(ITextEditorActionConstants.COPY);
fSelectionActions.add(ITextEditorActionConstants.PASTE);
// create context menu
MenuManager manager= new MenuManager(null, null);
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager mgr) {
fillContextMenu(mgr);
}
});
StyledText text= fPatternEditor.getTextWidget();
Menu menu= manager.createContextMenu(text);
text.setMenu(menu);
}
private void fillContextMenu(IMenuManager menu) {
menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO));
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO));
menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL));
menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$
}
protected void updateSelectionDependentActions() {
Iterator iterator= fSelectionActions.iterator();
while (iterator.hasNext())
updateAction((String)iterator.next());
}
protected void updateUndoAction() {
IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO);
if (action instanceof IUpdate)
((IUpdate) action).update();
}
protected void updateAction(String actionId) {
IAction action= (IAction) fGlobalActions.get(actionId);
if (action instanceof IUpdate)
((IUpdate) action).update();
}
private int getIndex(String context) {
ContextTypeRegistry registry= ContextTypeRegistry.getInstance();
registry.getContextType(context);
if (context == null)
return -1;
return fContextTypes.indexOf(context);
}
protected void okPressed() {
fTemplate.setName(fNameText.getText());
fTemplate.setDescription(fDescriptionText.getText());
fTemplate.setContext(fContextCombo.getText());
fTemplate.setPattern(fPatternEditor.getTextWidget().getText());
super.okPressed();
}
private void updateButtons() {
boolean valid= fNameText.getText().trim().length() != 0;
StatusInfo status= new StatusInfo();
if (!valid) {
if (fSuppressError)
status.setError(""); //$NON-NLS-1$
else
status.setError(TemplateMessages.getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$
} else if (fTranslator.getErrorMessage() != null) {
status.setError(fTranslator.getErrorMessage());
}
updateStatus(status);
}
}
|
8,082 |
Bug 8082 template pref page: export overwrites without warning
|
export from template pref page overwrites files without warning this is never good - you can lose templates you have saved on your disk somewhere
|
resolved fixed
|
e63e83a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T10:04:23Z | 2002-01-23T12:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/TemplatePreferencePage.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.corext.template.ContextType;
import org.eclipse.jdt.internal.corext.template.ContextTypeRegistry;
import org.eclipse.jdt.internal.corext.template.Template;
import org.eclipse.jdt.internal.corext.template.TemplateContext;
import org.eclipse.jdt.internal.corext.template.TemplateMessages;
import org.eclipse.jdt.internal.corext.template.TemplateSet;
import org.eclipse.jdt.internal.corext.template.Templates;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.template.TemplateContentProvider;
import org.eclipse.jdt.internal.ui.text.template.TemplateLabelProvider;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
public class TemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
// preference store keys
private static final String PREF_FORMAT_TEMPLATES= JavaUI.ID_PLUGIN + ".template.format"; //$NON-NLS-1$
private Templates fTemplates;
private CheckboxTableViewer fTableViewer;
private Button fAddButton;
private Button fEditButton;
private Button fImportButton;
private Button fExportButton;
private Button fExportAllButton;
private Button fRemoveButton;
private Button fEnableAllButton;
private Button fDisableAllButton;
private SourceViewer fPatternViewer;
private Button fFormatButton;
public TemplatePreferencePage() {
super();
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(TemplateMessages.getString("TemplatePreferencePage.message")); //$NON-NLS-1$
fTemplates= Templates.getInstance();
}
/**
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite ancestor) {
Composite parent= new Composite(ancestor, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
parent.setLayout(layout);
Table table= new Table(parent, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= convertWidthInCharsToPixels(80);
data.heightHint= convertHeightInCharsToPixels(10);
table.setLayoutData(data);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableLayout tableLayout= new TableLayout();
table.setLayout(tableLayout);
TableColumn column1= new TableColumn(table, SWT.NONE);
column1.setText(TemplateMessages.getString("TemplatePreferencePage.column.name")); //$NON-NLS-1$
TableColumn column2= new TableColumn(table, SWT.NONE);
column2.setText(TemplateMessages.getString("TemplatePreferencePage.column.context")); //$NON-NLS-1$
TableColumn column3= new TableColumn(table, SWT.NONE);
column3.setText(TemplateMessages.getString("TemplatePreferencePage.column.description")); //$NON-NLS-1$
tableLayout.addColumnData(new ColumnWeightData(30));
tableLayout.addColumnData(new ColumnWeightData(20));
tableLayout.addColumnData(new ColumnWeightData(70));
fTableViewer= new CheckboxTableViewer(table);
fTableViewer.setLabelProvider(new TemplateLabelProvider());
fTableViewer.setContentProvider(new TemplateContentProvider());
fTableViewer.setSorter(new ViewerSorter() {
public int compare(Viewer viewer, Object object1, Object object2) {
if ((object1 instanceof Template) && (object2 instanceof Template)) {
Template left= (Template) object1;
Template right= (Template) object2;
int result= left.getName().compareToIgnoreCase(right.getName());
if (result != 0)
return result;
return left.getDescription().compareToIgnoreCase(right.getDescription());
}
return super.compare(viewer, object1, object2);
}
public boolean isSorterProperty(Object element, String property) {
return true;
}
});
fTableViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent e) {
edit();
}
});
fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent e) {
selectionChanged1();
}
});
fTableViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
Template template= (Template) event.getElement();
template.setEnabled(event.getChecked());
}
});
Composite buttons= new Composite(parent, SWT.NULL);
buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
buttons.setLayout(layout);
fAddButton= new Button(buttons, SWT.PUSH);
fAddButton.setLayoutData(getButtonGridData(fAddButton));
fAddButton.setText(TemplateMessages.getString("TemplatePreferencePage.new")); //$NON-NLS-1$
fAddButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
add();
}
});
fEditButton= new Button(buttons, SWT.PUSH);
fEditButton.setLayoutData(getButtonGridData(fEditButton));
fEditButton.setText(TemplateMessages.getString("TemplatePreferencePage.edit")); //$NON-NLS-1$
fEditButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
edit();
}
});
fRemoveButton= new Button(buttons, SWT.PUSH);
fRemoveButton.setLayoutData(getButtonGridData(fRemoveButton));
fRemoveButton.setText(TemplateMessages.getString("TemplatePreferencePage.remove")); //$NON-NLS-1$
fRemoveButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
remove();
}
});
createSpacer(buttons);
fImportButton= new Button(buttons, SWT.PUSH);
fImportButton.setLayoutData(getButtonGridData(fImportButton));
fImportButton.setText(TemplateMessages.getString("TemplatePreferencePage.import")); //$NON-NLS-1$
fImportButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
import_();
}
});
fExportButton= new Button(buttons, SWT.PUSH);
fExportButton.setLayoutData(getButtonGridData(fExportButton));
fExportButton.setText(TemplateMessages.getString("TemplatePreferencePage.export")); //$NON-NLS-1$
fExportButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
export();
}
});
fExportAllButton= new Button(buttons, SWT.PUSH);
fExportAllButton.setLayoutData(getButtonGridData(fExportAllButton));
fExportAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.export.all")); //$NON-NLS-1$
fExportAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
exportAll();
}
});
createSpacer(buttons);
fEnableAllButton= new Button(buttons, SWT.PUSH);
fEnableAllButton.setLayoutData(getButtonGridData(fEnableAllButton));
fEnableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.enable.all")); //$NON-NLS-1$
fEnableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
enableAll(true);
}
});
fDisableAllButton= new Button(buttons, SWT.PUSH);
fDisableAllButton.setLayoutData(getButtonGridData(fDisableAllButton));
fDisableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.disable.all")); //$NON-NLS-1$
fDisableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
enableAll(false);
}
});
fPatternViewer= createViewer(parent);
createSpacer(parent);
fFormatButton= new Button(parent, SWT.CHECK);
fFormatButton.setText(TemplateMessages.getString("TemplatePreferencePage.use.code.formatter")); //$NON-NLS-1$
fTableViewer.setInput(fTemplates);
fTableViewer.setAllChecked(false);
fTableViewer.setCheckedElements(getEnabledTemplates());
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fFormatButton.setSelection(prefs.getBoolean(PREF_FORMAT_TEMPLATES));
updateButtons();
WorkbenchHelp.setHelp(parent, IJavaHelpContextIds.TEMPLATE_PREFERENCE_PAGE);
return parent;
}
private Template[] getEnabledTemplates() {
Template[] templates= fTemplates.getTemplates();
List list= new ArrayList(templates.length);
for (int i= 0; i != templates.length; i++)
if (templates[i].isEnabled())
list.add(templates[i]);
return (Template[]) list.toArray(new Template[list.size()]);
}
private SourceViewer createViewer(Composite parent) {
Label label= new Label(parent, SWT.NONE);
label.setText("Preview:");
GridData data= new GridData();
data.horizontalSpan= 2;
label.setLayoutData(data);
SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
viewer.configure(new JavaSourceViewerConfiguration(tools, null));
viewer.setEditable(false);
viewer.setDocument(new Document());
viewer.getTextWidget().setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
Font font= JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT);
viewer.getTextWidget().setFont(font);
Control control= viewer.getControl();
data= new GridData(GridData.FILL_BOTH);
data.heightHint= convertHeightInCharsToPixels(5);
control.setLayoutData(data);
return viewer;
}
public void createSpacer(Composite parent) {
Label spacer= new Label(parent, SWT.NONE);
GridData data= new GridData();
data.horizontalAlignment= GridData.FILL;
data.verticalAlignment= GridData.BEGINNING;
data.heightHint= 4;
spacer.setLayoutData(data);
}
private static GridData getButtonGridData(Button button) {
GridData data= new GridData(GridData.FILL_HORIZONTAL);
data.widthHint= SWTUtil.getButtonWidthHint(button);
data.heightHint= SWTUtil.getButtonHeigthHint(button);
return data;
}
private void selectionChanged1() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
if (selection.size() == 1) {
Template template= (Template) selection.getFirstElement();
fPatternViewer.getTextWidget().setText(template.getPattern());
} else {
fPatternViewer.getTextWidget().setText(""); //$NON-NLS-1$
}
updateButtons();
}
private void updateButtons() {
int selectionCount= ((IStructuredSelection) fTableViewer.getSelection()).size();
int itemCount= fTableViewer.getTable().getItemCount();
fEditButton.setEnabled(selectionCount == 1);
fExportButton.setEnabled(selectionCount > 0);
fRemoveButton.setEnabled(selectionCount > 0 && selectionCount <= itemCount);
fEnableAllButton.setEnabled(itemCount > 0);
fDisableAllButton.setEnabled(itemCount > 0);
}
private void add() {
Template template= new Template();
ContextTypeRegistry registry=ContextTypeRegistry.getInstance();
ContextType type= registry.getContextType("java");
String contextTypeName;
if (type != null)
contextTypeName= type.getName();
else {
Iterator iterator= registry.iterator();
contextTypeName= (String) iterator.next();
}
template.setContext(contextTypeName); //$NON-NLS-1$
EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, false);
if (dialog.open() == dialog.OK) {
fTemplates.add(template);
fTableViewer.refresh();
fTableViewer.setChecked(template, template.isEnabled());
fTableViewer.setSelection(new StructuredSelection(template));
}
}
private void edit() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
Object[] objects= selection.toArray();
if ((objects == null) || (objects.length != 1))
return;
Template template= (Template) selection.getFirstElement();
edit(template);
}
private void edit(Template template) {
EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, true);
if (dialog.open() == dialog.OK) {
fTableViewer.refresh(template);
fTableViewer.setChecked(template, template.isEnabled());
fTableViewer.setSelection(new StructuredSelection(template));
}
}
private void import_() {
FileDialog dialog= new FileDialog(getShell());
dialog.setText(TemplateMessages.getString("TemplatePreferencePage.import.title")); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.import.extension")}); //$NON-NLS-1$
String path= dialog.open();
if (path == null)
return;
try {
fTemplates.addFromFile(new File(path));
fTableViewer.refresh();
fTableViewer.setAllChecked(false);
fTableViewer.setCheckedElements(getEnabledTemplates());
} catch (CoreException e) {
openReadErrorDialog(e);
}
}
private void exportAll() {
export(fTemplates);
}
private void export() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
Object[] templates= selection.toArray();
TemplateSet templateSet= new TemplateSet();
for (int i= 0; i != templates.length; i++)
templateSet.add((Template) templates[i]);
export(templateSet);
}
private void export(TemplateSet templateSet) {
FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
dialog.setText(TemplateMessages.getFormattedString("TemplatePreferencePage.export.title", new Integer(templateSet.getTemplates().length))); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.export.extension")}); //$NON-NLS-1$
dialog.setFileName(TemplateMessages.getString("TemplatePreferencePage.export.filename")); //$NON-NLS-1$
String path= dialog.open();
if (path == null)
return;
try {
templateSet.saveToFile(new File(path));
} catch (CoreException e) {
JavaPlugin.log(e);
openWriteErrorDialog(e);
}
}
private void remove() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
Iterator elements= selection.iterator();
while (elements.hasNext()) {
Template template= (Template) elements.next();
fTemplates.remove(template);
}
fTableViewer.refresh();
}
private void enableAll(boolean enable) {
Template[] templates= fTemplates.getTemplates();
for (int i= 0; i != templates.length; i++)
templates[i].setEnabled(enable);
fTableViewer.setAllChecked(enable);
}
/*
* @see IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {}
/*
* @see Control#setVisible(boolean)
*/
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible)
setTitle(TemplateMessages.getString("TemplatePreferencePage.title")); //$NON-NLS-1$
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fFormatButton.setSelection(prefs.getDefaultBoolean(PREF_FORMAT_TEMPLATES));
try {
fTemplates.restoreDefaults();
} catch (CoreException e) {
JavaPlugin.log(e);
openReadErrorDialog(e);
}
// refresh
fTableViewer.refresh();
fTableViewer.setAllChecked(false);
fTableViewer.setCheckedElements(getEnabledTemplates());
}
/*
* @see PreferencePage#performOk()
*/
public boolean performOk() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
prefs.setValue(PREF_FORMAT_TEMPLATES, fFormatButton.getSelection());
try {
fTemplates.save();
} catch (CoreException e) {
JavaPlugin.log(e);
openWriteErrorDialog(e);
}
return super.performOk();
}
/*
* @see PreferencePage#performCancel()
*/
public boolean performCancel() {
try {
fTemplates.reset();
} catch (CoreException e) {
JavaPlugin.log(e);
openReadErrorDialog(e);
}
return super.performCancel();
}
/**
* Initializes the default values of this page in the preference bundle.
* Will be called on startup of the JavaPlugin
*/
public static void initDefaults(IPreferenceStore prefs) {
prefs.setDefault(PREF_FORMAT_TEMPLATES, true);
}
public static boolean useCodeFormatter() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_FORMAT_TEMPLATES);
}
private void openReadErrorDialog(CoreException e) {
ErrorDialog.openError(getShell(),
TemplateMessages.getString("TemplatePreferencePage.error.read.title"), //$NON-NLS-1$
null, e.getStatus());
}
private void openWriteErrorDialog(CoreException e) {
ErrorDialog.openError(getShell(),
TemplateMessages.getString("TemplatePreferencePage.error.write.title"), //$NON-NLS-1$
null, e.getStatus());
}
}
|
8,082 |
Bug 8082 template pref page: export overwrites without warning
|
export from template pref page overwrites files without warning this is never good - you can lose templates you have saved on your disk somewhere
|
resolved fixed
|
e63e83a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T10:04:23Z | 2002-01-23T12:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ExperimentalProposal.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jdt.internal.corext.template.TemplateMessages;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI;
/**
* An experimental proposal.
*/
public class ExperimentalProposal extends JavaCompletionProposal {
private int[] fPositionOffsets;
private int[] fPositionLengths;
private ITextViewer fViewer;
private IRegion fSelectedRegion; // initialized by apply()
/**
* Creates a template proposal with a template and its context.
* @param template the template
* @param context the context in which the template was requested.
* @param image the icon of the proposal.
*/
public ExperimentalProposal(String replacementString, int replacementOffset, int replacementLength, Image image,
String displayString, int[] positionOffsets, int[] positionLengths, ITextViewer viewer)
{
super(replacementString, replacementOffset, replacementLength, image, displayString);
fPositionOffsets= positionOffsets;
fPositionLengths= positionLengths;
fViewer= viewer;
}
/*
* @see ICompletionProposalExtension#apply(IDocument, char)
*/
public void apply(IDocument document, char trigger, int offset) {
super.apply(document, trigger, offset);
int replacementOffset= getReplacementOffset();
String replacementString= getReplacementString();
try {
LinkedPositionManager manager= new LinkedPositionManager(document);
for (int i= 0; i != fPositionOffsets.length; i++)
manager.addPosition(replacementOffset + fPositionOffsets[i], fPositionLengths[i]);
LinkedPositionUI editor= new LinkedPositionUI(fViewer, manager);
editor.setFinalCaretOffset(replacementOffset + replacementString.length());
editor.enter();
fSelectedRegion= editor.getSelectedRegion();
} catch (BadLocationException e) {
JavaPlugin.log(e);
openErrorDialog(e);
}
}
/**
* @see ICompletionProposal#getSelection(IDocument)
*/
public Point getSelection(IDocument document) {
if (fSelectedRegion == null)
return new Point(getReplacementOffset(), 0);
return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength());
}
private void openErrorDialog(BadLocationException e) {
Shell shell= fViewer.getTextWidget().getShell();
MessageDialog.openError(shell, TemplateMessages.getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$
}
}
|
8,082 |
Bug 8082 template pref page: export overwrites without warning
|
export from template pref page overwrites files without warning this is never good - you can lose templates you have saved on your disk somewhere
|
resolved fixed
|
e63e83a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T10:04:23Z | 2002-01-23T12:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ExperimentalResultCollector.java
|
package org.eclipse.jdt.internal.ui.text.java;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.jface.text.ITextViewer;
/**
* Bin to collect the proposal of the infrastructure on code assist in a java text.
*/
public class ExperimentalResultCollector extends ResultCollector {
private ITextViewer fViewer;
protected JavaCompletionProposal createMethodCallCompletion(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName, char[] completionName, int modifiers, int start, int end) {
JavaCompletionProposal original= super.createMethodCallCompletion(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end);
// XXX hack to handle empty code completion
if ((completionName.length == 0) || ((completionName.length == 1) && completionName[0] == ')'))
return original;
int count= parameterNames.length;
int[] offsets= new int[count];
int[] lengths= new int[count];
StringBuffer buffer= new StringBuffer();
buffer.append(name);
buffer.append('(');
for (int i= 0; i != count; i++) {
if (i != 0)
buffer.append(", ");
offsets[i]= buffer.length();
buffer.append(parameterNames[i]);
lengths[i]= buffer.length() - offsets[i];
}
buffer.append(')');
return new JavaCompletionProposal(buffer.toString(), start, end - start, original.getImage(),
original.getDisplayString());
// return new ExperimentalProposal(buffer.toString(), start, end - start, original.getImage(),
// original.getDisplayString(), offsets, lengths, fViewer);
}
/**
* Sets the viewer.
* @param viewer The viewer to set
*/
public void setViewer(ITextViewer viewer) {
fViewer= viewer;
}
}
|
12,283 |
Bug 12283 exception in organize import dialog
|
20020321++ i pressed 'next' in the dialog that shows up on organize imports java.lang.ArrayIndexOutOfBoundsException: 2 at org.eclipse.jdt.internal.ui.dialogs.FilteredList.getSelection (FilteredList.java:337) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.getSelect edElements(AbstractElementListSelectionDialog.java:222) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.validateC urrentSelection(AbstractElementListSelectionDialog.java:270) at org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog.turnPage (MultiElementListSelectionDialog.java:240) at org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog.buttonPresse d(MultiElementListSelectionDialog.java:170) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.access$su perOpen(AbstractElementListSelectionDialog.java:400) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.access$2 (AbstractElementListSelectionDialog.java:399) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog$4.run (AbstractElementListSelectionDialog.java:393) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java (Compiled Code)) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.open (AbstractElementListSelectionDialog.java:391) at org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog.open (MultiElementListSelectionDialog.java:99) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction.doChooseImports (OrganizeImportsAction.java:123) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction.access$0 (OrganizeImportsAction.java:107) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction$1.chooseImports (OrganizeImportsAction.java:102) at org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.run (OrganizeImportsOperation.java:355) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1338) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run (WorkbenchRunnableAdapter.java:32) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.inter nalRun(BusyIndicatorRunnableContext.java:107) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run (BusyIndicatorRunnableContext.java:74) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java (Compiled Code)) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run (BusyIndicatorRunnableContext.java:120) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction.run (OrganizeImportsAction.java:79) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run (RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:705) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396)
|
resolved fixed
|
5c48792
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T14:52:30Z | 2002-03-26T16:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/AbstractElementListSelectionDialog.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.dialogs;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ILabelProvider;
/**
* An abstract class to select elements out of a list of elements.
*/
public abstract class AbstractElementListSelectionDialog extends SelectionStatusDialog {
private ILabelProvider fRenderer;
private boolean fIgnoreCase= true;
private boolean fIsMultipleSelection= false;
private boolean fMatchEmptyString= true;
private boolean fAllowDuplicates= true;
private Label fMessage;
protected FilteredList fFilteredList;
private Text fFilterText;
private ISelectionValidator fValidator;
private String fFilter= null;
private String fEmptyListMessage= ""; //$NON-NLS-1$
private String fEmptySelectionMessage= ""; //$NON-NLS-1$
private int fWidth= 60;
private int fHeight= 18;
private Object[] fSelection= new Object[0];
/**
* Constructs a list selection dialog.
* @param renderer The label renderer used
* @param ignoreCase Decides if the match string ignores lower/upppr case
* @param multipleSelection Allow multiple selection
*/
protected AbstractElementListSelectionDialog(Shell parent, ILabelProvider renderer)
{
super(parent);
fRenderer= renderer;
int shellStyle= getShellStyle();
setShellStyle(shellStyle | SWT.MAX | SWT.RESIZE);
}
/**
* Handles default selection (double click).
* By default, the OK button is pressed.
*/
protected void handleDefaultSelected() {
if (validateCurrentSelection())
buttonPressed(IDialogConstants.OK_ID);
}
/**
* Specifies if sorting, filtering and folding is case sensitive.
*/
public void setIgnoreCase(boolean ignoreCase) {
fIgnoreCase= ignoreCase;
}
/**
* Returns if sorting, filtering and folding is case sensitive.
*/
public boolean isCaseIgnored() {
return fIgnoreCase;
}
/**
* Specifies whether everything or nothing should be filtered on
* empty filter string.
*/
public void setMatchEmptyString(boolean matchEmptyString) {
fMatchEmptyString= matchEmptyString;
}
/**
* Specifies if multiple selection is allowed.
*/
public void setMultipleSelection(boolean multipleSelection) {
fIsMultipleSelection= multipleSelection;
}
/**
* Specifies whether duplicate entries are displayed or not.
*/
public void setAllowDuplicates(boolean allowDuplicates) {
fAllowDuplicates= allowDuplicates;
}
/**
* Sets the list size in unit of characters.
* @param width the width of the list.
* @param height the height of the list.
*/
public void setSize(int width, int height) {
fWidth= width;
fHeight= height;
}
/**
* Sets the message to be displayed if the list is empty.
* @param message the message to be displayed.
*/
public void setEmptyListMessage(String message) {
fEmptyListMessage= message;
}
/**
* Sets the message to be displayed if the selection is empty.
* @param message the message to be displayed.
*/
public void setEmptySelectionMessage(String message) {
fEmptySelectionMessage= message;
}
/**
* Sets an optional validator to check if the selection is valid.
* The validator is invoked whenever the selection changes.
* @param validator the validator to validate the selection.
*/
public void setValidator(ISelectionValidator validator) {
fValidator= validator;
}
/**
* Sets the elements of the list (widget).
* To be called within open().
* @param elements the elements of the list.
*/
protected void setListElements(Object[] elements) {
Assert.isNotNull(fFilteredList);
fFilteredList.setElements(elements);
}
/**
* Sets the filter pattern.
* @param filter the filter pattern.
*/
public void setFilter(String filter) {
if (fFilterText == null)
fFilter= filter;
else
fFilterText.setText(filter);
}
/**
* Returns the current filter pattern.
* @return returns the current filter pattern or <code>null<code> if filter was not set.
*/
public String getFilter() {
if (fFilteredList == null)
return fFilter;
else
return fFilteredList.getFilter();
}
/**
* Returns the indices referring the current selection.
* To be called within open().
* @return returns the indices of the current selection.
*/
protected int[] getSelectionIndices() {
Assert.isNotNull(fFilteredList);
return fFilteredList.getSelectionIndices();
}
/**
* Returns an index referring the first current selection.
* To be called within open().
* @return returns the indices of the current selection.
*/
protected int getSelectionIndex() {
Assert.isNotNull(fFilteredList);
return fFilteredList.getSelectionIndex();
}
/**
* Sets the selection referenced by an array of elements.
* To be called within open().
* @param selection the indices of the selection.
*/
protected void setSelection(Object[] selection) {
Assert.isNotNull(fFilteredList);
fFilteredList.setSelection(selection);
}
/**
* Returns an array of the currently selected elements.
* To be called within or after open().
* @return returns an array of the currently selected elements.
*/
protected Object[] getSelectedElements() {
Assert.isNotNull(fFilteredList);
return fFilteredList.getSelection();
}
/**
* Returns all elements which are folded together to one entry in the list.
* @param index the index selecting the entry in the list.
* @return returns an array of elements folded together.
*/
public Object[] getFoldedElements(int index) {
Assert.isNotNull(fFilteredList);
return fFilteredList.getFoldedElements(index);
}
/**
* Creates the message text widget and sets layout data.
* @param composite the parent composite of the message area.
*/
protected Label createMessageArea(Composite composite) {
Label label= super.createMessageArea(composite);
GridData data= new GridData();
data.grabExcessVerticalSpace= false;
data.grabExcessHorizontalSpace= true;
data.horizontalAlignment= GridData.FILL;
data.verticalAlignment= GridData.BEGINNING;
label.setLayoutData(data);
fMessage= label;
return label;
}
/**
* Handles a selection changed event.
* By default, the current selection is validated.
*/
protected void handleSelectionChanged() {
validateCurrentSelection();
}
/**
* Validates the current selection and updates the status line
* accordingly.
*/
protected boolean validateCurrentSelection() {
Assert.isNotNull(fFilteredList);
IStatus status;
Object[] elements= getSelectedElements();
if (elements.length > 0) {
if (fValidator != null) {
status= fValidator.validate(elements);
} else {
status= new StatusInfo();
}
} else {
if (fFilteredList.isEmpty()) {
status= new StatusInfo(IStatus.ERROR, fEmptyListMessage);
} else {
status= new StatusInfo(IStatus.ERROR, fEmptySelectionMessage);
}
}
updateStatus(status);
return status.isOK();
}
/*
* @see Dialog#cancelPressed
*/
protected void cancelPressed() {
setResult(null);
super.cancelPressed();
}
/**
* Creates a filtered list.
* @param parent the parent composite.
* @return returns the filtered list widget.
*/
protected FilteredList createFilteredList(Composite parent) {
int flags= SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL |
(fIsMultipleSelection ? SWT.MULTI : SWT.SINGLE);
FilteredList list= new FilteredList(parent, flags, fRenderer,
fIgnoreCase, fAllowDuplicates, fMatchEmptyString);
GridData data= new GridData();
data.widthHint= convertWidthInCharsToPixels(fWidth);
data.heightHint= convertHeightInCharsToPixels(fHeight);
data.grabExcessVerticalSpace= true;
data.grabExcessHorizontalSpace= true;
data.horizontalAlignment= GridData.FILL;
data.verticalAlignment= GridData.FILL;
list.setLayoutData(data);
list.setFilter((fFilter == null ? "" : fFilter)); //$NON-NLS-1$
list.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
handleDefaultSelected();
}
public void widgetSelected(SelectionEvent e) {
handleWidgetSelected();
}
});
fFilteredList= list;
return list;
}
// 3515
private void handleWidgetSelected() {
Object[] newSelection= fFilteredList.getSelection();
if (newSelection.length != fSelection.length) {
fSelection= newSelection;
handleSelectionChanged();
} else {
for (int i= 0; i != newSelection.length; i++) {
if (!newSelection[i].equals(fSelection[i])) {
fSelection= newSelection;
handleSelectionChanged();
break;
}
}
}
}
protected Text createFilterText(Composite parent) {
Text text= new Text(parent, SWT.BORDER);
GridData data= new GridData();
data.grabExcessVerticalSpace= false;
data.grabExcessHorizontalSpace= true;
data.horizontalAlignment= GridData.FILL;
data.verticalAlignment= GridData.BEGINNING;
text.setLayoutData(data);
text.setText((fFilter == null ? "" : fFilter)); //$NON-NLS-1$
Listener listener= new Listener() {
public void handleEvent(Event e) {
fFilteredList.setFilter(fFilterText.getText());
}
};
text.addListener(SWT.Modify, listener);
text.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ARROW_DOWN)
fFilteredList.setFocus();
}
public void keyReleased(KeyEvent e) {}
});
fFilterText= text;
return text;
}
/*
* @see Window#open()
*/
public int open() {
BusyIndicator.showWhile(null, new Runnable() {
public void run() {
access$superOpen();
}
});
return getReturnCode();
}
private void access$superOpen() {
super.open();
}
/*
* @see Window#create(Shell)
*/
public void create() {
super.create();
Assert.isNotNull(fFilteredList);
if (fFilteredList.isEmpty()) {
handleEmptyList();
} else {
validateCurrentSelection();
fFilterText.selectAll();
fFilterText.setFocus();
}
}
/**
* Handles empty list by disabling widgets.
*/
protected void handleEmptyList() {
fMessage.setEnabled(false);
fFilterText.setEnabled(false);
fFilteredList.setEnabled(false);
}
}
|
12,283 |
Bug 12283 exception in organize import dialog
|
20020321++ i pressed 'next' in the dialog that shows up on organize imports java.lang.ArrayIndexOutOfBoundsException: 2 at org.eclipse.jdt.internal.ui.dialogs.FilteredList.getSelection (FilteredList.java:337) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.getSelect edElements(AbstractElementListSelectionDialog.java:222) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.validateC urrentSelection(AbstractElementListSelectionDialog.java:270) at org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog.turnPage (MultiElementListSelectionDialog.java:240) at org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog.buttonPresse d(MultiElementListSelectionDialog.java:170) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.access$su perOpen(AbstractElementListSelectionDialog.java:400) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.access$2 (AbstractElementListSelectionDialog.java:399) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog$4.run (AbstractElementListSelectionDialog.java:393) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java (Compiled Code)) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.open (AbstractElementListSelectionDialog.java:391) at org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog.open (MultiElementListSelectionDialog.java:99) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction.doChooseImports (OrganizeImportsAction.java:123) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction.access$0 (OrganizeImportsAction.java:107) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction$1.chooseImports (OrganizeImportsAction.java:102) at org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.run (OrganizeImportsOperation.java:355) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1338) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run (WorkbenchRunnableAdapter.java:32) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.inter nalRun(BusyIndicatorRunnableContext.java:107) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run (BusyIndicatorRunnableContext.java:74) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java (Compiled Code)) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run (BusyIndicatorRunnableContext.java:120) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction.run (OrganizeImportsAction.java:79) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run (RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:705) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396)
|
resolved fixed
|
5c48792
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T14:52:30Z | 2002-03-26T16:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/FilteredList.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.dialogs;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionListener;
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.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jdt.internal.core.Assert;
import org.eclipse.jdt.internal.ui.util.StringMatcher;
/**
* A composite widget which holds a list of elements for user selection.
* The elements are sorted alphabetically.
* Optionally, the elements can be filtered and duplicate entries can
* be hidden (folding).
*/
public class FilteredList extends Composite {
public interface FilterMatcher {
/**
* Sets the filter.
*
* @param pattern the filter pattern.
* @param ignoreCase a flag indicating whether pattern matching is case insensitive or not.
* @param ignoreWildCards a flag indicating whether wildcard characters are interpreted or not.
*/
void setFilter(String pattern, boolean ignoreCase, boolean ignoreWildCards);
/**
* Returns <code>true</code> if the object matches the pattern, <code>false</code> otherwise.
* <code>setFilter()</code> must have been called at least once prior to a call to this method.
*/
boolean match(Object element);
}
private class DefaultFilterMatcher implements FilterMatcher {
private StringMatcher fMatcher;
public void setFilter(String pattern, boolean ignoreCase, boolean ignoreWildCards) {
fMatcher= new StringMatcher(pattern + '*', ignoreCase, ignoreWildCards);
}
public boolean match(Object element) {
return fMatcher.match(fRenderer.getText(element));
}
}
private Table fList;
private ILabelProvider fRenderer;
private boolean fMatchEmtpyString= true;
private boolean fIgnoreCase;
private boolean fAllowDuplicates;
private String fFilter= ""; //$NON-NLS-1$
private TwoArrayQuickSorter fSorter;
private Object[] fElements= new Object[0];
private Label[] fLabels;
private Vector fImages= new Vector();
private int[] fFoldedIndices;
private int fFoldedCount;
private int[] fFilteredIndices;
private int fFilteredCount;
private FilterMatcher fFilterMatcher= new DefaultFilterMatcher();
private Comparator fComparator;
private UpdateThread fUpdateThread;
private static class Label {
public final String string;
public final Image image;
public Label(String string, Image image) {
this.string= string;
this.image= image;
}
public boolean equals(Label label) {
if (label == null)
return false;
return
string.equals(label.string) &&
image.equals(label.image);
}
}
private final class LabelComparator implements Comparator {
private boolean fIgnoreCase;
LabelComparator(boolean ignoreCase) {
fIgnoreCase= ignoreCase;
}
public int compare(Object left, Object right) {
Label leftLabel= (Label) left;
Label rightLabel= (Label) right;
int value;
if (fComparator == null) {
value= fIgnoreCase
? leftLabel.string.compareToIgnoreCase(rightLabel.string)
: leftLabel.string.compareTo(rightLabel.string);
} else {
value= fComparator.compare(leftLabel.string, rightLabel.string);
}
if (value != 0)
return value;
// images are allowed to be null
if (leftLabel.image == null) {
return (rightLabel.image == null) ? 0 : -1;
} else if (rightLabel.image == null) {
return +1;
} else {
return
fImages.indexOf(leftLabel.image) -
fImages.indexOf(rightLabel.image);
}
}
}
/**
* Constructs a new instance of a filtered list.
* @param parent the parent composite.
* @param style the widget style.
* @param renderer the label renderer.
* @param ignoreCase specifies whether sorting and folding is case sensitive.
* @param allowDuplicates specifies whether folding of duplicates is desired.
* @param matchEmptyString specifies whether empty filter strings should filter everything or nothing.
*/
public FilteredList(Composite parent, int style, ILabelProvider renderer,
boolean ignoreCase, boolean allowDuplicates, boolean matchEmptyString)
{
super(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
setLayout(layout);
fList= new Table(this, style);
fList.setLayoutData(new GridData(GridData.FILL_BOTH));
fList.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
fRenderer.dispose();
if (fUpdateThread != null)
fUpdateThread.requestStop();
}
});
fRenderer= renderer;
fIgnoreCase= ignoreCase;
fSorter= new TwoArrayQuickSorter(new LabelComparator(ignoreCase));
fAllowDuplicates= allowDuplicates;
fMatchEmtpyString= matchEmptyString;
}
/**
* Sets the list of elements.
* @param elements the elements to be shown in the list.
*/
public void setElements(Object[] elements) {
if (elements == null) {
fElements= new Object[0];
} else {
// copy list for sorting
fElements= new Object[elements.length];
System.arraycopy(elements, 0, fElements, 0, elements.length);
}
int length= fElements.length;
// fill labels
fLabels= new Label[length];
Set imageSet= new HashSet();
for (int i= 0; i != length; i++) {
String text= fRenderer.getText(fElements[i]);
Image image= fRenderer.getImage(fElements[i]);
fLabels[i]= new Label(text, image);
imageSet.add(image);
}
fImages.clear();
fImages.addAll(imageSet);
fSorter.sort(fLabels, fElements);
fFilteredIndices= new int[length];
fFoldedIndices= new int[length];
updateList();
}
/**
* Tests if the list (before folding and filtering) is empty.
* @return returns <code>true</code> if the list is empty, <code>false</code> otherwise.
*/
public boolean isEmpty() {
return (fElements == null) || (fElements.length == 0);
}
/**
* Sets the filter matcher.
*/
public void setFilterMatcher(FilterMatcher filterMatcher) {
Assert.isNotNull(filterMatcher);
fFilterMatcher= filterMatcher;
}
/**
* Sets a custom comparator for sorting the list.
*/
public void setComparator(Comparator comparator) {
Assert.isNotNull(comparator);
fComparator= comparator;
}
/**
* Adds a selection listener to the list.
* @param listener the selection listener to be added.
*/
public void addSelectionListener(SelectionListener listener) {
fList.addSelectionListener(listener);
}
/**
* Removes a selection listener from the list.
* @param listener the selection listener to be removed.
*/
public void removeSelectionListener(SelectionListener listener) {
fList.removeSelectionListener(listener);
}
/**
* Sets the selection of the list.
* @param selection an array of indices specifying the selection.
*/
public void setSelection(int[] selection) {
fList.setSelection(selection);
}
/**
* Returns the selection of the list.
* @return returns an array of indices specifying the current selection.
*/
public int[] getSelectionIndices() {
return fList.getSelectionIndices();
}
/**
* Returns the selection of the list.
* This is a convenience function for <code>getSelectionIndices()</code>.
* @return returns the index of the selection, -1 for no selection.
*/
public int getSelectionIndex() {
return fList.getSelectionIndex();
}
/**
* Sets the selection of the list.
* @param elements the array of elements to be selected.
*/
public void setSelection(Object[] elements) {
if ((elements == null) || (fElements == null))
return;
// fill indices
int[] indices= new int[elements.length];
for (int i= 0; i != elements.length; i++) {
int j;
for (j= 0; j != fFoldedCount; j++) {
int max= (j == fFoldedCount - 1)
? fFilteredCount
: fFoldedIndices[j + 1];
int l;
for (l= fFoldedIndices[j]; l != max; l++) {
// found matching element?
if (fElements[fFilteredIndices[l]].equals(elements[i])) {
indices[i]= j;
break;
}
}
if (l != max)
break;
}
// not found
if (j == fFoldedCount)
indices[i] = 0;
}
fList.setSelection(indices);
}
/**
* Returns an array of the selected elements. The type of the elements
* returned in the list are the same as the ones passed with
* <code>setElements</code>. The array does not contain the rendered strings.
* @return returns the array of selected elements.
*/
public Object[] getSelection() {
if (fList.isDisposed() || (fList.getSelectionCount() == 0))
return new Object[0];
int[] indices= fList.getSelectionIndices();
Object[] elements= new Object[indices.length];
for (int i= 0; i != indices.length; i++)
elements[i]= fElements[fFilteredIndices[fFoldedIndices[indices[i]]]];
return elements;
}
/**
* Sets the filter pattern. Current only prefix filter patterns are supported.
* @param filter the filter pattern.
*/
public void setFilter(String filter) {
fFilter= (filter == null) ? "" : filter; //$NON-NLS-1$
updateList();
}
private void updateList() {
fFilteredCount= filter();
fFoldedCount= fold();
if (fUpdateThread != null)
fUpdateThread.requestStop();
fUpdateThread= new UpdateThread(new TableUpdater(fList, fFoldedCount));
fUpdateThread.start();
}
/**
* Returns the filter pattern.
* @return returns the filter pattern.
*/
public String getFilter() {
return fFilter;
}
/**
* Returns all elements which are folded together to one entry in the list.
* @param index the index selecting the entry in the list.
* @return returns an array of elements folded together, <code>null</code> if index is out of range.
*/
public Object[] getFoldedElements(int index) {
if ((index < 0) || (index >= fFoldedCount))
return null;
int start= fFoldedIndices[index];
int count= (index == fFoldedCount - 1)
? fFilteredCount - start
: fFoldedIndices[index + 1] - start;
Object[] elements= new Object[count];
for (int i= 0; i != count; i++)
elements[i]= fElements[fFilteredIndices[start + i]];
return elements;
}
/*
* Folds duplicate entries. Two elements are considered as a pair of
* duplicates if they coiincide in the rendered string and image.
* @return returns the number of elements after folding.
*/
private int fold() {
if (fAllowDuplicates) {
for (int i= 0; i != fFilteredCount; i++)
fFoldedIndices[i]= i; // identity mapping
return fFilteredCount;
} else {
int k= 0;
Label last= null;
for (int i= 0; i != fFilteredCount; i++) {
int j= fFilteredIndices[i];
Label current= fLabels[j];
if (! current.equals(last)) {
fFoldedIndices[k]= i;
k++;
last= current;
}
}
return k;
}
}
/*
* Filters the list with the filter pattern.
* @return returns the number of elements after filtering.
*/
private int filter() {
if (((fFilter == null) || (fFilter.length() == 0)) && !fMatchEmtpyString)
return 0;
fFilterMatcher.setFilter(fFilter.trim(), fIgnoreCase, false);
int k= 0;
for (int i= 0; i != fElements.length; i++) {
if (fFilterMatcher.match(fElements[i]))
fFilteredIndices[k++]= i;
}
return k;
}
private interface IncrementalRunnable extends Runnable {
public int getCount();
public void cancel();
}
private class TableUpdater implements IncrementalRunnable {
private final Display fDisplay;
private final Table fTable;
private final int fCount;
private int fIndex;
public TableUpdater(Table table, int count) {
fTable= table;
fDisplay= table.getDisplay();
fCount= count;
}
/*
* @see IncrementalRunnable#getCount()
*/
public int getCount() {
return fCount + 1;
}
/*
* @see IncrementalRunnable#cancel()
*/
public void cancel() {
fIndex= 0;
}
/*
* @see Runnable#run()
*/
public void run() {
final int index= fIndex++;
fDisplay.syncExec(new Runnable() {
public void run() {
if (fTable.isDisposed())
return;
final int itemCount= fTable.getItemCount();
if (index < fCount) {
final TableItem item= (index < itemCount)
? fTable.getItem(index)
: new TableItem(fTable, SWT.NONE);
final Label label= fLabels[fFilteredIndices[fFoldedIndices[index]]];
item.setText(label.string);
item.setImage(label.image);
// select first item
if (index == 0) {
fTable.setSelection(0);
fTable.notifyListeners(SWT.Selection, new Event());
}
// finish
} else {
if (fCount < itemCount) {
fTable.setRedraw(false);
fTable.remove(fCount, itemCount - 1);
fTable.setRedraw(true);
}
// table empty -> no selection
if (fCount == 0)
fTable.notifyListeners(SWT.Selection, new Event());
}
}
});
}
}
private static class UpdateThread extends Thread {
/** The incremental runnable */
private final IncrementalRunnable fRunnable;
/** A flag indicating a thread stop request */
private boolean fStop;
/**
* Creates an update thread.
*/
public UpdateThread(IncrementalRunnable runnable) {
fRunnable= runnable;
}
/**
* Requests the thread to stop.
*/
public void requestStop() {
fStop= true;
}
/**
* @see Runnable#run()
*/
public void run() {
final int count= fRunnable.getCount();
for (int i= 0; i != count; i++) {
if (i % 50 == 0)
try { Thread.sleep(10); } catch (InterruptedException e) {}
if (fStop) {
fRunnable.cancel();
break;
}
fRunnable.run();
}
}
}
}
|
12,283 |
Bug 12283 exception in organize import dialog
|
20020321++ i pressed 'next' in the dialog that shows up on organize imports java.lang.ArrayIndexOutOfBoundsException: 2 at org.eclipse.jdt.internal.ui.dialogs.FilteredList.getSelection (FilteredList.java:337) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.getSelect edElements(AbstractElementListSelectionDialog.java:222) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.validateC urrentSelection(AbstractElementListSelectionDialog.java:270) at org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog.turnPage (MultiElementListSelectionDialog.java:240) at org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog.buttonPresse d(MultiElementListSelectionDialog.java:170) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.access$su perOpen(AbstractElementListSelectionDialog.java:400) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.access$2 (AbstractElementListSelectionDialog.java:399) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog$4.run (AbstractElementListSelectionDialog.java:393) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java (Compiled Code)) at org.eclipse.jdt.internal.ui.dialogs.AbstractElementListSelectionDialog.open (AbstractElementListSelectionDialog.java:391) at org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog.open (MultiElementListSelectionDialog.java:99) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction.doChooseImports (OrganizeImportsAction.java:123) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction.access$0 (OrganizeImportsAction.java:107) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction$1.chooseImports (OrganizeImportsAction.java:102) at org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.run (OrganizeImportsOperation.java:355) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1338) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run (WorkbenchRunnableAdapter.java:32) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.inter nalRun(BusyIndicatorRunnableContext.java:107) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run (BusyIndicatorRunnableContext.java:74) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java (Compiled Code)) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run (BusyIndicatorRunnableContext.java:120) at org.eclipse.jdt.internal.ui.javaeditor.OrganizeImportsAction.run (OrganizeImportsAction.java:79) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run (RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:705) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396)
|
resolved fixed
|
5c48792
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T14:52:30Z | 2002-03-26T16:26: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.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.core.runtime.IStatus;
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;
fNextButton.setEnabled(isOK && (fCurrentPage < fNumberOfPages - 1));
fBackButton.setEnabled(fCurrentPage != 0);
boolean isAllOK= isOK;
for (int i= 0; i != fNumberOfPages; i++)
isAllOK = isAllOK && fPages[i].okState;
fFinishButton.setEnabled(isAllOK);
}
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);
if (selectedElements != null)
setSelection(selectedElements);
}
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;
}
}
|
13,558 |
Bug 13558 move cu with ref update broken
|
20020409 try moving a cu from 1 package to another - dnd of not - no not press 'preview' nothing happens - file is not moved! it is moved if you do press 'preview'
|
resolved fixed
|
fd51532
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T16:24:19Z | 2002-04-11T18:33:20Z |
org.eclipse.jdt.ui/core
| |
13,558 |
Bug 13558 move cu with ref update broken
|
20020409 try moving a cu from 1 package to another - dnd of not - no not press 'preview' nothing happens - file is not moved! it is moved if you do press 'preview'
|
resolved fixed
|
fd51532
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T16:24:19Z | 2002-04-11T18:33:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/MoveRefactoring.java
| |
12,593 |
Bug 12593 code assist inserts fully qualified type names (ignoring preferences)
|
20020328 package p; import java.util.List; public abstract class Test { public void foo() { List l= new List(){<CODE ASSIST HERE>} } } choose the 'addAll' method (any of the two) you get the fully qualified name for Collections (although my java editor/code assist preference says it should insert an import statement)
|
resolved fixed
|
b37ed19
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T18:41:45Z | 2002-04-02T12:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/IJavaCompletionProposal.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.java;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
public interface IJavaCompletionProposal extends ICompletionProposal {
int getRelevance();
}
|
12,593 |
Bug 12593 code assist inserts fully qualified type names (ignoring preferences)
|
20020328 package p; import java.util.List; public abstract class Test { public void foo() { List l= new List(){<CODE ASSIST HERE>} } } choose the 'addAll' method (any of the two) you get the fully qualified name for Collections (although my java editor/code assist preference says it should insert an import statement)
|
resolved fixed
|
b37ed19
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T18:41:45Z | 2002-04-02T12:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/MethodStubCompletionProposal.java
| |
12,593 |
Bug 12593 code assist inserts fully qualified type names (ignoring preferences)
|
20020328 package p; import java.util.List; public abstract class Test { public void foo() { List l= new List(){<CODE ASSIST HERE>} } } choose the 'addAll' method (any of the two) you get the fully qualified name for Collections (although my java editor/code assist preference says it should insert an import statement)
|
resolved fixed
|
b37ed19
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T18:41:45Z | 2002-04-02T12:20:00Z |
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.IImportDeclaration;
import org.eclipse.jdt.core.IJavaProject;
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;
/**
* 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', ' ', '=', ';' };
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 IJavaProject fJavaProject;
private ICompilationUnit fCompilationUnit; // set when imports can be added
private int fCodeAssistOffset;
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= JavaPluginImages.DESC_OBJS_CLASS;
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, 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= getMemberDescriptor(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= JavaPluginImages.DESC_OBJS_INTERFACE;
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, 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), null, buf.toString(), relevance);
proposal.setTriggerCharacters(VAR_TRIGGER);
fVariables.add(proposal);
}
private String getParameterSignature(char[][] parameterTypeNames, char[][] parameterNames) {
StringBuffer buf = new StringBuffer();
if (parameterTypeNames != null) {
for (int i = 0; i < parameterTypeNames.length; i++) {
if (i > 0) {
buf.append(',');
buf.append(' ');
}
buf.append(parameterTypeNames[i]);
if (parameterNames != 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) {
JavaCompletionProposal proposal= createMethodCallCompletion(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end, relevance);
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, returnTypeName.length == 0));
boolean hasOpeningBracket= completionName.length == 0 || (completionName.length > 0 && completionName[completionName.length - 1] == ')');
ProposalContextInformation contextInformation= null;
if (hasOpeningBracket && parameterTypeNames.length > 0) {
contextInformation= new ProposalContextInformation();
contextInformation.setInformationDisplayString(getParameterSignature(parameterTypeNames, parameterNames));
contextInformation.setContextDisplayString(proposal.getDisplayString());
contextInformation.setImage(proposal.getImage());
proposal.setContextInformation(contextInformation);
}
boolean userMustCompleteParameters= (contextInformation != null && completionName.length > 0);
char[] triggers= userMustCompleteParameters ? METHOD_WITH_ARGUMENTS_TRIGGERS : METHOD_TRIGGERS;
proposal.setTriggerCharacters(triggers);
if (userMustCompleteParameters) {
// set the cursor before the closing bracket
proposal.setCursorPosition(completionName.length - 1);
}
fMethods.add(proposal);
}
/*
* @see ICompletionRequestor#acceptModifier
*/
public void acceptModifier(char[] modifier, int start, int end, 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) {
// XXX: To be revised
JavaCompletionProposal proposal= createMethodDeclarationCompletion(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end, 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[][] 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 createMethodDeclarationCompletion(char[] declaringTypeName, char[] name, 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) {
IImportDeclaration importDeclaration= null;
if (containerName != null && fCompilationUnit != null) {
if (completion.equals(JavaModelUtil.concatenateName(containerName, typeName))) {
importDeclaration= fCompilationUnit.getImport(completion);
completion= typeName;
}
}
StringBuffer buf= new StringBuffer(typeName);
if (containerName != null) {
buf.append(" - "); //$NON-NLS-1$
if (containerName.length() > 0) {
buf.append(containerName);
} else {
buf.append(JavaTextMessages.getString("ResultCollector.default_package")); //$NON-NLS-1$
}
}
String name= buf.toString();
JavaCompletionProposal proposal= createCompletion(start, end, completion, descriptor, name, relevance);
proposal.setImportDeclaration(importDeclaration);
proposal.setProposalInfo(proposalInfo);
proposal.setTriggerCharacters(TYPE_TRIGGERS);
return proposal;
}
protected ImageDescriptor getMemberDescriptor(int modifiers) {
ImageDescriptor desc;
if (Flags.isPublic(modifiers)) {
desc= JavaPluginImages.DESC_MISC_PUBLIC;
} else if (Flags.isProtected(modifiers)) {
desc= JavaPluginImages.DESC_MISC_PROTECTED;
} else if (Flags.isPrivate(modifiers)) {
desc= JavaPluginImages.DESC_MISC_PRIVATE;
} else {
desc= JavaPluginImages.DESC_MISC_DEFAULT;
}
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) {
int length;
if (fUserReplacementLength == -1) {
length= fPreventEating ? fCodeAssistOffset - start : end - start;
} else {
length= fUserReplacementLength;
// extend length to begin at start
if (start < fCodeAssistOffset) {
length+= fCodeAssistOffset - start;
}
}
Image icon= (descriptor == null) ? null : fRegistry.get(descriptor);
return new JavaCompletionProposal(completion, start, length, icon, name, relevance);
}
/**
* Specifies the context of the code assist operation.
* @param codeAssistOffset The Offset on which the code assist will be called.
* Used to modify the offsets of the created proposals. ('Non Eating')
* @param jproject The Java project to which the underlying source belongs.
* Needed to find types referred.
* @param cu The compilation unit that is edited. Used to add import statements.
* Can be <code>null</code> if no import statements should be added.
*/
public void reset(int codeAssistOffset, IJavaProject jproject, ICompilationUnit cu) {
fJavaProject= jproject;
fCompilationUnit= cu;
fCodeAssistOffset= codeAssistOffset;
fUserReplacementLength= -1;
fLastProblem= null;
for (int i= 0; i < fResults.length; i++)
fResults[i].clear();
}
/**
* If the replacement length is set, it overrides the length returned from
* the content assist infrastructure.
* Use this setting if code assist is called with a none empty selection.
*/
public void setReplacementLength(int length) {
fUserReplacementLength= length;
}
/**
* If set, proposals created will not remove characters after the code assist position
* @param preventEating The preventEating to set
*/
public void setPreventEating(boolean preventEating) {
fPreventEating= preventEating;
}
}
|
13,323 |
Bug 13323 Problem Tree Viewer not propagating Label change
|
Build 20020409 In the handleLabelProviderChanged method in ProblemTreeViewer a changed event on a resource is adapted to the Java elements it represents but the change is not propagated. As a result when the CVS decorator is turned on the ProblemTreeViewer is not decorated. The last line LabelProviderChangedEvent e= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource(), mapped); should read super.handleLabelProviderChanged(new LabelProviderChangedEvent ((IBaseLabelProvider)event.getSource(), mapped));
|
resolved fixed
|
a85f683
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-12T19:10:41Z | 2002-04-10T14:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/ProblemTreeViewer.java
|
package org.eclipse.jdt.internal.ui.viewsupport;
import java.util.Set;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Extends a TreeViewer to allow more performance when showing error ticks.
* A <code>ProblemItemMapper</code> is contained that maps all items in
* the tree to underlying resource
*/
public class ProblemTreeViewer extends TreeViewer implements IProblemChangedListener {
private ProblemItemMapper fProblemItemMapper;
/*
* @see TreeViewer#TreeViewer(Composite)
*/
public ProblemTreeViewer(Composite parent) {
super(parent);
initMapper();
}
/*
* @see TreeViewer#TreeViewer(Composite, int)
*/
public ProblemTreeViewer(Composite parent, int style) {
super(parent, style);
initMapper();
}
/*
* @see TreeViewer#TreeViewer(Tree)
*/
public ProblemTreeViewer(Tree tree) {
super(tree);
initMapper();
}
private void initMapper() {
fProblemItemMapper= new ProblemItemMapper();
}
/*
* @see IProblemChangedListener#problemsChanged
*/
public void problemsChanged(final Set changed) {
Control control= getControl();
if (control != null && !control.isDisposed()) {
control.getDisplay().asyncExec(new Runnable() {
public void run() {
fProblemItemMapper.problemsChanged(changed, (ILabelProvider)getLabelProvider());
}
});
}
}
/*
* @see StructuredViewer#mapElement(Object, Widget)
*/
protected void mapElement(Object element, Widget item) {
super.mapElement(element, item);
if (item instanceof Item) {
fProblemItemMapper.addToMap(element, (Item) item);
}
}
/*
* @see StructuredViewer#unmapElement(Object, Widget)
*/
protected void unmapElement(Object element, Widget item) {
if (item instanceof Item) {
fProblemItemMapper.removeFromMap(element, (Item) item);
}
super.unmapElement(element, item);
}
/*
* @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent)
*/
protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
Object[] source= event.getElements();
if (source == null) {
super.handleLabelProviderChanged(event);
return;
}
// map the event to the Java elements if possible
// this does not handle the ambiguity of default packages
Object[] mapped= new Object[source.length];
for (int i= 0; i < source.length; i++) {
Object o= source[i];
// needs to handle the case of:
// default package
// package fragment root on project
if (o instanceof IResource) {
IResource r= (IResource)o;
IJavaElement element= JavaCore.create(r);
if (element != null)
mapped[i]= element;
else
mapped[i]= o;
} else {
mapped[i]= o;
}
}
LabelProviderChangedEvent e= new LabelProviderChangedEvent((IBaseLabelProvider)event.getSource(), mapped);
}
}
|
13,799 |
Bug 13799 JAR exporter exports class files from output folder
|
There was a problem with the output folder not being detected as such.
|
resolved fixed
|
a65156e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-15T16:01:16Z | 2002-04-15T14:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionWriter;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.ui.jarpackager.JarWriter;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaStatusConstants;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IJarExportRunnable {
private static final String COMPILER_SOURCE_FILE_ATTR = "org.eclipse.jdt.core.compiler.debug.sourceFile"; //$NON-NLS-1$
private JarWriter fJarWriter;
private JarPackageData fJarPackage;
private JarPackageData[] fJarPackages;
private IFile[] fDescriptionFiles;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private Set fExportedClassContainers;
private MultiStatus fProblems;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData jarPackage, Shell parent) {
this(new JarPackageData[] {jarPackage}, parent);
}
/**
* Creates an instance of this class.
*
* @param descriptions an array with JAR package descriptions
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData[] jarPackages, Shell parent) {
this(parent);
fJarPackages= jarPackages;
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fProblems= new MultiStatus(JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"), null); //$NON-NLS-1$
}
protected void addWarning(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logWarnings())
fProblems.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logErrors())
fProblems.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return count;
}
}
else
resource= (IResource)element;
if (resource.getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)resource);
}
return count;
}
private int getTotalChildCount(IContainer container) {
IResource[] members;
try {
members= container.members();
} catch (CoreException ex) {
return 0;
}
int count= 0;
for (int i= 0; i < members.length; i++) {
if (members[i].getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)members[i]);
}
return count;
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= jProject.findPackageFragmentRoot(resource.getFullPath().removeLastSegments(1));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
if (fJarPackage.useSourceFolderHierarchy()&& !pkgRoot.getElementName().equals(pkgRoot.DEFAULT_PACKAGEROOT_PATH))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else if (element instanceof IPackageFragment)
exportPackageFragment(progressMonitor, (IPackageFragment)element);
else
exportContainer(progressMonitor, resource);
}
private void exportPackageFragment(IProgressMonitor progressMonitor, IPackageFragment pkgFragment) throws java.lang.InterruptedException {
Object[] children;
try {
children= pkgFragment.getChildren();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
children= pkgFragment.getNonJavaResources();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", pkgFragment.toString()), e); //$NON-NLS-1$
}
}
private void exportContainer(IProgressMonitor progressMonitor, IResource resource) throws java.lang.InterruptedException {
IResource[] children= null;
try {
children= ((IContainer) resource).members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", resource.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
boolean isNonJavaResource= !isInJavaProject || pkgRoot == null;
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == pkgRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", destinationPath.toString())); //$NON-NLS-1$
fJarWriter.write((IFile) resource, destinationPath);
} catch (IOException ex) {
String message= ex.getLocalizedMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getLocalizedMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", classFilePath.toString())); //$NON-NLS-1$
fJarWriter.write(file, classFilePath);
}
} catch (IOException ex) {
String message= ex.getLocalizedMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getLocalizedMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
fExportedClassContainers= new HashSet(10);
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++)
exportElement(fJarPackage.getElements()[i], progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
// Allow JAR Package to provide its own strategy
IFile[] classFiles= fJarPackage.findClassfilesFor(file);
if (classFiles != null)
return Arrays.asList(classFiles).iterator();
if (!isJavaFile(file))
return Collections.EMPTY_LIST.iterator();
IPath outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
// Java CU - search files with .class ending
boolean hasErrors= hasCompileErrors(file);
boolean hasWarnings= hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fExportedClassContainers.contains(classContainer))
return Collections.EMPTY_LIST.iterator();
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
if (fJavaNameToClassFilesMap == null) {
// Could not fully build map. fallback is to export whole directory
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.missingSourceFileAttributeExportedAll", classContainer.getLocation().toFile()); //$NON-NLS-1$
addWarning(msg, null);
fExportedClassContainers.add(classContainer);
return getClassesIn(classContainer);
}
fClassFilesMapContainer= classContainer;
}
ArrayList classFileList= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFileList == null || classFileList.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFileList.iterator();
}
private Iterator getClassesIn(IContainer classContainer) throws CoreException {
IResource[] resources= classContainer.members();
List files= new ArrayList(resources.length);
for (int i= 0; i < resources.length; i++)
if (resources[i].getType() == IResource.FILE && isClassFile(resources[i]))
files.add(resources[i]);
return files.iterator();
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (!isCompilerGeneratingSourceFileAttribute())
return null;
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
if (cfReader.sourceFileName() == null) {
/*
* Can't fully build the map because one or more
* class file does not contain the name of its
* source file.
*/
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", classFile.getLocation().toFile()), null); //$NON-NLS-1$
return null;
}
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* If there were any errors, the result is a status object containing
* individual status objects for each error.
* If there were no errors, the result is a status object with error code <code>OK</code>.
*
* @return the status of this operation
*/
public IStatus getStatus() {
if (fProblems.getSeverity() == IStatus.ERROR) {
String message= null;
if (fDescriptionFiles != null && fDescriptionFiles.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
// Create new status because we want another message - no API to set message
return new MultiStatus(JavaPlugin.getPluginId(), 0, fProblems.getChildren(), message, null);
}
return fProblems;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.areErrorsExported())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int count= fJarPackages.length;
progressMonitor.beginTask("", count); //$NON-NLS-1$
try {
for (int i= 0; i < count; i++) {
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1);
fJarPackage= fJarPackages[i];
if (fJarPackage != null)
singleRun(subProgressMonitor);
}
} finally {
progressMonitor.done();
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
int totalWork= countSelectedElements();
if (!isAutoBuilding() && fJarPackage.isBuildingIfNeeded()) {
int subMonitorTicks= totalWork/10;
totalWork += subMonitorTicks;
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, subMonitorTicks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
buildProjects(subProgressMonitor);
} else
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
fJarWriter= fJarPackage.createJarWriter(fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFle", ex.getLocalizedMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFileDueToInvalidManifest", ex.getLocalizedMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCloseJarFile", ex.getLocalizedMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getElements() == null || fJarPackage.getElements().length == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isManifestAccessible()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
IFile[] unsavedFiles= getUnsavedFiles();
if (unsavedFiles.length > 0)
return saveModifiedResourcesIfUserConfirms(unsavedFiles);
return true;
}
/**
* Returns the files which are not saved and which are
* part of the files being exported.
*
* @return an array of unsaved files
*/
private IFile[] getUnsavedFiles() {
IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors();
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
List selection= JarPackagerUtil.asResources(fJarPackage.getElements());
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (selection.contains(dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[])unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* Asks the user to confirm to save the modified resources.
*
* @return true if user pressed OK.
*/
private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) {
if (dirtyFiles == null || dirtyFiles.length == 0)
return true;
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(fParentShell, dirtyFiles);
final int[] intResult= new int[1];
Runnable runnable= new Runnable() {
public void run() {
intResult[0]= dlg.open();
}
};
display.syncExec(runnable);
return intResult[0] == IDialogConstants.OK_ID;
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles))
return saveModifiedResources(dirtyFiles);
// Report unsaved files
for (int i= 0; i < dirtyFiles.length; i++)
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFiles[i].getFullPath()), null); //$NON-NLS-1$
return false;
}
/**
* Save all of the editors in the workbench.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) {
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
final boolean[] retVal= new boolean[1];
Runnable runnable= new Runnable() {
public void run() {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IWorkspaceDescription description= workspace.getDescription();
boolean autoBuild= description.isAutoBuilding();
description.setAutoBuilding(false);
try {
workspace.setDescription(description);
// This save operation can not be canceled.
try {
new ProgressMonitorDialog(fParentShell).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
retVal[0]= true;
} finally {
description.setAutoBuilding(autoBuild);
workspace.setDescription(description);
}
} catch (InvocationTargetException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
} catch (InterruptedException ex) {
Assert.isTrue(false); // Can't happen. Operation isn't cancelable.
retVal[0]= false;
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
}
}
};
display.syncExec(runnable);
return retVal[0];
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= JavaPlugin.getDirtyEditors();
pm.beginTask(JarPackagerMessages.getString("JarFileExportOperation.savingModifiedResources"), editorsToSave.length); //$NON-NLS-1$
try {
List dirtyFilesList= Arrays.asList(dirtyFiles);
for (int i= 0; i < editorsToSave.length; i++) {
if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)editorsToSave[i].getEditorInput()).getFile();
if (dirtyFilesList.contains((dirtyFile)))
editorsToSave[i].doSave(new SubProgressMonitor(pm, 1));
}
pm.worked(1);
}
} finally {
pm.done();
}
}
};
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
IJarDescriptionWriter writer= fJarPackage.createJarDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
writer.write(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile= fJarPackage.getDescriptionFile();
if (descriptionFile.isAccessible() && (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, descriptionFile.getFullPath().toString())))
descriptionFile.setContents(fileInput, true, true, null);
else {
descriptionFile.create(fileInput, true, null);
}
} finally {
if (fileInput != null)
fileInput.close();
if (writer != null)
writer.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
IFile manifestFile= fJarPackage.getManifestFile();
if (manifestFile.isAccessible() && (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, manifestFile.getFullPath().toString())))
manifestFile.setContents(fileInput, true, true, null);
else {
manifestFile.create(fileInput, true, null);
}
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
private boolean isAutoBuilding() {
return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
}
private boolean isCompilerGeneratingSourceFileAttribute() {
Object value= JavaCore.getOptions().get(COMPILER_SOURCE_FILE_ATTR);
if (value instanceof String)
return "generate".equalsIgnoreCase((String)value); //$NON-NLS-1$
else
return true; // default
}
private void buildProjects(IProgressMonitor progressMonitor) {
Set builtProjects= new HashSet(10);
Object[] elements= fJarPackage.getElements();
for (int i= 0; i < elements.length; i++) {
IProject project= null;
Object element= elements[i];
if (element instanceof IResource)
project= ((IResource)element).getProject();
else if (element instanceof IJavaElement)
project= ((IJavaElement)element).getJavaProject().getProject();
if (project != null && !builtProjects.contains(project)) {
try {
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, progressMonitor);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringProjectBuild", project.getFullPath()); //$NON-NLS-1$
addError(message, ex);
} finally {
// don't try to build same project a second time even if it failed
builtProjects.add(project);
}
}
}
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileErrors(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
return true;
}
return false;
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileWarnings(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_WARNING)
return true;
}
return false;
}
}
|
10,654 |
Bug 10654 Allow all jars in a folder to be added to build path
| null |
resolved fixed
|
0de9fba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-15T16:40:25Z | 2002-03-04T02:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ClasspathVariablesPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.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.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock;
public class ClasspathVariablesPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private VariableBlock fVariableBlock;
/**
* Constructor for ClasspathVariablesPreferencePage
*/
public ClasspathVariablesPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
IStatusChangeListener listener= new IStatusChangeListener() {
public void statusChanged(IStatus status) {
updateStatus(status);
}
};
fVariableBlock= new VariableBlock(listener, false, null);
setDescription(JavaUIMessages.getString("ClasspathVariablesPreferencePage.description")); //$NON-NLS-1$
}
/**
* @see PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite parent) {
WorkbenchHelp.setHelp(parent, IJavaHelpContextIds.CP_VARIABLES_PREFERENCE_PAGE);
return fVariableBlock.createContents(parent);
}
/**
* @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/**
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fVariableBlock.performDefaults();
super.performDefaults();
}
/**
* @see PreferencePage#performOk()
*/
public boolean performOk() {
return fVariableBlock.performOk();
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
/**
* Initializes the default values of this page in the preference bundle.
* Will be called on startup of the JavaPlugin
*/
public static void initDefaults(IPreferenceStore prefs) {
}
}
|
10,654 |
Bug 10654 Allow all jars in a folder to be added to build path
| null |
resolved fixed
|
0de9fba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-15T16:40:25Z | 2002-03-04T02:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/CPListElement.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.net.URL;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.JavaCore;
public class CPListElement {
private int fEntryKind;
private IPath fPath;
private IResource fResource;
private boolean fIsMissing;
private IPath fSourceAttachmentPath;
private IPath fSourceAttachmentPrefix;
private URL fJavadocLocation;
private boolean fIsExported;
private IClasspathEntry fCachedEntry;
///private URL fJavaDocLocation;
public CPListElement(int entryKind, IPath path, IResource res, IPath attachPath, IPath attachRoot, boolean isExported) {
fEntryKind= entryKind;
fPath= path;
fSourceAttachmentPath= attachPath;
fSourceAttachmentPrefix= attachRoot;
fJavadocLocation= null;
fResource= res;
fIsMissing= false;
fIsExported= isExported;
fCachedEntry= null;
}
public CPListElement(int entryKind, IPath path, IResource res) {
this(entryKind, path, res, null, null, false);
}
public IClasspathEntry getClasspathEntry() {
if (fCachedEntry == null) {
fCachedEntry= newClasspathEntry();
}
return fCachedEntry;
}
private IClasspathEntry newClasspathEntry() {
switch (fEntryKind) {
case IClasspathEntry.CPE_SOURCE:
return JavaCore.newSourceEntry(fPath);
case IClasspathEntry.CPE_LIBRARY:
return JavaCore.newLibraryEntry(fPath, fSourceAttachmentPath, fSourceAttachmentPrefix, fIsExported);
case IClasspathEntry.CPE_PROJECT:
return JavaCore.newProjectEntry(fPath, fIsExported);
default: // IClasspathEntry.CPE_VARIABLE:
return JavaCore.newVariableEntry(fPath, fSourceAttachmentPath, fSourceAttachmentPrefix, fIsExported);
}
}
/**
* Gets the classpath entry path.
* @see IClasspathEntry#getPath()
*/
public IPath getPath() {
return fPath;
}
/**
* Gets the classpath entry kind.
* @see IClasspathEntry#getEntryKind()
*/
public int getEntryKind() {
return fEntryKind;
}
/**
* Entries without resource are either non existing or a variable entry
* External jars do not have a resource
*/
public IResource getResource() {
return fResource;
}
/**
* Sets the paths for source annotation
* @see org.eclipse.jdt.core.IPackageFragmentRoot#attachSource
*/
public void setSourceAttachment(IPath path, IPath prefix) {
fSourceAttachmentPath= path;
fSourceAttachmentPrefix= prefix;
fCachedEntry= null;
}
/**
* Gets the current path prefix used when accessing the source attachment
* @see org.eclipse.jdt.core.IPackageFragmentRoot#getSourceAttachmentPath
* @return The source attachment prefix
*/
public IPath getSourceAttachmentPath() {
return fSourceAttachmentPath;
}
/**
* Returns the root path used for accessing source attchments
* @see org.eclipse.jdt.core.IPackageFragmentRoot#getSourceAttachmentRootPath
*/
public IPath getSourceAttachmentRootPath() {
return fSourceAttachmentPrefix;
}
/*
* @see Object#equals(java.lang.Object)
*/
public boolean equals(Object other) {
if (other.getClass() == getClass()) {
CPListElement elem= (CPListElement)other;
return elem.fEntryKind == fEntryKind && elem.fPath == fPath;
}
return false;
}
/*
* @see Object#hashCode()
*/
public int hashCode() {
return fPath.hashCode() + fEntryKind;
}
/**
* Returns if a entry is missing.
* @return Returns a boolean
*/
public boolean isMissing() {
return fIsMissing;
}
/**
* Sets the 'missing' state of the entry.
*/
public void setIsMissing(boolean isMissing) {
fIsMissing= isMissing;
}
/**
* Returns if a entry is exported (only applies to libraries)
* @return Returns a boolean
*/
public boolean isExported() {
return fIsExported;
}
/**
* Sets the export state of the entry.
*/
public void setExported(boolean isExported) {
if (isExported != fIsExported) {
fIsExported = isExported;
fCachedEntry= null;
}
}
/**
* Gets the Javadoc location.
* @return Returns a URL
*/
public URL getJavadocLocation() {
return fJavadocLocation;
}
/**
* Sets the Javadoc location.
* @param javadocLocation The javadocLocation to set
*/
public void setJavadocLocation(URL javadocLocation) {
fJavadocLocation= javadocLocation;
}
}
|
10,654 |
Bug 10654 Allow all jars in a folder to be added to build path
| null |
resolved fixed
|
0de9fba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-15T16:40:25Z | 2002-03-04T02:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/ChooseVariableDialog.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
public class ChooseVariableDialog extends StatusDialog implements IStatusChangeListener, IDoubleClickListener {
private VariableBlock fVariableBlock;
public ChooseVariableDialog(Shell parent, String variableSelection) {
super(parent);
setTitle(NewWizardMessages.getString("ChooseVariableDialog.variabledialog.title")); //$NON-NLS-1$
fVariableBlock= new VariableBlock(this, true, variableSelection);
}
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite)super.createDialogArea(parent);
fVariableBlock.createContents(composite);
fVariableBlock.addDoubleClickListener(this);
return composite;
}
protected void okPressed() {
fVariableBlock.performOk();
super.okPressed();
}
public String getSelectedVariable() {
return fVariableBlock.getSelectedVariable();
}
/*
* @see IStatusChangeListener#statusChanged(IStatus)
*/
public void statusChanged(IStatus status) {
updateStatus(status);
}
/*
* @see IDoubleClickListener#doubleClick(DoubleClickEvent)
*/
public void doubleClick(DoubleClickEvent event) {
if (getStatus().isOK()) {
okPressed();
}
}
}
|
10,654 |
Bug 10654 Allow all jars in a folder to be added to build path
| null |
resolved fixed
|
0de9fba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-15T16:40:25Z | 2002-03-04T02:46:40Z |
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.net.URL;
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.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.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.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.ElementTreeSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator;
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.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
public class LibrariesWorkbookPage extends BuildPathBasePage {
private ListDialogField fClassPathList;
private IJavaProject fCurrJProject;
private ListDialogField fLibrariesList;
private IWorkspaceRoot fWorkspaceRoot;
private IDialogSettings fDialogSettings;
private Control fSWTControl;
public LibrariesWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList) {
fClassPathList= classPathList;
fWorkspaceRoot= root;
fSWTControl= null;
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
String[] buttonLabels= new String[] {
/* 0 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addnew.button"), //$NON-NLS-1$
/* 1 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addexisting.button"), //$NON-NLS-1$
/* 2 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addjar.button"), //$NON-NLS-1$
/* 3 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addextjar.button"), //$NON-NLS-1$
/* 4 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addvariable.button"), //$NON-NLS-1$
/* 5 */ null,
/* 6 */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.setsource.button"), //$NON-NLS-1$
/* 7 */ null,
/* 8 */ 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(8); //$NON-NLS-1$
fLibrariesList.enableButton(6, false);
fLibrariesList.setViewerSorter(new CPListElementSorter());
}
public void init(IJavaProject jproject) {
fCurrJProject= jproject;
updateLibrariesList();
}
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);
int kind= cpe.getEntryKind();
if (kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE) {
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 0: /* add new */
libentries= createNewClassContainer();
break;
case 1: /* add existing */
libentries= chooseClassContainers();
break;
case 2: /* add jar */
libentries= chooseJarFiles();
break;
case 3: /* add external jar */
libentries= chooseExtJarFiles();
break;
case 4: /* add variable */
libentries= chooseVariableEntries();
break;
case 6: /* set source attachment */
List selElements= fLibrariesList.getSelectedElements();
CPListElement selElement= (CPListElement) selElements.get(0);
SourceAttachmentDialog dialog= new SourceAttachmentDialog(getShell(), selElement.getClasspathEntry());
if (dialog.open() == dialog.OK) {
selElement.setSourceAttachment(dialog.getSourceAttachmentPath(), dialog.getSourceAttachmentRootPath());
selElement.setJavadocLocation(dialog.getJavadocLocation());
fLibrariesList.refresh();
fClassPathList.refresh();
}
break;
}
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));
}
}
private void libaryPageSelectionChanged(DialogField field) {
List selElements= fLibrariesList.getSelectedElements();
fLibrariesList.enableButton(6, canDoSourceAttachment(selElements));
}
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);
return (!(elem.getResource() instanceof IFolder));
}
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 (kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE) {
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[] createNewClassContainer() {
String title= NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.title"); //$NON-NLS-1$
IProject currProject= fCurrJProject.getProject();
NewContainerDialog dialog= new NewContainerDialog(getShell(), title, currProject, getUsedContainers());
IPath projpath= currProject.getFullPath();
dialog.setMessage(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.NewClassFolderDialog.description", projpath.toString())); //$NON-NLS-1$
int ret= dialog.open();
if (ret == dialog.OK) {
IFolder folder= dialog.getFolder();
return new CPListElement[] { newCPLibraryElement(folder) };
}
return null;
}
private CPListElement[] chooseClassContainers() {
Class[] acceptedClasses= new Class[] { IFolder.class };
ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true);
acceptedClasses= new Class[] { IProject.class, IFolder.class };
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, getUsedContainers());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.description")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setInitialSelection(fCurrJProject.getProject());
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[] chooseJarFiles() {
Class[] acceptedClasses= new Class[] { IFile.class };
ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, true);
ViewerFilter filter= new ArchiveFileFilter(getUsedJARFiles());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.description")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setInitialSelection(fCurrJProject.getProject());
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() {
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);
IResource resource= elem.getResource();
if (resource instanceof IContainer) {
res.add(resource);
}
}
return (IContainer[]) res.toArray(new IContainer[res.size()]);
}
private IFile[] getUsedJARFiles() {
List res= new ArrayList();
List cplist= fLibrariesList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
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(IClasspathEntry.CPE_LIBRARY, res.getFullPath(), res);
};
private CPListElement[] chooseExtJarFiles() {
String lastUsedPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR);
if (lastUsedPath == null) {
lastUsedPath= ""; //$NON-NLS-1$
}
FileDialog dialog= new FileDialog(getShell(), SWT.MULTI);
dialog.setText(NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.title")); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
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(IClasspathEntry.CPE_LIBRARY, path, null);
}
fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, filterPath.toOSString());
return elems;
}
private CPListElement[] chooseVariableEntries() {
ArrayList existingPaths= new ArrayList();
for (int i= 0; i < fLibrariesList.getSize(); i++) {
CPListElement elem= (CPListElement) fLibrariesList.getElement(i);
if (elem.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
existingPaths.add(elem.getPath());
}
}
VariableSelectionDialog dialog= new VariableSelectionDialog(getShell(), existingPaths);
if (dialog.open() == dialog.OK) {
IPath path= dialog.getVariable();
CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, path, null);
IPath resolvedPath= JavaCore.getResolvedVariablePath(path);
elem.setIsMissing((resolvedPath == null) || !resolvedPath.toFile().isFile());
return new CPListElement[] { elem };
}
return null;
}
private void addAttachmentsFromExistingLibs(CPListElement elem) {
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());
}
}
// a dialog to set the source attachment properties
private class VariableSelectionDialog extends StatusDialog implements IStatusChangeListener {
private VariableSelectionBlock fVariableSelectionBlock;
public VariableSelectionDialog(Shell parent, List existingPaths) {
super(parent);
setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.title")); //$NON-NLS-1$
String initVar= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTVARIABLE);
fVariableSelectionBlock= new VariableSelectionBlock(this, existingPaths, null, initVar, false);
}
/*
* @see Windows#configureShell
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.VARIABLE_SELECTION_DIALOG);
}
/*
* @see StatusDialog#createDialogArea()
*/
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite)super.createDialogArea(parent);
Label message= new Label(composite, SWT.WRAP);
message.setText(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.message")); //$NON-NLS-1$
message.setLayoutData(new GridData());
Control inner= fVariableSelectionBlock.createControl(composite);
inner.setLayoutData(new GridData(GridData.FILL_BOTH));
return composite;
}
/*
* @see Dialog#okPressed()
*/
protected void okPressed() {
fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTVARIABLE, getVariable().segment(0));
super.okPressed();
}
/*
* @see IStatusChangeListener#statusChanged()
*/
public void statusChanged(IStatus status) {
updateStatus(status);
}
public IPath getVariable() {
return fVariableSelectionBlock.getVariablePath();
}
}
// a dialog to set the source attachment properties
private class SourceAttachmentDialog extends StatusDialog implements IStatusChangeListener {
private SourceAttachmentBlock fSourceAttachmentBlock;
public SourceAttachmentDialog(Shell parent, IClasspathEntry entry) {
super(parent);
setTitle(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.SourceAttachmentDialog.title", entry.getPath().toString())); //$NON-NLS-1$
fSourceAttachmentBlock= new SourceAttachmentBlock(fWorkspaceRoot, 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();
}
public URL getJavadocLocation() {
return fSourceAttachmentBlock.getJavadocLocation();
}
}
/*
* @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);
int kind= curr.getEntryKind();
if (kind != IClasspathEntry.CPE_LIBRARY && kind != IClasspathEntry.CPE_VARIABLE) {
selElements.remove(i);
}
}
fLibrariesList.selectElements(new StructuredSelection(selElements));
}
}
|
10,654 |
Bug 10654 Allow all jars in a folder to be added to build path
| null |
resolved fixed
|
0de9fba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-15T16:40:25Z | 2002-03-04T02:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/NewVariableEntryDialog.java
| |
10,654 |
Bug 10654 Allow all jars in a folder to be added to build path
| null |
resolved fixed
|
0de9fba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-15T16:40:25Z | 2002-03-04T02:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariableBlock.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
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.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
public class VariableBlock {
private ListDialogField fVariablesList;
private StatusInfo fSelectionStatus;
private IStatusChangeListener fContext;
private boolean fUseAsSelectionDialog;
private boolean fRemovingSelection= false;
private String fSelectedVariable;
private Control fControl;
/**
* Constructor for VariableBlock
*/
public VariableBlock(IStatusChangeListener context, boolean useAsSelectionDialog, String initSelection) {
fContext= context;
fUseAsSelectionDialog= useAsSelectionDialog;
fSelectionStatus= new StatusInfo();
String[] buttonLabels= new String[] {
/* 0 */ NewWizardMessages.getString("VariableBlock.vars.add.button"), //$NON-NLS-1$
/* 1 */ NewWizardMessages.getString("VariableBlock.vars.edit.button"), //$NON-NLS-1$
/* 2 */ null,
/* 3 */ NewWizardMessages.getString("VariableBlock.vars.remove.button") //$NON-NLS-1$
};
VariablesAdapter adapter= new VariablesAdapter();
CPVariableElementLabelProvider labelProvider= new CPVariableElementLabelProvider(useAsSelectionDialog);
fVariablesList= new ListDialogField(adapter, buttonLabels, labelProvider);
fVariablesList.setDialogFieldListener(adapter);
fVariablesList.setLabelText(NewWizardMessages.getString("VariableBlock.vars.label")); //$NON-NLS-1$
fVariablesList.setRemoveButtonIndex(3);
fVariablesList.enableButton(1, false);
fVariablesList.setViewerSorter(new ViewerSorter() {
public int compare(Viewer viewer, Object e1, Object e2) {
if (e1 instanceof CPVariableElement && e2 instanceof CPVariableElement) {
return ((CPVariableElement)e1).getName().compareTo(((CPVariableElement)e2).getName());
}
return super.compare(viewer, e1, e2);
}
});
CPVariableElement initSelectedElement= null;
String[] reservedName= getReservedVariableNames();
ArrayList reserved= new ArrayList(reservedName.length);
addAll(reservedName, reserved);
String[] entries= JavaCore.getClasspathVariableNames();
ArrayList elements= new ArrayList(entries.length);
for (int i= 0; i < entries.length; i++) {
String name= entries[i];
CPVariableElement elem;
IPath entryPath= JavaCore.getClasspathVariable(name);
elem= new CPVariableElement(name, entryPath, reserved.contains(name));
elements.add(elem);
if (name.equals(initSelection)) {
initSelectedElement= elem;
}
}
fVariablesList.setElements(elements);
if (initSelectedElement != null) {
ISelection sel= new StructuredSelection(initSelectedElement);
fVariablesList.selectElements(sel);
} else {
fVariablesList.selectFirstElement();
}
}
private String[] getReservedVariableNames() {
return new String[] {
JavaRuntime.JRELIB_VARIABLE,
JavaRuntime.JRESRC_VARIABLE,
JavaRuntime.JRESRCROOT_VARIABLE,
};
}
public Control createContents(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fVariablesList }, true, 0, 0);
LayoutUtil.setHorizontalGrabbing(fVariablesList.getListControl(null));
fControl= composite;
return composite;
}
public void addDoubleClickListener(IDoubleClickListener listener) {
fVariablesList.getTableViewer().addDoubleClickListener(listener);
}
private Shell getShell() {
if (fControl != null) {
return fControl.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
public String getSelectedVariable() {
return fSelectedVariable;
}
private class VariablesAdapter implements IDialogFieldListener, IListAdapter {
// -------- IListAdapter --------
public void customButtonPressed(DialogField field, int index) {
switch (index) {
case 0: /* add */
editEntries(null);
break;
case 1: /* edit */
List selected= fVariablesList.getSelectedElements();
editEntries((CPVariableElement)selected.get(0));
break;
}
}
public void selectionChanged(DialogField field) {
doSelectionChanged(field);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
}
}
private boolean containsReserved(List selected) {
for (int i= selected.size()-1; i >= 0; i--) {
if (((CPVariableElement)selected.get(i)).isReserved()) {
return true;
}
}
return false;
}
private static void addAll(Object[] objs, Collection dest) {
for (int i= 0; i < objs.length; i++) {
dest.add(objs[i]);
}
}
private void doSelectionChanged(DialogField field) {
List selected= fVariablesList.getSelectedElements();
boolean isSingleSelected= selected.size() == 1;
boolean containsReserved= containsReserved(selected);
// edit
fVariablesList.enableButton(1, isSingleSelected && !containsReserved);
// remove button
fVariablesList.enableButton(3, !containsReserved);
fSelectedVariable= null;
if (fUseAsSelectionDialog) {
if (isSingleSelected) {
fSelectionStatus.setOK();
fSelectedVariable= ((CPVariableElement)selected.get(0)).getName();
} else {
fSelectionStatus.setError(""); //$NON-NLS-1$
}
fContext.statusChanged(fSelectionStatus);
}
}
private void editEntries(CPVariableElement entry) {
List existingEntries= fVariablesList.getElements();
VariableCreationDialog dialog= new VariableCreationDialog(getShell(), entry, existingEntries);
if (dialog.open() != dialog.OK) {
return;
}
CPVariableElement newEntry= dialog.getClasspathElement();
if (entry == null) {
fVariablesList.addElement(newEntry);
entry= newEntry;
} else {
entry.setName(newEntry.getName());
entry.setPath(newEntry.getPath());
fVariablesList.refresh();
}
fVariablesList.selectElements(new StructuredSelection(entry));
}
public void performDefaults() {
fVariablesList.removeAllElements();
String[] reservedName= getReservedVariableNames();
for (int i= 0; i < reservedName.length; i++) {
CPVariableElement elem= new CPVariableElement(reservedName[i], null, true);
elem.setReserved(true);
fVariablesList.addElement(elem);
}
}
public boolean performOk() {
List toRemove= new ArrayList();
toRemove.addAll(Arrays.asList(JavaCore.getClasspathVariableNames()));
// remove all unchanged
List elements= fVariablesList.getElements();
for (int i= elements.size()-1; i >= 0; i--) {
CPVariableElement curr= (CPVariableElement) elements.get(i);
if (curr.isReserved()) {
elements.remove(curr);
} else {
IPath path= curr.getPath();
IPath prevPath= JavaCore.getClasspathVariable(curr.getName());
if (prevPath != null && prevPath.equals(path)) {
elements.remove(curr);
}
}
toRemove.remove(curr.getName());
}
int steps= elements.size() + toRemove.size();
if (steps > 0) {
IRunnableWithProgress runnable= new VariableBlockRunnable(toRemove, elements);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, runnable);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), NewWizardMessages.getString("VariableBlock.operation_errror.title"), NewWizardMessages.getString("VariableBlock.operation_errror.message")); //$NON-NLS-1$ //$NON-NLS-2$
return false;
} catch (InterruptedException e) {
return true;
}
}
return true;
}
private class VariableBlockRunnable implements IRunnableWithProgress {
private List fToRemove;
private List fToChange;
public VariableBlockRunnable(List toRemove, List toChange) {
fToRemove= toRemove;
fToChange= toChange;
}
/*
* @see IRunnableWithProgress#run(IProgressMonitor)
*/
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
int steps= fToChange.size() + fToRemove.size();
monitor.beginTask(NewWizardMessages.getString("VariableBlock.operation_desc"), steps); //$NON-NLS-1$
try {
for (int i= 0; i < fToChange.size(); i++) {
CPVariableElement curr= (CPVariableElement) fToChange.get(i);
SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1);
JavaCore.setClasspathVariable(curr.getName(), curr.getPath(), subMonitor);
if (monitor.isCanceled()) {
return;
}
}
for (int i= 0; i < fToRemove.size(); i++) {
SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1);
JavaCore.removeClasspathVariable((String) fToRemove.get(i), subMonitor);
if (monitor.isCanceled()) {
return;
}
}
} catch (JavaModelException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
}
}
|
10,654 |
Bug 10654 Allow all jars in a folder to be added to build path
| null |
resolved fixed
|
0de9fba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-15T16:40:25Z | 2002-03-04T02:46:40Z |
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 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.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
public class VariablePathDialogField extends StringButtonDialogField {
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());
}
}
}
|
10,654 |
Bug 10654 Allow all jars in a folder to be added to build path
| null |
resolved fixed
|
0de9fba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-15T16:40:25Z | 2002-03-04T02:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariableSelectionBlock.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.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jdt.core.JavaCore;
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.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
public class VariableSelectionBlock {
private List fExistingPaths;
private StringButtonDialogField fVariableField;
private StringButtonDialogField fExtensionField;
private CLabel fFullPath;
private IStatus fVariableStatus;
private IStatus fExistsStatus;
private IStatus fExtensionStatus;
private String fVariable;
private IStatusChangeListener fContext;
private boolean fIsEmptyAllowed;
private String fLastVariableSelection;
/**
* Constructor for VariableSelectionBlock
*/
public VariableSelectionBlock(IStatusChangeListener context, List existingPaths, IPath varPath, String lastVarSelection, boolean emptyAllowed) {
fContext= context;
fExistingPaths= existingPaths;
fIsEmptyAllowed= emptyAllowed;
fLastVariableSelection= lastVarSelection;
fVariableStatus= new StatusInfo();
fExistsStatus= new StatusInfo();
VariableSelectionAdapter adapter= new VariableSelectionAdapter();
fVariableField= new StringButtonDialogField(adapter);
fVariableField.setDialogFieldListener(adapter);
fVariableField.setLabelText(NewWizardMessages.getString("VariableSelectionBlock.variable.label")); //$NON-NLS-1$
fVariableField.setButtonLabel(NewWizardMessages.getString("VariableSelectionBlock.variable.button")); //$NON-NLS-1$
fExtensionField= new StringButtonDialogField(adapter);
fExtensionField.setDialogFieldListener(adapter);
fExtensionField.setLabelText(NewWizardMessages.getString("VariableSelectionBlock.extension.label")); //$NON-NLS-1$
fExtensionField.setButtonLabel(NewWizardMessages.getString("VariableSelectionBlock.extension.button")); //$NON-NLS-1$
if (varPath != null) {
fVariableField.setText(varPath.segment(0));
fExtensionField.setText(varPath.removeFirstSegments(1).toString());
} else {
fVariableField.setText(""); //$NON-NLS-1$
fExtensionField.setText(""); //$NON-NLS-1$
}
updateFullTextField();
}
public IPath getVariablePath() {
if (fVariable != null) {
return new Path(fVariable).append(fExtensionField.getText());
}
return null;
}
public IPath getResolvedPath() {
if (fVariable != null) {
IPath entryPath= JavaCore.getClasspathVariable(fVariable);
if (entryPath != null) {
return entryPath.append(fExtensionField.getText());
}
}
return null;
}
public void setFocus(Display display) {
fVariableField.postSetFocusOnDialogField(display);
}
public Control createControl(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
int nColumns= 3;
Composite inner= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= nColumns;
inner.setLayout(layout);
int fieldWidthHint= converter.convertWidthInCharsToPixels(50);
fVariableField.doFillIntoGrid(inner, nColumns);
LayoutUtil.setWidthHint(fVariableField.getTextControl(null), fieldWidthHint);
LayoutUtil.setHorizontalGrabbing(fVariableField.getTextControl(null));
fExtensionField.doFillIntoGrid(inner, nColumns);
LayoutUtil.setWidthHint(fExtensionField.getTextControl(null), fieldWidthHint);
Label label= new Label(inner, SWT.LEFT);
label.setLayoutData(new GridData());
label.setText(NewWizardMessages.getString("VariableSelectionBlock.fullpath.label")); //$NON-NLS-1$
fFullPath= new CLabel(inner, SWT.NONE);
fFullPath.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
DialogField.createEmptySpace(inner, nColumns - 2);
updateFullTextField();
setFocus(parent.getDisplay());
return inner;
}
// -------- VariableSelectionAdapter --------
private class VariableSelectionAdapter implements IDialogFieldListener, IStringButtonAdapter {
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
doFieldUpdated(field);
}
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
doChangeControlPressed(field);
}
}
private void doChangeControlPressed(DialogField field) {
if (field == fVariableField) {
String variable= chooseVariable();
if (variable != null) {
fVariableField.setText(variable);
}
} else if (field == fExtensionField) {
IPath filePath= chooseExtJar();
if (filePath != null) {
fExtensionField.setText(filePath.toString());
}
}
}
private void doFieldUpdated(DialogField field) {
if (field == fVariableField) {
fVariableStatus= variableUpdated();
} else if (field == fExtensionField) {
fExtensionStatus= extensionUpdated();
}
fExistsStatus= getExistsStatus();
updateFullTextField();
fContext.statusChanged(StatusUtil.getMostSevere(new IStatus[] { fVariableStatus, fExtensionStatus, fExistsStatus }));
}
private IStatus variableUpdated() {
fVariable= null;
StatusInfo status= new StatusInfo();
String name= fVariableField.getText();
if (name.length() == 0) {
if (!fIsEmptyAllowed) {
status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.entername")); //$NON-NLS-1$
} else {
fVariable= ""; //$NON-NLS-1$
}
} else if (JavaCore.getClasspathVariable(name) == null) {
status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.namenotexists")); //$NON-NLS-1$
} else {
fVariable= name;
}
fExtensionField.enableButton(fVariable != null);
return status;
}
private IStatus extensionUpdated() {
StatusInfo status= new StatusInfo();
String extension= fExtensionField.getText();
if (extension.length() > 0 && !Path.ROOT.isValidPath(extension)) {
status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.invalidextension")); //$NON-NLS-1$
}
return status;
}
private IStatus getExistsStatus() {
StatusInfo status= new StatusInfo();
IPath path= getResolvedPath();
if (path != null) {
if (findPath(path)) {
status.setError(NewWizardMessages.getString("VariableSelectionBlock.error.pathexists")); //$NON-NLS-1$
} else if (!path.toFile().isFile()) {
status.setWarning(NewWizardMessages.getString("VariableSelectionBlock.warning.pathnotexists")); //$NON-NLS-1$
}
} else {
status.setWarning(NewWizardMessages.getString("VariableSelectionBlock.warning.pathnotexists")); //$NON-NLS-1$
}
return status;
}
private boolean findPath(IPath path) {
for (int i= fExistingPaths.size() -1; i >=0; i--) {
IPath curr= (IPath) fExistingPaths.get(i);
if (curr.equals(path)) {
return true;
}
}
return false;
}
private void updateFullTextField() {
if (fFullPath != null && !fFullPath.isDisposed()) {
IPath resolvedPath= getResolvedPath();
if (resolvedPath != null) {
fFullPath.setText(resolvedPath.toOSString());
} else {
fFullPath.setText(""); //$NON-NLS-1$
}
}
}
private Shell getShell() {
if (fFullPath != null) {
return fFullPath.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private IPath chooseExtJar() {
String lastUsedPath= ""; //$NON-NLS-1$
IPath entryPath= getResolvedPath();
if (entryPath != null) {
if (ArchiveFileFilter.isArchivePath(entryPath)) {
lastUsedPath= entryPath.removeLastSegments(1).toOSString();
} else {
lastUsedPath= entryPath.toOSString();
}
}
FileDialog dialog= new FileDialog(getShell(), SWT.SINGLE);
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
dialog.setText(NewWizardMessages.getString("VariableSelectionBlock.ExtJarDialog.title")); //$NON-NLS-1$
String res= dialog.open();
if (res == null) {
return null;
}
IPath resPath= new Path(res).makeAbsolute();
IPath varPath= JavaCore.getClasspathVariable(fVariable);
if (!varPath.isPrefixOf(resPath)) {
return new Path(resPath.lastSegment());
} else {
return resPath.removeFirstSegments(varPath.segmentCount()).setDevice(null);
}
}
private String chooseVariable() {
ChooseVariableDialog dialog= new ChooseVariableDialog(getShell(), fVariable);
if (dialog.open() == dialog.OK) {
return dialog.getSelectedVariable();
}
return null;
}
}
|
12,611 |
Bug 12611 'move..' is always disabled in the outline context menu
|
'move..' is always disabled in the outline context menu this comes from ReorgGroup which includes 'move' as well (maybe it shouldn't) maybe this should be adressed together with Dirk's menu restructuring
|
resolved fixed
|
dcdc2c8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-15T16:45:27Z | 2002-04-02T15:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/ReorgGroup.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.reorg;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GroupContext;
import org.eclipse.jdt.internal.ui.actions.StructuredSelectionProvider;
import org.eclipse.jdt.internal.ui.refactoring.actions.IRefactoringAction;
public class ReorgGroup extends ContextMenuGroup {
private static final String GROUP_NAME= IContextMenuConstants.GROUP_REORGANIZE;
private IRefactoringAction[] fActions;
public void fill(IMenuManager manager, GroupContext context) {
createActions(context.getSelectionProvider());
for (int i= 0; i < fActions.length; i++) {
fActions[i].update();
manager.appendToGroup(GROUP_NAME, fActions[i]);
}
}
private void createActions(ISelectionProvider p) {
StructuredSelectionProvider provider= StructuredSelectionProvider.createFrom(p);
if (fActions != null)
return;
fActions= new IRefactoringAction[] {
createCutAction(p),
createCopyAction(p),
createPasteAction(p),
createDeleteAction(p),
//new DuplicateSourceReferenceAction(provider, p),
new JdtMoveAction(provider),
new RenameAction(p)
};
}
public static void addGlobalReorgActions(IActionBars actionBars, ISelectionProvider provider) {
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.COPY, createCopyAction(provider));
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.CUT, createCutAction(provider));
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.PASTE, createPasteAction(provider));
}
private static IRefactoringAction createCutAction(ISelectionProvider p){
return new CutSourceReferencesToClipboardAction(p);
}
public static IRefactoringAction createCopyAction(ISelectionProvider p){
IRefactoringAction copyResources= new CopyResourcesToClipboardAction(p);
IRefactoringAction copySourceReferences= new CopySourceReferencesToClipboardAction(p);
return new DualReorgAction(p, ReorgMessages.getString("ReorgGroup.copy"), ReorgMessages.getString("copyAction.description"), copyResources, copySourceReferences); //$NON-NLS-1$ //$NON-NLS-2$
}
public static IRefactoringAction createPasteAction(ISelectionProvider p){
IRefactoringAction pasteResources= new PasteResourcesFromClipboardAction(p);
IRefactoringAction pasteSourceReferences= new PasteSourceReferencesFromClipboardAction(p);
return new DualReorgAction(p, ReorgMessages.getString("ReorgGroup.paste"), ReorgMessages.getString("ReorgGroup.pasteAction.description"), pasteResources, pasteSourceReferences); //$NON-NLS-1$ //$NON-NLS-2$
}
public static IRefactoringAction createDeleteAction(ISelectionProvider p){
IRefactoringAction deleteResources= new DeleteResourcesAction(p);
IRefactoringAction deleteSourceReferences= new DeleteSourceReferencesAction(p);
return new DualReorgAction(p, ReorgMessages.getString("ReorgGroup.delete"), ReorgMessages.getString("deleteAction.description"), deleteResources, deleteSourceReferences); //$NON-NLS-1$ //$NON-NLS-2$
}
}
|
12,775 |
Bug 12775 [Dialogs] double click behaviour in move dialog (package view)
|
I double-clicked on a project, but instead of expanding the project and showing the children (source folders), it accepted the project as the target and commited OK. I think it's more natural that double clicking on projects, packages, etc. would expand/unexpand the node.
|
resolved fixed
|
78f4cb0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-15T16:47:29Z | 2002-04-04T14:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/JdtMoveAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.reorg;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.ui.actions.MoveProjectAction;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementContentProvider;
import org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.StructuredSelectionProvider;
import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class JdtMoveAction extends ReorgDestinationAction {
private boolean fShowPreview= false;
public JdtMoveAction(String name, StructuredSelectionProvider provider) {
super(name, provider);
setDescription(ReorgMessages.getString("moveAction.description")); //$NON-NLS-1$
}
public JdtMoveAction(StructuredSelectionProvider provider) {
super(ReorgMessages.getString("moveAction.label"), provider); //$NON-NLS-1$
}
/* non java-doc
* see @ReorgDestinationAction#isOkToProceed
*/
String getActionName() {
return ReorgMessages.getString("moveAction.name"); //$NON-NLS-1$
}
/* non java-doc
* see @ReorgDestinationAction#getDestinationDialogMessage
*/
String getDestinationDialogMessage() {
return ReorgMessages.getString("moveAction.destination.label"); //$NON-NLS-1$
}
/* non java-doc
* see @ReorgDestinationAction#createRefactoring
*/
ReorgRefactoring createRefactoring(List elements){
return new MoveRefactoring(elements, JavaPreferencesSettings.getCodeGenerationSettings());
}
ElementTreeSelectionDialog createDestinationSelectionDialog(Shell parent, ILabelProvider labelProvider, JavaElementContentProvider cp, ReorgRefactoring refactoring){
return new MoveDestinationDialog(parent, labelProvider, cp, (MoveRefactoring)refactoring);
}
/* non java-doc
* see @ReorgDestinationAction#isOkToProceed
*/
protected boolean isOkToProceed(ReorgRefactoring refactoring) throws JavaModelException{
return (isOkToMoveReadOnly(refactoring));
}
/*
* @see ReorgDestinationAction#getExcluded(ReorgRefactoring)
*/
Set getExcluded(ReorgRefactoring refactoring) throws JavaModelException{
Set elements= refactoring.getElementsThatExistInTarget();
Set result= new HashSet();
for (Iterator iter= elements.iterator(); iter.hasNext(); ){
Object o= iter.next();
int action= askIfOverwrite(ReorgUtils.getName(o));
if (action == IDialogConstants.CANCEL_ID)
return null;
if (action == IDialogConstants.YES_TO_ALL_ID)
return new HashSet(0); //nothing excluded
if (action == IDialogConstants.NO_ID)
result.add(o);
}
return result;
}
private static int askIfOverwrite(String elementName){
Shell shell= JavaPlugin.getActiveWorkbenchShell().getShell();
String title= ReorgMessages.getString("JdtMoveAction.move"); //$NON-NLS-1$
String question= "Element '" + elementName + "' already exists. Would you like to overwrite?";
String[] labels= new String[] {IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL,
IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL };
final MessageDialog dialog = new MessageDialog(shell, title, null, question, MessageDialog.QUESTION, labels, 0);
shell.getDisplay().syncExec(new Runnable() {
public void run() {
dialog.open();
}
});
int result = dialog.getReturnCode();
if (result == 0)
return IDialogConstants.YES_ID;
if (result == 1)
return IDialogConstants.YES_TO_ALL_ID;
if (result == 2)
return IDialogConstants.NO_ID;
return IDialogConstants.CANCEL_ID;
}
protected void setShowPreview(boolean showPreview) {
fShowPreview = showPreview;
}
private static boolean isOkToMoveReadOnly(ReorgRefactoring refactoring){
if (! hasReadOnlyElements(refactoring))
return true;
return MessageDialog.openQuestion(
JavaPlugin.getActiveWorkbenchShell(),
ReorgMessages.getString("moveAction.checkMove"), //$NON-NLS-1$
ReorgMessages.getString("moveAction.error.readOnly")); //$NON-NLS-1$
}
private static boolean hasReadOnlyElements(ReorgRefactoring refactoring){
for (Iterator iter= refactoring.getElementsToReorg().iterator(); iter.hasNext(); ){
if (ReorgUtils.shouldConfirmReadOnly(iter.next()))
return true;
}
return false;
}
/* non java-doc
* @see IRefactoringAction#canOperateOn(IStructuredSelection)
*/
public boolean canOperateOn(IStructuredSelection selection) {
if (hasOnlyProjects())
return selection.size() == 1;
else
return super.canOperateOn(selection);
}
/*
* @see Action#run()
*/
public void run() {
if (hasOnlyProjects()){
moveProject();
} else {
super.run();
}
}
/* non java-doc
* @see ReorgDestinationAction#doReorg(ReorgRefactoring)
*/
void doReorg(ReorgRefactoring refactoring) throws JavaModelException{
if (!fShowPreview){
super.doReorg(refactoring);
return;
}
//XX incorrect help
RefactoringWizard wizard= new RefactoringWizard(refactoring, ReorgMessages.getString("JdtMoveAction.move"), IJavaHelpContextIds.MOVE_CU_ERROR_WIZARD_PAGE); //$NON-NLS-1$
new RefactoringWizardDialog(JavaPlugin.getActiveWorkbenchShell(), wizard).open();
}
private void moveProject(){
MoveProjectAction action= new MoveProjectAction(JavaPlugin.getActiveWorkbenchShell());
action.selectionChanged(getStructuredSelection());
action.run();
}
//--- static inner classes
private class MoveDestinationDialog extends ElementTreeSelectionDialog {
private static final int PREVIEW_ID= IDialogConstants.CLIENT_ID + 1;
private MoveRefactoring fRefactoring;
private Button fCheckbox;
private Button fPreview;
MoveDestinationDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, MoveRefactoring refactoring){
super(parent, labelProvider, contentProvider);
fRefactoring= refactoring;
fShowPreview= false;//from outter instance
}
protected Control createDialogArea(Composite parent) {
Composite result= (Composite)super.createDialogArea(parent);
fCheckbox= new Button(result, SWT.CHECK);
fCheckbox.setText(ReorgMessages.getString("JdtMoveAction.update_references")); //$NON-NLS-1$
fCheckbox.setEnabled(canUpdateReferences());
fCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updatePreviewButton();
fRefactoring.setUpdateReferences(fCheckbox.getEnabled() && fCheckbox.getSelection());
}
});
fCheckbox.setSelection(canUpdateReferences());
return result;
}
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
fPreview= createButton(parent, PREVIEW_ID, ReorgMessages.getString("JdtMoveAction.preview"), false); //$NON-NLS-1$
}
protected void updateOKStatus() {
super.updateOKStatus();
try{
fRefactoring.setDestination(getFirstResult());
fCheckbox.setEnabled(getOkButton().getEnabled() && canUpdateReferences());
updatePreviewButton();
} catch (JavaModelException e){
ExceptionHandler.handle(e, ReorgMessages.getString("JdtMoveAction.move"), ReorgMessages.getString("JdtMoveAction.exception")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
protected void buttonPressed(int buttonId) {
fShowPreview= (buttonId == PREVIEW_ID);
super.buttonPressed(buttonId);
if (buttonId == PREVIEW_ID)
close();
}
private void updatePreviewButton(){
fPreview.setEnabled(fCheckbox.getEnabled() && fCheckbox.getSelection());
}
private boolean canUpdateReferences(){
try{
return fRefactoring.canUpdateReferences();
} catch (JavaModelException e){
return false;
}
}
}
}
|
13,620 |
Bug 13620 The Java Source Attachment Preference Page has text with large amount of white space
| null |
resolved fixed
|
6c31768
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-16T09:32:45Z | 2002-04-12T14:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/SourceAttachmentPropertyPage.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.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.dialogs.PropertyPage;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
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.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.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.SourceAttachmentBlock;
/**
* Property page to configure a archive's JARs source attachment
*/
public class SourceAttachmentPropertyPage extends PropertyPage implements IStatusChangeListener {
private SourceAttachmentBlock fSourceAttachmentBlock;
private IPackageFragmentRoot fJarRoot;
public SourceAttachmentPropertyPage() {
}
/*
* @see PreferencePage#createContents
*/
protected Control createContents(Composite composite) {
fJarRoot= getJARPackageFragmentRoot();
if (fJarRoot != null) {
try {
IClasspathEntry entry= JavaModelUtil.getRawClasspathEntry(fJarRoot);
if (entry == null) {
// use a dummy entry to use for initialization
entry= JavaCore.newLibraryEntry(fJarRoot.getPath(), null, null);
}
IWorkspaceRoot wsroot= fJarRoot.getJavaModel().getWorkspace().getRoot();
fSourceAttachmentBlock= new SourceAttachmentBlock(wsroot, this, entry);
return fSourceAttachmentBlock.createControl(composite);
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
}
}
Label label= new Label(composite, SWT.LEFT + SWT.WRAP);
label.setText(JavaUIMessages.getString("SourceAttachmentPropertyPage.noarchive.message")); //$NON-NLS-1$
label.setFont(composite.getFont());
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.SOURCE_ATTACHMENT_PROPERTY_PAGE);
return label;
}
/*
* @see IPreferencePage#performOk
*/
public boolean performOk() {
if (fSourceAttachmentBlock != null) {
try {
IRunnableWithProgress runnable= fSourceAttachmentBlock.getRunnable(fJarRoot.getJavaProject(), getShell());
new ProgressMonitorDialog(getShell()).run(true, true, runnable);
} catch (InvocationTargetException e) {
String title= JavaUIMessages.getString("SourceAttachmentPropertyPage.error.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("SourceAttachmentPropertyPage.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
return false;
} catch (InterruptedException e) {
// cancelled
return false;
}
}
return true;
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
if (fSourceAttachmentBlock != null) {
fSourceAttachmentBlock.setDefaults();
}
super.performDefaults();
}
private IPackageFragmentRoot getJARPackageFragmentRoot() {
// try to find it as Java element (needed for external jars)
IAdaptable adaptable= getElement();
IJavaElement elem= (IJavaElement) adaptable.getAdapter(IJavaElement.class);
if (elem instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot) elem;
if (root.isArchive()) {
return root;
} else {
return null;
}
}
// not on classpath or not in a java project
IResource resource= (IResource) adaptable.getAdapter(IResource.class);
if (resource instanceof IFile) {
IProject proj= resource.getProject();
try {
if (proj.hasNature(JavaCore.NATURE_ID)) {
IJavaProject jproject= JavaCore.create(proj);
return jproject.getPackageFragmentRoot(resource);
}
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
}
}
return null;
}
/*
* @see IStatusChangeListener#statusChanged
*/
public void statusChanged(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
}
|
13,744 |
Bug 13744 jar export wizard: wrong path to resource folders
|
Ther jar export wizard creates since last integration build 20020412 a wrong path to the resource path of eg. images. The wizard adds a "src/" below the image or resource path. I have my sources in "src/" and the binaries in "bin/".
|
resolved fixed
|
a30f3ea
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-16T13:10:55Z | 2002-04-13T17:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionWriter;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.ui.jarpackager.JarWriter;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaStatusConstants;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IJarExportRunnable {
private static final String COMPILER_SOURCE_FILE_ATTR = "org.eclipse.jdt.core.compiler.debug.sourceFile"; //$NON-NLS-1$
private JarWriter fJarWriter;
private JarPackageData fJarPackage;
private JarPackageData[] fJarPackages;
private IFile[] fDescriptionFiles;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private Set fExportedClassContainers;
private MultiStatus fProblems;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData jarPackage, Shell parent) {
this(new JarPackageData[] {jarPackage}, parent);
}
/**
* Creates an instance of this class.
*
* @param descriptions an array with JAR package descriptions
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData[] jarPackages, Shell parent) {
this(parent);
fJarPackages= jarPackages;
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fProblems= new MultiStatus(JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"), null); //$NON-NLS-1$
}
protected void addWarning(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logWarnings())
fProblems.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logErrors())
fProblems.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return count;
}
}
else
resource= (IResource)element;
if (resource.getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)resource);
}
return count;
}
private int getTotalChildCount(IContainer container) {
IResource[] members;
try {
members= container.members();
} catch (CoreException ex) {
return 0;
}
int count= 0;
for (int i= 0; i < members.length; i++) {
if (members[i].getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)members[i]);
}
return count;
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= jProject.findPackageFragmentRoot(resource.getFullPath().removeLastSegments(1));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
if (fJarPackage.useSourceFolderHierarchy()&& !pkgRoot.getElementName().equals(pkgRoot.DEFAULT_PACKAGEROOT_PATH))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else if (element instanceof IPackageFragment)
exportPackageFragment(progressMonitor, (IPackageFragment)element);
else
exportContainer(progressMonitor, (IContainer)resource);
}
private void exportPackageFragment(IProgressMonitor progressMonitor, IPackageFragment pkgFragment) throws java.lang.InterruptedException {
Object[] children;
try {
children= pkgFragment.getChildren();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
children= pkgFragment.getNonJavaResources();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", pkgFragment.toString()), e); //$NON-NLS-1$
}
}
private void exportContainer(IProgressMonitor progressMonitor, IContainer container) throws java.lang.InterruptedException {
if (container.getType() == IResource.FOLDER && isOutputFolder((IFolder)container))
return;
IResource[] children= null;
try {
children= container.members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", container.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
boolean isNonJavaResource= !isInJavaProject || pkgRoot == null;
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == pkgRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", destinationPath.toString())); //$NON-NLS-1$
fJarWriter.write((IFile) resource, destinationPath);
} catch (IOException ex) {
String message= ex.getLocalizedMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getLocalizedMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
private boolean isOutputFolder(IFolder folder) {
try {
IJavaProject javaProject= JavaCore.create(folder.getProject());
IPath outputFolderPath= javaProject.getOutputLocation();
return folder.getFullPath().equals(outputFolderPath);
} catch (JavaModelException ex) {
return false;
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", classFilePath.toString())); //$NON-NLS-1$
fJarWriter.write(file, classFilePath);
}
} catch (IOException ex) {
String message= ex.getLocalizedMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getLocalizedMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
fExportedClassContainers= new HashSet(10);
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++)
exportElement(fJarPackage.getElements()[i], progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
// Allow JAR Package to provide its own strategy
IFile[] classFiles= fJarPackage.findClassfilesFor(file);
if (classFiles != null)
return Arrays.asList(classFiles).iterator();
if (!isJavaFile(file))
return Collections.EMPTY_LIST.iterator();
IPath outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
// Java CU - search files with .class ending
boolean hasErrors= hasCompileErrors(file);
boolean hasWarnings= hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fExportedClassContainers.contains(classContainer))
return Collections.EMPTY_LIST.iterator();
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
if (fJavaNameToClassFilesMap == null) {
// Could not fully build map. fallback is to export whole directory
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.missingSourceFileAttributeExportedAll", classContainer.getLocation().toFile()); //$NON-NLS-1$
addWarning(msg, null);
fExportedClassContainers.add(classContainer);
return getClassesIn(classContainer);
}
fClassFilesMapContainer= classContainer;
}
ArrayList classFileList= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFileList == null || classFileList.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFileList.iterator();
}
private Iterator getClassesIn(IContainer classContainer) throws CoreException {
IResource[] resources= classContainer.members();
List files= new ArrayList(resources.length);
for (int i= 0; i < resources.length; i++)
if (resources[i].getType() == IResource.FILE && isClassFile(resources[i]))
files.add(resources[i]);
return files.iterator();
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (!isCompilerGeneratingSourceFileAttribute())
return null;
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
if (cfReader.sourceFileName() == null) {
/*
* Can't fully build the map because one or more
* class file does not contain the name of its
* source file.
*/
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", classFile.getLocation().toFile()), null); //$NON-NLS-1$
return null;
}
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* If there were any errors, the result is a status object containing
* individual status objects for each error.
* If there were no errors, the result is a status object with error code <code>OK</code>.
*
* @return the status of this operation
*/
public IStatus getStatus() {
if (fProblems.getSeverity() == IStatus.ERROR) {
String message= null;
if (fDescriptionFiles != null && fDescriptionFiles.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
// Create new status because we want another message - no API to set message
return new MultiStatus(JavaPlugin.getPluginId(), 0, fProblems.getChildren(), message, null);
}
return fProblems;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.areErrorsExported())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int count= fJarPackages.length;
progressMonitor.beginTask("", count); //$NON-NLS-1$
try {
for (int i= 0; i < count; i++) {
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1);
fJarPackage= fJarPackages[i];
if (fJarPackage != null)
singleRun(subProgressMonitor);
}
} finally {
progressMonitor.done();
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
int totalWork= countSelectedElements();
if (!isAutoBuilding() && fJarPackage.isBuildingIfNeeded()) {
int subMonitorTicks= totalWork/10;
totalWork += subMonitorTicks;
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, subMonitorTicks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
buildProjects(subProgressMonitor);
} else
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
fJarWriter= fJarPackage.createJarWriter(fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFle", ex.getLocalizedMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFileDueToInvalidManifest", ex.getLocalizedMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCloseJarFile", ex.getLocalizedMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getElements() == null || fJarPackage.getElements().length == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isManifestAccessible()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
IFile[] unsavedFiles= getUnsavedFiles();
if (unsavedFiles.length > 0)
return saveModifiedResourcesIfUserConfirms(unsavedFiles);
return true;
}
/**
* Returns the files which are not saved and which are
* part of the files being exported.
*
* @return an array of unsaved files
*/
private IFile[] getUnsavedFiles() {
IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors();
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
List selection= JarPackagerUtil.asResources(fJarPackage.getElements());
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (selection.contains(dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[])unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* Asks the user to confirm to save the modified resources.
*
* @return true if user pressed OK.
*/
private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) {
if (dirtyFiles == null || dirtyFiles.length == 0)
return true;
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(fParentShell, dirtyFiles);
final int[] intResult= new int[1];
Runnable runnable= new Runnable() {
public void run() {
intResult[0]= dlg.open();
}
};
display.syncExec(runnable);
return intResult[0] == IDialogConstants.OK_ID;
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles))
return saveModifiedResources(dirtyFiles);
// Report unsaved files
for (int i= 0; i < dirtyFiles.length; i++)
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFiles[i].getFullPath()), null); //$NON-NLS-1$
return false;
}
/**
* Save all of the editors in the workbench.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) {
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
final boolean[] retVal= new boolean[1];
Runnable runnable= new Runnable() {
public void run() {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IWorkspaceDescription description= workspace.getDescription();
boolean autoBuild= description.isAutoBuilding();
description.setAutoBuilding(false);
try {
workspace.setDescription(description);
// This save operation can not be canceled.
try {
new ProgressMonitorDialog(fParentShell).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
retVal[0]= true;
} finally {
description.setAutoBuilding(autoBuild);
workspace.setDescription(description);
}
} catch (InvocationTargetException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
} catch (InterruptedException ex) {
Assert.isTrue(false); // Can't happen. Operation isn't cancelable.
retVal[0]= false;
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
}
}
};
display.syncExec(runnable);
return retVal[0];
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= JavaPlugin.getDirtyEditors();
pm.beginTask(JarPackagerMessages.getString("JarFileExportOperation.savingModifiedResources"), editorsToSave.length); //$NON-NLS-1$
try {
List dirtyFilesList= Arrays.asList(dirtyFiles);
for (int i= 0; i < editorsToSave.length; i++) {
if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)editorsToSave[i].getEditorInput()).getFile();
if (dirtyFilesList.contains((dirtyFile)))
editorsToSave[i].doSave(new SubProgressMonitor(pm, 1));
}
pm.worked(1);
}
} finally {
pm.done();
}
}
};
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
IJarDescriptionWriter writer= fJarPackage.createJarDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
writer.write(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile= fJarPackage.getDescriptionFile();
if (descriptionFile.isAccessible() && (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, descriptionFile.getFullPath().toString())))
descriptionFile.setContents(fileInput, true, true, null);
else {
descriptionFile.create(fileInput, true, null);
}
} finally {
if (fileInput != null)
fileInput.close();
if (writer != null)
writer.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
IFile manifestFile= fJarPackage.getManifestFile();
if (manifestFile.isAccessible() && (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, manifestFile.getFullPath().toString())))
manifestFile.setContents(fileInput, true, true, null);
else {
manifestFile.create(fileInput, true, null);
}
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
private boolean isAutoBuilding() {
return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
}
private boolean isCompilerGeneratingSourceFileAttribute() {
Object value= JavaCore.getOptions().get(COMPILER_SOURCE_FILE_ATTR);
if (value instanceof String)
return "generate".equalsIgnoreCase((String)value); //$NON-NLS-1$
else
return true; // default
}
private void buildProjects(IProgressMonitor progressMonitor) {
Set builtProjects= new HashSet(10);
Object[] elements= fJarPackage.getElements();
for (int i= 0; i < elements.length; i++) {
IProject project= null;
Object element= elements[i];
if (element instanceof IResource)
project= ((IResource)element).getProject();
else if (element instanceof IJavaElement)
project= ((IJavaElement)element).getJavaProject().getProject();
if (project != null && !builtProjects.contains(project)) {
try {
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, progressMonitor);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringProjectBuild", project.getFullPath()); //$NON-NLS-1$
addError(message, ex);
} finally {
// don't try to build same project a second time even if it failed
builtProjects.add(project);
}
}
}
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileErrors(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
return true;
}
return false;
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileWarnings(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_WARNING)
return true;
}
return false;
}
}
|
13,068 |
Bug 13068 Move refactoring enabled for non-static methods
|
1) select a static and a non-static method in the outline 2) Refactor>Move ->the wizard tells to move 2 static members.
|
resolved fixed
|
0c35708
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-16T13:52:49Z | 2002-04-09T13:46:40Z |
org.eclipse.jdt.ui/core
| |
13,068 |
Bug 13068 Move refactoring enabled for non-static methods
|
1) select a static and a non-static method in the outline 2) Refactor>Move ->the wizard tells to move 2 static members.
|
resolved fixed
|
0c35708
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-16T13:52:49Z | 2002-04-09T13:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveMembersRefactoring.java
| |
13,081 |
Bug 13081 Bad progress reporting in Rename Type Refactoring
|
Build 20020404 - do smoke test - Rename Test case to A - bad progress reporting when you press next and when you press finish. The text is blank most of the time.
|
resolved fixed
|
c20320e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-16T13:53:24Z | 2002-04-09T16:33:20Z |
org.eclipse.jdt.ui/ui
| |
13,081 |
Bug 13081 Bad progress reporting in Rename Type Refactoring
|
Build 20020404 - do smoke test - Rename Test case to A - bad progress reporting when you press next and when you press finish. The text is blank most of the time.
|
resolved fixed
|
c20320e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-16T13:53:24Z | 2002-04-09T16:33:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/CreateChangeOperation.java
| |
13,877 |
Bug 13877 NLS tool - values are not displayed correctly
|
On the first page, the values ".", "...", "\n" are displayed as "", "", " ". At least the case of "." seems to happen for windows as well. I think "\n" should be displayed in the escaped notation again, as "\n".
|
resolved fixed
|
5cfdae2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-16T14:15:43Z | 2002-04-16T12:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/ProblemTableViewer.java
|
package org.eclipse.jdt.internal.ui.viewsupport;
import java.util.Set;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.TableViewer;
/**
* Extends a TableViewer to allow more performance when showing error ticks.
* A <code>ProblemItemMapper</code> is contained that maps all items in
* the tree to underlying resource
*/
public class ProblemTableViewer extends TableViewer implements IProblemChangedListener {
private ProblemItemMapper fProblemItemMapper;
/**
* Constructor for ProblemTableViewer.
* @param parent
*/
public ProblemTableViewer(Composite parent) {
super(parent);
initMapper();
}
/**
* Constructor for ProblemTableViewer.
* @param parent
* @param style
*/
public ProblemTableViewer(Composite parent, int style) {
super(parent, style);
initMapper();
}
/**
* Constructor for ProblemTableViewer.
* @param table
*/
public ProblemTableViewer(Table table) {
super(table);
initMapper();
}
private void initMapper() {
fProblemItemMapper= new ProblemItemMapper();
}
/*
* @see IProblemChangedListener#problemsChanged
*/
public void problemsChanged(final Set changed) {
Control control= getControl();
if (control != null && !control.isDisposed()) {
control.getDisplay().asyncExec(new Runnable() {
public void run() {
fProblemItemMapper.problemsChanged(changed, (ILabelProvider)getLabelProvider());
}
});
}
}
/*
* @see StructuredViewer#mapElement(Object, Widget)
*/
protected void mapElement(Object element, Widget item) {
super.mapElement(element, item);
if (item instanceof Item) {
fProblemItemMapper.addToMap(element, (Item) item);
}
}
/*
* @see StructuredViewer#unmapElement(Object, Widget)
*/
protected void unmapElement(Object element, Widget item) {
if (item instanceof Item) {
fProblemItemMapper.removeFromMap(element, (Item) item);
}
super.unmapElement(element, item);
}
}
|
13,916 |
Bug 13916 api: IScanner - Scanner.linePtr
|
20020412 i can't find a good way to get the old Scanner.linePtr funtionality in the api scanner (i need read access to that field)
|
resolved fixed
|
a107675
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-16T17:05:10Z | 2002-04-16T18:00:00Z |
org.eclipse.jdt.ui/core
| |
13,916 |
Bug 13916 api: IScanner - Scanner.linePtr
|
20020412 i can't find a good way to get the old Scanner.linePtr funtionality in the api scanner (i need read access to that field)
|
resolved fixed
|
a107675
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-16T17:05:10Z | 2002-04-16T18:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/NLSScanner.java
| |
13,907 |
Bug 13907 Scanner does not report whitespace tokens at end of input
|
The Scanner does not report the whitespace at the end of its input. The whitespace is added to the EOF token. If I explicitely ask for whitespace this behavior seems to be wrong (comments are reported correctly). Run the following testcase: import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.internal.compiler.parser.Scanner; import org.eclipse.jdt.core.compiler.ITerminalSymbols; public class ScannerTest { public static void main(String[] args) { String input= "package com.ibm.itp.compare.ui; //foo \r\n"; int l= input.length(); Scanner scanner= new Scanner(true, true); // returns comments & whitespace char[] chars= new char[l]; input.getChars(0, l, chars, 0); scanner.setSource(chars); try { for (;;) { int t= 0; switch (t= scanner.getNextToken()) { case ITerminalSymbols.TokenNameEOF: System.out.println("EOF"); return; case ITerminalSymbols.TokenNameWHITESPACE: System.out.println("WS"); break; case ITerminalSymbols.TokenNameCOMMENT_LINE: System.out.println("COMMENT"); break; case ITerminalSymbols.TokenNameSEMICOLON: System.out.println("SEMICOLON"); break; default: System.out.println("Token: " + t); break; } } } catch (InvalidInputException ex) { } } }
|
verified fixed
|
606480f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-17T09:01:56Z | 2002-04-16T15:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaTokenComparator.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.compare;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.internal.compiler.parser.Scanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.compare.contentmergeviewer.ITokenComparator;
import org.eclipse.compare.rangedifferencer.IRangeComparator;
/**
* A comparator for Java tokens.
*/
class JavaTokenComparator implements ITokenComparator {
private String fText;
private boolean fShouldEscape= true;
private int fCount;
private int[] fStarts;
private int[] fLengths;
/**
* Creates a TokenComparator for the given string.
*/
public JavaTokenComparator(String text, boolean shouldEscape) {
Assert.isNotNull(text);
fText= text;
fShouldEscape= shouldEscape;
int length= fText.length();
fStarts= new int[length];
fLengths= new int[length];
fCount= 0;
Scanner scanner= new Scanner(true, true); // returns comments & whitespace
scanner.setSource(fText.toCharArray());
try {
while (scanner.getNextToken() != ITerminalSymbols.TokenNameEOF) {
fStarts[fCount]= scanner.startPosition;
fLengths[fCount]= scanner.currentPosition - fStarts[fCount];
fCount++;
}
} catch (InvalidInputException ex) {
}
}
/**
* Returns the number of token in the string.
*
* @return number of token in the string
*/
public int getRangeCount() {
return fCount;
}
/* (non Javadoc)
* see ITokenComparator.getTokenStart
*/
public int getTokenStart(int index) {
if (index < fCount)
return fStarts[index];
return fText.length();
}
/* (non Javadoc)
* see ITokenComparator.getTokenLength
*/
public int getTokenLength(int index) {
if (index < fCount)
return fLengths[index];
return 0;
}
/**
* Returns <code>true</code> if a token given by the first index
* matches a token specified by the other <code>IRangeComparator</code> and index.
*
* @param thisIndex the number of the token within this range comparator
* @param other the range comparator to compare this with
* @param otherIndex the number of the token within the other comparator
* @return <code>true</code> if the token are equal
*/
public boolean rangesEqual(int thisIndex, IRangeComparator other, int otherIndex) {
if (other != null && getClass() == other.getClass()) {
JavaTokenComparator tc= (JavaTokenComparator) other; // safe cast
int thisLen= getTokenLength(thisIndex);
int otherLen= tc.getTokenLength(otherIndex);
if (thisLen == otherLen)
return fText.regionMatches(false, getTokenStart(thisIndex), tc.fText, tc.getTokenStart(otherIndex), thisLen);
}
return false;
}
/**
* Aborts the comparison if the number of tokens is too large.
*
* @return <code>true</code> to abort a token comparison
*/
public boolean skipRangeComparison(int length, int max, IRangeComparator other) {
if (!fShouldEscape)
return false;
if (getRangeCount() < 50 || other.getRangeCount() < 50)
return false;
if (max < 100)
return false;
if (length < 100)
return false;
if (max > 800)
return true;
if (length < max / 4)
return false;
return true;
}
}
|
13,507 |
Bug 13507 LinkedPositionUI has a reference to SWT.COLOR_RED
|
LinkedPositionUI(ITextViewer, LinkedPositionManager) - org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI has a reference to SWT.COLOR_RED which will be unreadble if the user sets their background colour to Red. We will be adding a getErrorText colour to JFaceColours in build >20020411. You may want to use that.
|
resolved fixed
|
0ceae1a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-17T12:28:28Z | 2002-04-11T13:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java
|
package org.eclipse.jdt.internal.ui.javaeditor;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.PropertyChangeEvent;
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.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.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.Path;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.MarkerUtilities;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.tasklist.TaskList;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IProblemRequestor;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.javaeditor.structureselection.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.structureselection.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.structureselection.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.structureselection.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.structureselection.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.structureselection.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.preferences.WorkInProgressPreferencePage;
import org.eclipse.jdt.internal.ui.refactoring.actions.SurroundWithTryCatchAction;
import org.eclipse.jdt.internal.ui.reorg.ReorgGroup;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionSourceViewer;
import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.JavaTextTools;
/**
* Java specific text editor.
*/
public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant {
interface ITextConverter {
void customizeDocumentCommand(IDocument document, DocumentCommand command);
};
class AdaptedRulerLayout extends Layout {
protected int fGap;
protected AdaptedSourceViewer fAdaptedSourceViewer;
protected AdaptedRulerLayout(int gap, AdaptedSourceViewer asv) {
fGap= gap;
fAdaptedSourceViewer= asv;
}
protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
Control[] children= composite.getChildren();
Point s= children[children.length - 1].computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache);
if (fAdaptedSourceViewer.isVerticalRulerVisible())
s.x += fAdaptedSourceViewer.getVerticalRuler().getWidth() + fGap;
return s;
}
protected void layout(Composite composite, boolean flushCache) {
Rectangle clArea= composite.getClientArea();
if (fAdaptedSourceViewer.isVerticalRulerVisible()) {
StyledText textWidget= fAdaptedSourceViewer.getTextWidget();
Rectangle trim= textWidget.computeTrim(0, 0, 0, 0);
int scrollbarHeight= trim.height;
IVerticalRuler vr= fAdaptedSourceViewer.getVerticalRuler();
int vrWidth=vr.getWidth();
int orWidth= 0;
if (fAdaptedSourceViewer.isOverviewRulerVisible()) {
OverviewRuler or= fAdaptedSourceViewer.getOverviewRuler();
orWidth= or.getWidth();
or.getControl().setBounds(clArea.width - orWidth, scrollbarHeight, orWidth, clArea.height - 3*scrollbarHeight);
}
textWidget.setBounds(vrWidth + fGap, 0, clArea.width - vrWidth - orWidth - 2*fGap, clArea.height);
vr.getControl().setBounds(0, 0, vrWidth, clArea.height - scrollbarHeight);
} else {
StyledText textWidget= fAdaptedSourceViewer.getTextWidget();
textWidget.setBounds(0, 0, clArea.width, clArea.height);
}
}
};
class AdaptedSourceViewer extends JavaCorrectionSourceViewer {
private List fTextConverters;
private OverviewRuler fOverviewRuler;
private boolean fIsOverviewRulerVisible;
private IVerticalRuler fCachedVerticalRuler;
private boolean fCachedIsVerticalRulerVisible;
public AdaptedSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
super(parent, ruler, styles, CompilationUnitEditor.this);
fCachedVerticalRuler= ruler;
fCachedIsVerticalRulerVisible= (ruler != null);
fOverviewRuler= new OverviewRuler(VERTICAL_RULER_WIDTH);
delayedCreateControl(parent, styles);
}
/*
* @see ISourceViewer#showAnnotations(boolean)
*/
public void showAnnotations(boolean show) {
fCachedIsVerticalRulerVisible= (show && fCachedVerticalRuler != null);
super.showAnnotations(show);
}
public IContentAssistant getContentAssistant() {
return fContentAssistant;
}
/*
* @see ITextOperationTarget#doOperation(int)
*/
public void doOperation(int operation) {
if (getTextWidget() == null)
return;
switch (operation) {
case CONTENTASSIST_PROPOSALS:
String msg= fContentAssistant.showPossibleCompletions();
setStatusLineErrorMessage(msg);
return;
}
super.doOperation(operation);
}
public void insertTextConverter(ITextConverter textConverter, int index) {
throw new UnsupportedOperationException();
}
public void addTextConverter(ITextConverter textConverter) {
if (fTextConverters == null) {
fTextConverters= new ArrayList(1);
fTextConverters.add(textConverter);
} else if (!fTextConverters.contains(textConverter))
fTextConverters.add(textConverter);
}
public void removeTextConverter(ITextConverter textConverter) {
if (fTextConverters != null) {
fTextConverters.remove(textConverter);
if (fTextConverters.size() == 0)
fTextConverters= null;
}
}
/*
* @see TextViewer#customizeDocumentCommand(DocumentCommand)
*/
protected void customizeDocumentCommand(DocumentCommand command) {
super.customizeDocumentCommand(command);
if (fTextConverters != null) {
for (Iterator e = fTextConverters.iterator(); e.hasNext();)
((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), command);
}
}
public IVerticalRuler getVerticalRuler() {
return fCachedVerticalRuler;
}
public boolean isVerticalRulerVisible() {
return fCachedIsVerticalRulerVisible;
}
public OverviewRuler getOverviewRuler() {
return fOverviewRuler;
}
/*
* @see TextViewer#createControl(Composite, int)
*/
protected void createControl(Composite parent, int styles) {
// do nothing here
}
protected void delayedCreateControl(Composite parent, int styles) {
//create the viewer
super.createControl(parent, styles);
Control control= getControl();
if (control instanceof Composite) {
Composite composite= (Composite) control;
composite.setLayout(new AdaptedRulerLayout(GAP_SIZE, this));
fOverviewRuler.createControl(composite, this);
}
}
public void hideOverviewRuler() {
fIsOverviewRulerVisible= false;
Control control= getControl();
if (control instanceof Composite) {
Composite composite= (Composite) control;
composite.layout();
}
}
public void showOverviewRuler() {
fIsOverviewRulerVisible= true;
Control control= getControl();
if (control instanceof Composite) {
Composite composite= (Composite) control;
composite.layout();
}
}
public boolean isOverviewRulerVisible() {
return fIsOverviewRulerVisible;
}
/*
* @see ISourceViewer#setDocument(IDocument, IAnnotationModel, int, int)
*/
public void setDocument(IDocument document, IAnnotationModel annotationModel, int visibleRegionOffset, int visibleRegionLength) {
super.setDocument(document, annotationModel, visibleRegionOffset, visibleRegionLength);
fOverviewRuler.setModel(annotationModel);
}
};
static class TabConverter implements ITextConverter {
private int fTabRatio;
private ILineTracker fLineTracker;
public TabConverter() {
}
public void setNumberOfSpacesPerTab(int ratio) {
fTabRatio= ratio;
}
public void setLineTracker(ILineTracker lineTracker) {
fLineTracker= lineTracker;
}
private int insertTabString(StringBuffer buffer, int offsetInLine) {
int remainder= offsetInLine % fTabRatio;
remainder= fTabRatio - remainder;
for (int i= 0; i < remainder; i++)
buffer.append(' ');
return remainder;
}
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
String text= command.text;
if (text == null)
return;
int index= text.indexOf('\t');
if (index > -1) {
StringBuffer buffer= new StringBuffer();
fLineTracker.set(command.text);
int lines= fLineTracker.getNumberOfLines();
try {
for (int i= 0; i < lines; i++) {
int offset= fLineTracker.getLineOffset(i);
int endOffset= offset + fLineTracker.getLineLength(i);
String line= text.substring(offset, endOffset);
int position= 0;
if (i == 0) {
IRegion firstLine= document.getLineInformationOfOffset(command.offset);
position= command.offset - firstLine.getOffset();
}
int length= line.length();
for (int j= 0; j < length; j++) {
char c= line.charAt(j);
if (c == '\t') {
position += insertTabString(buffer, position);
} else {
buffer.append(c);
++ position;
}
}
}
command.text= buffer.toString();
} catch (BadLocationException x) {
}
}
}
};
/* Preference key for code formatter tab size */
private final static String CODE_FORMATTER_TAB_SIZE= "org.eclipse.jdt.core.formatter.tabulation.size"; //$NON-NLS-1$
/* Preference key for code formatter tab character */
private final static String CODE_FORMATTER_TAB_CHAR= "org.eclipse.jdt.core.formatter.tabulation.char"; //$NON-NLS-1$
/** Preference key for matching brackets */
public final static String MATCHING_BRACKETS= "matchingBrackets"; //$NON-NLS-1$
/** Preference key for matching brackets color */
public final static String MATCHING_BRACKETS_COLOR= "matchingBracketsColor"; //$NON-NLS-1$
/** Preference key for highlighting current line */
public final static String CURRENT_LINE= "currentLine"; //$NON-NLS-1$
/** Preference key for highlight color of current line */
public final static String CURRENT_LINE_COLOR= "currentLineColor"; //$NON-NLS-1$
/** Preference key for showing print marging ruler */
public final static String PRINT_MARGIN= "printMargin"; //$NON-NLS-1$
/** Preference key for print margin ruler color */
public final static String PRINT_MARGIN_COLOR= "printMarginColor"; //$NON-NLS-1$
/** Preference key for print margin ruler column */
public final static String PRINT_MARGIN_COLUMN= "printMarginColumn"; //$NON-NLS-1$
/** Preference key for inserting spaces rather than tabs */
public final static String SPACES_FOR_TABS= "spacesForTabs"; //$NON-NLS-1$
/** Preference key for problem indication */
public final static String PROBLEM_INDICATION= "problemIndication"; //$NON-NLS-1$
/** Preference key for problem highlight color */
public final static String PROBLEM_INDICATION_COLOR= "problemIndicationColor"; //$NON-NLS-1$
/** Preference key for shwoing the overview ruler */
public final static String OVERVIEW_RULER= "overviewRuler"; //$NON-NLS-1$
/** The status line clearer */
protected ISelectionChangedListener fStatusLineClearer;
/** The editor's save policy */
protected ISavePolicy fSavePolicy;
/** Listener to annotation model changes that updates the error tick in the tab image */
private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
/** The editor's paint manager */
private PaintManager fPaintManager;
/** The editor's bracket painter */
private BracketPainter fBracketPainter;
/** The editor's line painter */
private LinePainter fLinePainter;
/** The editor's print margin ruler painter */
private PrintMarginPainter fPrintMarginPainter;
/** The editor's problem painter */
private ProblemPainter fProblemPainter;
/** The editor's tab converter */
private TabConverter fTabConverter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The standard action groups added to the menu */
/* package */ CompositeActionGroup fStandardActionGroups;
/**
* Creates a new compilation unit editor.
*/
public CompilationUnitEditor() {
super();
setDocumentProvider(JavaPlugin.getDefault().getCompilationUnitDocumentProvider());
setEditorContextMenuId("#CompilationUnitEditorContext"); //$NON-NLS-1$
setRulerContextMenuId("#CompilationUnitRulerContext"); //$NON-NLS-1$
setOutlinerContextMenuId("#CompilationUnitOutlinerContext"); //$NON-NLS-1$
setHelpContextId(IJavaHelpContextIds.COMPILATION_UNIT_EDITOR);
fSavePolicy= null;
fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this);
}
/*
* @see AbstractTextEditor#createActions()
*/
protected void createActions() {
super.createActions();
setAction("CorrectionAssistProposal", new TextOperationAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal.", this, JavaCorrectionSourceViewer.CORRECTIONASSIST_PROPOSALS)); //$NON-NLS-1$ //$NON-NLS-2$
setAction("ContentAssistProposal", new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this, ISourceViewer.CONTENTASSIST_PROPOSALS)); //$NON-NLS-1$ //$NON-NLS-2$
setAction("ContentAssistContextInformation", new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION)); //$NON-NLS-1$ //$NON-NLS-2$
setAction("AddImportOnSelection", new AddImportOnSelectionAction(this)); //$NON-NLS-1$
setAction("OrganizeImports", new OrganizeImportsAction(this)); //$NON-NLS-1$
setAction("Comment", new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX)); //$NON-NLS-1$ //$NON-NLS-2$
setAction("Uncomment", new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX)); //$NON-NLS-1$ //$NON-NLS-2$
setAction("Format", new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT)); //$NON-NLS-1$ //$NON-NLS-2$
setAction("SurroundWithTryCatch", new SurroundWithTryCatchAction(this)); //$NON-NLS-1$
fSelectionHistory= new SelectionHistory(this);
setAction(StructureSelectionAction.ENCLOSING, new StructureSelectEnclosingAction(this, fSelectionHistory));
setAction(StructureSelectionAction.NEXT, new StructureSelectNextAction(this, fSelectionHistory));
setAction(StructureSelectionAction.PREVIOUS, new StructureSelectPreviousAction(this, fSelectionHistory));
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
fStandardActionGroups= new CompositeActionGroup(new ActionGroup[] {
new OpenEditorActionGroup(this), new OpenViewActionGroup(this), new ShowActionGroup(this), new GenerateActionGroup(this)});
}
/*
* @see JavaEditor#getElementAt(int)
*/
protected IJavaElement getElementAt(int offset) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
synchronized (unit) {
try {
unit.reconcile();
return unit.getElementAt(offset);
} catch (JavaModelException x) {
}
}
}
return null;
}
/*
* @see JavaEditor#getCorrespondingElement(IJavaElement)
*/
protected IJavaElement getCorrespondingElement(IJavaElement element) {
try {
return EditorUtility.getWorkingCopy(element, true);
} catch (JavaModelException x) {
// nothing found, be tolerant and go on
}
return null;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
/*
* http://dev.eclipse.org/bugs/show_bug.cgi?id=8735
* Removed duplicates of Edit menu entries to shorten context menu.
* Will be reworked for overal context menu reorganization.
*/
// addAction(menu, IContextMenuConstants.GROUP_GENERATE, "ContentAssistProposal"); //$NON-NLS-1$
addAction(menu, IContextMenuConstants.GROUP_GENERATE, "AddImportOnSelection"); //$NON-NLS-1$
addAction(menu, IContextMenuConstants.GROUP_GENERATE, "OrganizeImports"); //$NON-NLS-1$
addAction(menu, IContextMenuConstants.GROUP_GENERATE, "CorrectionAssistProposal"); //$NON-NLS-1$
addAction(menu, IContextMenuConstants.GROUP_GENERATE, "SurroundWithTryCatch"); //$NON-NLS-1$
addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Comment"); //$NON-NLS-1$
addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Uncomment"); //$NON-NLS-1$
addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); //$NON-NLS-1$
}
/*
* @see JavaEditor#createOutlinePage()
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= super.createOutlinePage();
page.setAction("OrganizeImports", new OrganizeImportsAction(this)); //$NON-NLS-1$
//page.setAction("ReplaceWithEdition", new JavaReplaceWithEditionAction(page)); //$NON-NLS-1$
//page.setAction("AddEdition", new JavaAddElementFromHistory(this, page)); //$NON-NLS-1$
IAction deleteElement= ReorgGroup.createDeleteAction(page);
page.setAction("DeleteElement", deleteElement); //$NON-NLS-1$
return page;
}
/*
* @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
*/
protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
if (page != null) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
page.setInput(manager.getWorkingCopy(input));
}
}
/*
* @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, IProgressMonitor)
*/
protected void performSaveOperation(WorkspaceModifyOperation operation, IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p;
cp.setSavePolicy(fSavePolicy);
}
try {
super.performSaveOperation(operation, progressMonitor);
} finally {
if (p instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p;
cp.setSavePolicy(null);
}
}
}
/*
* @see AbstractTextEditor#doSave(IProgressMonitor)
*/
public void doSave(IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p == null)
return;
if (p.isDeleted(getEditorInput())) {
if (isSaveAsAllowed()) {
/*
* 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
* Changed Behavior to make sure that if called inside a regular save (because
* of deletion of input element) there is a way to report back to the caller.
*/
performSaveAs(progressMonitor);
} else {
/*
* 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
* Missing resources.
*/
Shell shell= getSite().getShell();
MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
setStatusLineErrorMessage(null);
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
synchronized (unit) {
performSaveOperation(createSaveOperation(false), progressMonitor);
}
} else
performSaveOperation(createSaveOperation(false), progressMonitor);
}
}
/**
* Jumps to the error next according to the given direction.
*/
public void gotoError(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
if (fStatusLineClearer != null) {
provider.removeSelectionChangedListener(fStatusLineClearer);
fStatusLineClearer= null;
}
ITextSelection s= (ITextSelection) provider.getSelection();
IMarker nextError= getNextError(s.getOffset(), forward);
if (nextError != null) {
gotoMarker(nextError);
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(nextError);
((TaskList) view).setSelection(ss, true);
}
setStatusLineErrorMessage(nextError.getAttribute(IMarker.MESSAGE, "")); //$NON-NLS-1$
} else {
setStatusLineErrorMessage(null);
}
}
/**
* Sets the given message as error message to this editor's status line.
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
// set error message
getStatusLineManager().setErrorMessage(msg);
// install message remover
if (msg == null || msg.trim().length() == 0) {
if (fStatusLineClearer != null) {
getSelectionProvider().removeSelectionChangedListener(fStatusLineClearer);
fStatusLineClearer= null;
}
} else if (fStatusLineClearer == null) {
fStatusLineClearer= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
getSelectionProvider().removeSelectionChangedListener(fStatusLineClearer);
fStatusLineClearer= null;
getStatusLineManager().setErrorMessage(null);
}
};
getSelectionProvider().addSelectionChangedListener(fStatusLineClearer);
}
}
private IMarker getNextError(int offset, boolean forward) {
IMarker nextError= null;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= model.getAnnotationIterator();
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (a instanceof MarkerAnnotation) {
MarkerAnnotation ma= (MarkerAnnotation) a;
IMarker marker= ma.getMarker();
if (MarkerUtilities.isMarkerType(marker, IMarker.PROBLEM)) {
Position p= model.getPosition(a);
if (!p.includes(offset)) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextError == null || currentDistance < distance) {
distance= currentDistance;
nextError= marker;
}
}
}
}
}
return nextError;
}
/*
* @see AbstractTextEditor#isSaveAsAllowed()
*/
public boolean isSaveAsAllowed() {
return true;
}
/*
* 1GF7WG9: ITPJUI:ALL - EXCEPTION: "Save As..." always fails
*/
protected IPackageFragment getPackage(IWorkspaceRoot root, IPath path) {
if (path.segmentCount() == 1) {
IProject project= root.getProject(path.toString());
if (project != null) {
IJavaProject jProject= JavaCore.create(project);
if (jProject != null) {
try {
IJavaElement element= jProject.findElement(new Path("")); //$NON-NLS-1$
if (element instanceof IPackageFragment) {
IPackageFragment fragment= (IPackageFragment) element;
IJavaElement parent= fragment.getParent();
if (parent instanceof IPackageFragmentRoot) {
IPackageFragmentRoot pRoot= (IPackageFragmentRoot) parent;
if ( !pRoot.isArchive() && !pRoot.isExternal() && path.equals(pRoot.getPath()))
return fragment;
}
}
} catch (JavaModelException x) {
// ignore
}
}
}
return null;
} else if (path.segmentCount() > 1) {
IFolder folder= root.getFolder(path);
IJavaElement element= JavaCore.create(folder);
if (element instanceof IPackageFragment)
return (IPackageFragment) element;
}
return null;
}
/*
* 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
* Changed behavior to make sure that if called inside a regular save (because
* of deletion of input element) there is a way to report back to the caller.
*/
protected void performSaveAs(IProgressMonitor progressMonitor) {
Shell shell= getSite().getShell();
SaveAsDialog dialog= new SaveAsDialog(shell);
IEditorInput input = getEditorInput();
IFile original= null;
if (input instanceof IFileEditorInput)
original= ((IFileEditorInput) input).getFile();
if (original != null)
dialog.setOriginalFile(original);
if (dialog.open() == Dialog.CANCEL) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IPath filePath= dialog.getResult();
if (filePath == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
filePath= filePath.removeTrailingSeparator();
final String fileName= filePath.lastSegment();
IPath folderPath= filePath.removeLastSegments(1);
if (folderPath == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
/*
* 1GF7WG9: ITPJUI:ALL - EXCEPTION: "Save As..." always fails
*/
final IPackageFragment fragment= getPackage(root, folderPath);
IFile file= root.getFile(filePath);
/*
* Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=8873
* Problem caused by http://dev.eclipse.org/bugs/show_bug.cgi?id=9351
* Will be removed if #9351 is solved.
*/
if (original != null && original.equals(file)) {
doSave(progressMonitor);
return;
}
/* end of fix */
final FileEditorInput newInput= new FileEditorInput(file);
WorkspaceModifyOperation op= new WorkspaceModifyOperation() {
public void execute(final IProgressMonitor monitor) throws CoreException {
if (fragment != null) {
try {
// copy to another package
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
/*
* 1GJXY0L: ITPJUI:WINNT - NPE during save As in Java editor
* Introduced null check, just go on in the null case
*/
if (unit != null) {
/*
* 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
* Changed false to true.
*/
unit.copy(fragment, null, fileName, true, monitor);
return;
}
} catch (JavaModelException x) {
}
}
// if (fragment == null) then copy to a directory which is not a package
// if (unit == null) copy the file that is not a compilation unit
/*
* 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
* Changed false to true.
*/
getDocumentProvider().saveDocument(monitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true);
}
};
boolean success= false;
try {
if (fragment == null)
getDocumentProvider().aboutToChange(newInput);
new ProgressMonitorDialog(shell).run(false, true, op);
setInput(newInput);
success= true;
} catch (InterruptedException x) {
} catch (InvocationTargetException x) {
/*
* 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
* Missing resources.
*/
Throwable t= x.getTargetException();
if (t instanceof CoreException) {
CoreException cx= (CoreException) t;
ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), cx.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
} else {
MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title3"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message3") + t.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
} finally {
if (fragment == null)
getDocumentProvider().changed(newInput);
if (progressMonitor != null)
progressMonitor.setCanceled(!success);
}
}
/*
* @see AbstractTextEditor#doSetInput(IEditorInput)
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
fJavaEditorErrorTickUpdater.setAnnotationModel(getDocumentProvider().getAnnotationModel(input));
configureTabConverter();
}
private void startBracketHighlighting() {
if (fBracketPainter == null) {
ISourceViewer sourceViewer= getSourceViewer();
fBracketPainter= new BracketPainter(sourceViewer);
fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
fPaintManager.addPainter(fBracketPainter);
}
}
private void stopBracketHighlighting() {
if (fBracketPainter != null) {
fPaintManager.removePainter(fBracketPainter);
fBracketPainter.deactivate(true);
fBracketPainter.dispose();
fBracketPainter= null;
}
}
private boolean isBracketHighlightingEnabled() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(MATCHING_BRACKETS);
}
private void startLineHighlighting() {
if (fLinePainter == null) {
ISourceViewer sourceViewer= getSourceViewer();
fLinePainter= new LinePainter(sourceViewer);
fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
fPaintManager.addPainter(fLinePainter);
}
}
private void stopLineHighlighting() {
if (fLinePainter != null) {
fPaintManager.removePainter(fLinePainter);
fLinePainter.deactivate(true);
fLinePainter.dispose();
fLinePainter= null;
}
}
private boolean isLineHighlightingEnabled() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(CURRENT_LINE);
}
private void startShowingPrintMargin() {
if (fPrintMarginPainter == null) {
fPrintMarginPainter= new PrintMarginPainter(getSourceViewer());
fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
fPaintManager.addPainter(fPrintMarginPainter);
}
}
private void stopShowingPrintMargin() {
if (fPrintMarginPainter != null) {
fPaintManager.removePainter(fPrintMarginPainter);
fPrintMarginPainter.deactivate(true);
fPrintMarginPainter.dispose();
fPrintMarginPainter= null;
}
}
private boolean isShowingPrintMarginEnabled() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(PRINT_MARGIN);
}
private void startProblemIndication() {
if (fProblemPainter == null) {
fProblemPainter= new ProblemPainter(this, getSourceViewer());
fProblemPainter.setHighlightColor(getColor(PROBLEM_INDICATION_COLOR));
fPaintManager.addPainter(fProblemPainter);
}
}
private void stopProblemIndication() {
if (fProblemPainter != null) {
fPaintManager.removePainter(fProblemPainter);
fProblemPainter.deactivate(true);
fProblemPainter.dispose();
fProblemPainter= null;
}
}
private boolean isProblemIndicationEnabled() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(PROBLEM_INDICATION);
}
private void configureTabConverter() {
if (fTabConverter != null) {
IDocumentProvider provider= getDocumentProvider();
if (provider instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cup= (CompilationUnitDocumentProvider) provider;
fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
}
}
}
private void startTabConversion() {
if (fTabConverter == null) {
fTabConverter= new TabConverter();
configureTabConverter();
fTabConverter.setNumberOfSpacesPerTab(getPreferenceStore().getInt(CODE_FORMATTER_TAB_SIZE));
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.addTextConverter(fTabConverter);
}
}
private void stopTabConversion() {
if (fTabConverter != null) {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.removeTextConverter(fTabConverter);
fTabConverter= null;
}
}
private boolean isTabConversionEnabled() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(SPACES_FOR_TABS);
}
private void startShowingOverviewRuler() {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.showOverviewRuler();
}
private void stopShowingOverviewRuler() {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.hideOverviewRuler();
}
private boolean isShowingOverviewRuler() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(OVERVIEW_RULER);
}
private Color getColor(String key) {
RGB rgb= PreferenceConverter.getColor(getPreferenceStore(), key);
return getColor(rgb);
}
private Color getColor(RGB rgb) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.getColorManager().getColor(rgb);
}
/*
* @see AbstractTextEditor#dispose()
*/
public void dispose() {
if (fJavaEditorErrorTickUpdater != null) {
fJavaEditorErrorTickUpdater.setAnnotationModel(null);
fJavaEditorErrorTickUpdater= null;
}
if (fSelectionHistory != null)
fSelectionHistory.dispose();
stopBracketHighlighting();
stopLineHighlighting();
if (fPaintManager != null) {
fPaintManager.dispose();
fPaintManager= null;
}
super.dispose();
}
/*
* @see AbstractTextEditor#createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
fPaintManager= new PaintManager(getSourceViewer());
if (isBracketHighlightingEnabled())
startBracketHighlighting();
if (isLineHighlightingEnabled())
startLineHighlighting();
if (isShowingPrintMarginEnabled())
startShowingPrintMargin();
if (isProblemIndicationEnabled())
startProblemIndication();
if (isTabConversionEnabled())
startTabConversion();
if (isShowingOverviewRuler())
startShowingOverviewRuler();
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
if (asv != null) {
String p= event.getProperty();
if (CODE_FORMATTER_TAB_SIZE.equals(p) || CODE_FORMATTER_TAB_CHAR.equals(p)) {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(asv);
for (int i= 0; i < types.length; i++)
asv.setIndentPrefixes(configuration.getIndentPrefixes(asv, types[i]), types[i]);
if (fTabConverter != null)
fTabConverter.setNumberOfSpacesPerTab(getPreferenceStore().getInt(CODE_FORMATTER_TAB_SIZE));
}
if (SPACES_FOR_TABS.equals(p)) {
if (isTabConversionEnabled())
startTabConversion();
else
stopTabConversion();
return;
}
if (MATCHING_BRACKETS.equals(p)) {
if (isBracketHighlightingEnabled())
startBracketHighlighting();
else
stopBracketHighlighting();
return;
}
if (MATCHING_BRACKETS_COLOR.equals(p)) {
if (fBracketPainter != null)
fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
return;
}
if (CURRENT_LINE.equals(p)) {
if (isLineHighlightingEnabled())
startLineHighlighting();
else
stopLineHighlighting();
return;
}
if (CURRENT_LINE_COLOR.equals(p)) {
if (fLinePainter != null)
fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
return;
}
if (PRINT_MARGIN.equals(p)) {
if (isShowingPrintMarginEnabled())
startShowingPrintMargin();
else
stopShowingPrintMargin();
return;
}
if (PRINT_MARGIN_COLOR.equals(p)) {
if (fPrintMarginPainter != null)
fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
return;
}
if (PRINT_MARGIN_COLUMN.equals(p)) {
if (fPrintMarginPainter != null)
fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
return;
}
if (PROBLEM_INDICATION.equals(p)) {
if (isProblemIndicationEnabled())
startProblemIndication();
else
stopProblemIndication();
return;
}
if (PROBLEM_INDICATION_COLOR.equals(p)) {
if (fProblemPainter != null)
fProblemPainter.setHighlightColor(getColor(PROBLEM_INDICATION_COLOR));
return;
}
if (OVERVIEW_RULER.equals(p)) {
if (isShowingOverviewRuler())
startShowingOverviewRuler();
else
stopShowingOverviewRuler();
return;
}
IContentAssistant c= asv.getContentAssistant();
if (c instanceof ContentAssistant)
ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event);
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
String p= event.getProperty();
boolean affects=MATCHING_BRACKETS_COLOR.equals(p) ||
CURRENT_LINE_COLOR.equals(p) ||
PROBLEM_INDICATION_COLOR.equals(p);
return affects ? affects : super.affectsTextPresentation(event);
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
return new AdaptedSourceViewer(parent, ruler, styles);
}
/*
* @see IReconcilingParticipant#reconciled()
*/
public void reconciled() {
if (!WorkInProgressPreferencePage.synchronizeOutlineOnCursorMove()) {
Shell shell= getSite().getShell();
if (shell != null && !shell.isDisposed()) {
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
synchronizeOutlinePageSelection();
}
});
}
}
}
}
|
13,507 |
Bug 13507 LinkedPositionUI has a reference to SWT.COLOR_RED
|
LinkedPositionUI(ITextViewer, LinkedPositionManager) - org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI has a reference to SWT.COLOR_RED which will be unreadble if the user sets their background colour to Red. We will be adding a getErrorText colour to JFaceColours in build >20020411. You may want to use that.
|
resolved fixed
|
0ceae1a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-17T12:28:28Z | 2002-04-11T13:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.ui.texteditor.WorkbenchChainedTextFontFieldEditor;
import org.eclipse.jdt.ui.text.IJavaColorConstants;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
/*
* The page for setting the editor options.
*/
public class JavaEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String BOLD= "_bold"; //$NON-NLS-1$
public final OverlayPreferenceStore.OverlayKey[] fKeys= new OverlayPreferenceStore.OverlayKey[] {
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_MULTI_LINE_COMMENT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_KEYWORD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_KEYWORD + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_STRING),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_STRING + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_DEFAULT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_DEFAULT + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_KEYWORD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_KEYWORD + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_TAG),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_TAG + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_LINK),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_LINK + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_DEFAULT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_DEFAULT + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.MATCHING_BRACKETS_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.MATCHING_BRACKETS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.CURRENT_LINE_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.CURRENT_LINE),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.PRINT_MARGIN_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, CompilationUnitEditor.PRINT_MARGIN_COLUMN),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.PRINT_MARGIN),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.PROBLEM_INDICATION_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.PROBLEM_INDICATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitDocumentProvider.HANDLE_TEMPRARY_PROBELMS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.OVERVIEW_RULER),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.SPACES_FOR_TABS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.AUTOACTIVATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, ContentAssistPreference.AUTOACTIVATION_DELAY),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.AUTOINSERT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PROPOSALS_BACKGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PROPOSALS_FOREGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PARAMETERS_BACKGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PARAMETERS_FOREGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVA),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVADOC),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.SHOW_VISIBLE_PROPOSALS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.ORDER_PROPOSALS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.CASE_SENSITIVITY),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.ADD_IMPORT)
};
private final String[][] fListModel= new String[][] {
{ JavaUIMessages.getString("JavaEditorPreferencePage.multiLineComment"), IJavaColorConstants.JAVA_MULTI_LINE_COMMENT }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.singleLineComment"), IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.keywords"), IJavaColorConstants.JAVA_KEYWORD }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.strings"), IJavaColorConstants.JAVA_STRING }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.others"), IJavaColorConstants.JAVA_DEFAULT }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.javaDocKeywords"), IJavaColorConstants.JAVADOC_KEYWORD }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.javaDocHtmlTags"), IJavaColorConstants.JAVADOC_TAG }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.javaDocLinks"), IJavaColorConstants.JAVADOC_LINK }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.javaDocOthers"), IJavaColorConstants.JAVADOC_DEFAULT } //$NON-NLS-1$
};
private OverlayPreferenceStore fOverlayStore;
private JavaTextTools fJavaTextTools;
private Map fColorButtons= new HashMap();
private SelectionListener fColorButtonListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
ColorEditor editor= (ColorEditor) e.widget.getData();
PreferenceConverter.setValue(fOverlayStore, (String) fColorButtons.get(editor), editor.getColorValue());
}
};
private Map fCheckBoxes= new HashMap();
private SelectionListener fCheckBoxListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
Button button= (Button) e.widget;
fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection());
}
};
private Map fTextFields= new HashMap();
private ModifyListener fTextFieldListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
Text text= (Text) e.widget;
fOverlayStore.setValue((String) fTextFields.get(text), text.getText());
}
};
private WorkbenchChainedTextFontFieldEditor fFontEditor;
private List fList;
private ColorEditor fForegroundColorEditor;
private ColorEditor fBackgroundColorEditor;
private Button fBackgroundDefaultRadioButton;
private Button fBackgroundCustomRadioButton;
private Button fBackgroundColorButton;
private Button fBoldCheckBox;
private SourceViewer fPreviewViewer;
public JavaEditorPreferencePage() {
setDescription(JavaUIMessages.getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), fKeys);
}
public static void initDefaults(IPreferenceStore store) {
Color color;
Display display= Display.getDefault();
store.setDefault(CompilationUnitEditor.MATCHING_BRACKETS, true);
color= display.getSystemColor(SWT.COLOR_GRAY);
PreferenceConverter.setDefault(store, CompilationUnitEditor.MATCHING_BRACKETS_COLOR, color.getRGB());
store.setDefault(CompilationUnitEditor.CURRENT_LINE, true);
PreferenceConverter.setDefault(store, CompilationUnitEditor.CURRENT_LINE_COLOR, new RGB(225, 235, 224));
store.setDefault(CompilationUnitEditor.PRINT_MARGIN, false);
store.setDefault(CompilationUnitEditor.PRINT_MARGIN_COLUMN, 80);
PreferenceConverter.setDefault(store, CompilationUnitEditor.PRINT_MARGIN_COLOR, new RGB(176, 180 , 185));
PreferenceConverter.setDefault(store, AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE, new RGB(185, 176 , 180));
store.setDefault(CompilationUnitEditor.PROBLEM_INDICATION, true);
PreferenceConverter.setDefault(store, CompilationUnitEditor.PROBLEM_INDICATION_COLOR, new RGB(255, 0 , 128));
store.setDefault(CompilationUnitDocumentProvider.HANDLE_TEMPRARY_PROBELMS, true);
store.setDefault(CompilationUnitEditor.OVERVIEW_RULER, true);
WorkbenchChainedTextFontFieldEditor.startPropagate(store, JFaceResources.TEXT_FONT);
color= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND);
PreferenceConverter.setDefault(store, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, color.getRGB());
store.setDefault(AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT, true);
color= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
PreferenceConverter.setDefault(store, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, color.getRGB());
store.setDefault(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, true);
store.setDefault(JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH, 4);
store.setDefault(CompilationUnitEditor.SPACES_FOR_TABS, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_MULTI_LINE_COMMENT, new RGB(63, 127, 95));
store.setDefault(IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT, new RGB(63, 127, 95));
store.setDefault(IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_KEYWORD, new RGB(127, 0, 85));
store.setDefault(IJavaColorConstants.JAVA_KEYWORD + BOLD, true);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_STRING, new RGB(42, 0, 255));
store.setDefault(IJavaColorConstants.JAVA_STRING + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_DEFAULT, new RGB(0, 0, 0));
store.setDefault(IJavaColorConstants.JAVA_DEFAULT + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_KEYWORD, new RGB(127, 159, 191));
store.setDefault(IJavaColorConstants.JAVADOC_KEYWORD + BOLD, true);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_TAG, new RGB(127, 127, 159));
store.setDefault(IJavaColorConstants.JAVADOC_TAG + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_LINK, new RGB(63, 63, 191));
store.setDefault(IJavaColorConstants.JAVADOC_LINK + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_DEFAULT, new RGB(63, 95, 191));
store.setDefault(IJavaColorConstants.JAVADOC_DEFAULT + BOLD, false);
store.setDefault(ContentAssistPreference.AUTOACTIVATION, true);
store.setDefault(ContentAssistPreference.AUTOACTIVATION_DELAY, 500);
store.setDefault(ContentAssistPreference.AUTOINSERT, true);
PreferenceConverter.setDefault(store, ContentAssistPreference.PROPOSALS_BACKGROUND, new RGB(254, 241, 233));
PreferenceConverter.setDefault(store, ContentAssistPreference.PROPOSALS_FOREGROUND, new RGB(0, 0, 0));
PreferenceConverter.setDefault(store, ContentAssistPreference.PARAMETERS_BACKGROUND, new RGB(254, 241, 233));
PreferenceConverter.setDefault(store, ContentAssistPreference.PARAMETERS_FOREGROUND, new RGB(0, 0, 0));
store.setDefault(ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$
store.setDefault(ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); //$NON-NLS-1$
store.setDefault(ContentAssistPreference.SHOW_VISIBLE_PROPOSALS, true);
store.setDefault(ContentAssistPreference.CASE_SENSITIVITY, false);
store.setDefault(ContentAssistPreference.ORDER_PROPOSALS, false);
store.setDefault(ContentAssistPreference.ADD_IMPORT, true);
}
/*
* @see IWorkbenchPreferencePage#init()
*/
public void init(IWorkbench workbench) {
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE);
}
private void handleListSelection() {
int i= fList.getSelectionIndex();
String key= fListModel[i][1];
RGB rgb= PreferenceConverter.getColor(fOverlayStore, key);
fForegroundColorEditor.setColorValue(rgb);
fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + BOLD));
}
private Control createColorPage(Composite parent) {
Composite colorComposite= new Composite(parent, SWT.NULL);
colorComposite.setLayout(new GridLayout());
Composite backgroundComposite= new Composite(colorComposite, SWT.NULL);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
backgroundComposite.setLayout(layout);
Label label= new Label(backgroundComposite, SWT.NULL);
label.setText(JavaUIMessages.getString("JavaEditorPreferencePage.backgroundColor")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 2;
label.setLayoutData(gd);
SelectionListener backgroundSelectionListener= new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
boolean custom= fBackgroundCustomRadioButton.getSelection();
fBackgroundColorButton.setEnabled(custom);
fOverlayStore.setValue(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, !custom);
}
public void widgetDefaultSelected(SelectionEvent e) {}
};
fBackgroundDefaultRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT);
fBackgroundDefaultRadioButton.setText(JavaUIMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalSpan= 2;
fBackgroundDefaultRadioButton.setLayoutData(gd);
fBackgroundDefaultRadioButton.addSelectionListener(backgroundSelectionListener);
fBackgroundCustomRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT);
fBackgroundCustomRadioButton.setText(JavaUIMessages.getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$
fBackgroundCustomRadioButton.addSelectionListener(backgroundSelectionListener);
fBackgroundColorEditor= new ColorEditor(backgroundComposite);
fBackgroundColorButton= fBackgroundColorEditor.getButton();
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
fBackgroundColorButton.setLayoutData(gd);
label= new Label(colorComposite, SWT.LEFT);
label.setText(JavaUIMessages.getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Composite editorComposite= new Composite(colorComposite, SWT.NULL);
layout= new GridLayout();
layout.numColumns= 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
editorComposite.setLayout(layout);
gd= new GridData(GridData.FILL_BOTH);
editorComposite.setLayoutData(gd);
fList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL);
gd= new GridData(GridData.FILL_BOTH);
gd.heightHint= convertHeightInCharsToPixels(5);
fList.setLayoutData(gd);
Composite stylesComposite= new Composite(editorComposite, SWT.NULL);
layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
stylesComposite.setLayout(layout);
stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
label= new Label(stylesComposite, SWT.LEFT);
label.setText(JavaUIMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
fForegroundColorEditor= new ColorEditor(stylesComposite);
Button foregroundColorButton= fForegroundColorEditor.getButton();
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
foregroundColorButton.setLayoutData(gd);
label= new Label(stylesComposite, SWT.LEFT);
label.setText(JavaUIMessages.getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
fBoldCheckBox= new Button(stylesComposite, SWT.CHECK);
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
fBoldCheckBox.setLayoutData(gd);
label= new Label(colorComposite, SWT.LEFT);
label.setText(JavaUIMessages.getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Control previewer= createPreviewer(colorComposite);
gd= new GridData(GridData.FILL_BOTH);
gd.widthHint= convertWidthInCharsToPixels(80);
gd.heightHint= convertHeightInCharsToPixels(15);
previewer.setLayoutData(gd);
fList.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
handleListSelection();
}
});
foregroundColorButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fList.getSelectionIndex();
String key= fListModel[i][1];
PreferenceConverter.setValue(fOverlayStore, key, fForegroundColorEditor.getColorValue());
}
});
fBackgroundColorButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
PreferenceConverter.setValue(fOverlayStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, fBackgroundColorEditor.getColorValue());
}
});
fBoldCheckBox.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fList.getSelectionIndex();
String key= fListModel[i][1];
fOverlayStore.setValue(key + BOLD, fBoldCheckBox.getSelection());
}
});
return colorComposite;
}
private Control createPreviewer(Composite parent) {
fJavaTextTools= new JavaTextTools(fOverlayStore);
fPreviewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL);
fPreviewViewer.configure(new JavaSourceViewerConfiguration(fJavaTextTools, null));
fPreviewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT));
fPreviewViewer.setEditable(false);
initializeViewerColors(fPreviewViewer);
String content= loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$
IDocument document= new Document(content);
IDocumentPartitioner partitioner= fJavaTextTools.createDocumentPartitioner();
partitioner.connect(document);
document.setDocumentPartitioner(partitioner);
fPreviewViewer.setDocument(document);
fOverlayStore.addPropertyChangeListener(new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
String p= event.getProperty();
if (p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND) ||
p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT))
{
initializeViewerColors(fPreviewViewer);
}
fPreviewViewer.invalidateTextPresentation();
}
});
return fPreviewViewer.getControl();
}
private Color fBackgroundColor;
/**
* Initializes the given viewer's colors.
*
* @param viewer the viewer to be initialized
*/
private void initializeViewerColors(ISourceViewer viewer) {
IPreferenceStore store= fOverlayStore;
if (store != null) {
StyledText styledText= viewer.getTextWidget();
// ---------- background color ----------------------
Color color= store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)
? null
: createColor(store, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, styledText.getDisplay());
styledText.setBackground(color);
if (fBackgroundColor != null)
fBackgroundColor.dispose();
fBackgroundColor= color;
}
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
// sets enabled flag for a control and all its sub-tree
private static void setEnabled(Control control, boolean enable) {
control.setEnabled(enable);
if (control instanceof Composite) {
Composite composite= (Composite) control;
Control[] children= composite.getChildren();
for (int i= 0; i < children.length; i++)
setEnabled(children[i], enable);
}
}
private Button fBracketHighlightButton;
private Control fBracketHighlightColor;
private Button fLineHighlightButton;
private Control fLineHighlightColor;
private Button fPrintMarginButton;
private Control fPrintMarginColor;
private Control fPrintMarginColumn;
private Button fProblemIndicationButton;
private Control fProblemIndicationColor;
private Control fFindScopeColor;
private Control createBehaviorPage(Composite parent) {
Composite behaviorComposite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout(); layout.numColumns= 2;
behaviorComposite.setLayout(layout);
String label= JavaUIMessages.getString("JavaEditorPreferencePage.textFont"); //$NON-NLS-1$
addTextFontEditor(behaviorComposite, label, AbstractTextEditor.PREFERENCE_FONT);
label= JavaUIMessages.getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$
addTextField(behaviorComposite, label, JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH, 2, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.insertSpaceForTabs"); //$NON-NLS-1$
addCheckBox(behaviorComposite, label, CompilationUnitEditor.SPACES_FOR_TABS, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.showProblemsBeforeCompiling"); //$NON-NLS-1$
addCheckBox(behaviorComposite, label, CompilationUnitDocumentProvider.HANDLE_TEMPRARY_PROBELMS, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$
addCheckBox(behaviorComposite, label, CompilationUnitEditor.OVERVIEW_RULER, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$
fBracketHighlightButton= addCheckBox(behaviorComposite, label, CompilationUnitEditor.MATCHING_BRACKETS, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.matchingBracketsHighlightColor"); //$NON-NLS-1$
fBracketHighlightColor= addColorButton(behaviorComposite, label, CompilationUnitEditor.MATCHING_BRACKETS_COLOR, 0);
fBracketHighlightButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
setEnabled(fBracketHighlightColor, fBracketHighlightButton.getSelection());
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
label= JavaUIMessages.getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$
fLineHighlightButton= addCheckBox(behaviorComposite, label, CompilationUnitEditor.CURRENT_LINE, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.currentLineHighlightColor"); //$NON-NLS-1$
fLineHighlightColor= addColorButton(behaviorComposite, label, CompilationUnitEditor.CURRENT_LINE_COLOR, 0);
fLineHighlightButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
setEnabled(fLineHighlightColor, fLineHighlightButton.getSelection());
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
label= JavaUIMessages.getString("JavaEditorPreferencePage.highlightProblems"); //$NON-NLS-1$
fProblemIndicationButton= addCheckBox(behaviorComposite, label, CompilationUnitEditor.PROBLEM_INDICATION, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.problemHighlightColor"); //$NON-NLS-1$
fProblemIndicationColor= addColorButton(behaviorComposite, label, CompilationUnitEditor.PROBLEM_INDICATION_COLOR, 0);
fProblemIndicationButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
setEnabled(fProblemIndicationColor, fProblemIndicationButton.getSelection());
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
label= JavaUIMessages.getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$
fPrintMarginButton= addCheckBox(behaviorComposite, label, CompilationUnitEditor.PRINT_MARGIN, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.printMarginColor"); //$NON-NLS-1$
fPrintMarginColor= addColorButton(behaviorComposite, label, CompilationUnitEditor.PRINT_MARGIN_COLOR, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$
fPrintMarginColumn= addTextField(behaviorComposite, label, CompilationUnitEditor.PRINT_MARGIN_COLUMN, 4, 0);
fPrintMarginButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
boolean enabled= fPrintMarginButton.getSelection();
setEnabled(fPrintMarginColor, enabled);
setEnabled(fPrintMarginColumn, enabled);
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
label= JavaUIMessages.getString("JavaEditorPreferencePage.findScope"); //$NON-NLS-1$
fFindScopeColor= addColorButton(behaviorComposite, label, AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE, 0);
return behaviorComposite;
}
private Control createContentAssistPage(Composite parent) {
Composite contentAssistComposite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout(); layout.numColumns= 2;
contentAssistComposite.setLayout(layout);
String label= JavaUIMessages.getString("JavaEditorPreferencePage.insertSingleProposalsAutomatically"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, ContentAssistPreference.AUTOINSERT, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, ContentAssistPreference.SHOW_VISIBLE_PROPOSALS, 0);
// label= "Show only proposals with &matching cases";
// addCheckBox(contentAssistComposite, label, ContentAssistPreference.CASE_SENSITIVITY, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.presentProposalsInAlphabeticalOrder"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, ContentAssistPreference.ORDER_PROPOSALS, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.enableAutoActivation"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, ContentAssistPreference.ADD_IMPORT, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.autoActivationDelay"); //$NON-NLS-1$
addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_DELAY, 4, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJava"); //$NON-NLS-1$
addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVA, 25, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJavaDoc"); //$NON-NLS-1$
addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVADOC, 25, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.backgroundForCompletionProposals"); //$NON-NLS-1$
addColorButton(contentAssistComposite, label, ContentAssistPreference.PROPOSALS_BACKGROUND, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.foregroundForCompletionProposals"); //$NON-NLS-1$
addColorButton(contentAssistComposite, label, ContentAssistPreference.PROPOSALS_FOREGROUND, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.backgroundForMethodParameters"); //$NON-NLS-1$
addColorButton(contentAssistComposite, label, ContentAssistPreference.PARAMETERS_BACKGROUND, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.foregroundForMethodParameters"); //$NON-NLS-1$
addColorButton(contentAssistComposite, label, ContentAssistPreference.PARAMETERS_FOREGROUND, 0);
return contentAssistComposite;
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
fOverlayStore.load();
fOverlayStore.start();
TabFolder folder= new TabFolder(parent, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE));
item.setControl(createBehaviorPage(folder));
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE));
item.setControl(createColorPage(folder));
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("JavaEditorPreferencePage.codeAssist")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE));
item.setControl(createContentAssistPage(folder));
initialize();
return folder;
}
private void initialize() {
fFontEditor.setPreferenceStore(getPreferenceStore());
fFontEditor.setPreferencePage(this);
fFontEditor.load();
initializeFields();
for (int i= 0; i < fListModel.length; i++)
fList.add(fListModel[i][0]);
fList.getDisplay().asyncExec(new Runnable() {
public void run() {
fList.select(0);
handleListSelection();
}
});
}
private void initializeFields() {
Iterator e= fColorButtons.keySet().iterator();
while (e.hasNext()) {
ColorEditor c= (ColorEditor) e.next();
String key= (String) fColorButtons.get(c);
RGB rgb= PreferenceConverter.getColor(fOverlayStore, key);
c.setColorValue(rgb);
}
e= fCheckBoxes.keySet().iterator();
while (e.hasNext()) {
Button b= (Button) e.next();
String key= (String) fCheckBoxes.get(b);
b.setSelection(fOverlayStore.getBoolean(key));
}
e= fTextFields.keySet().iterator();
while (e.hasNext()) {
Text t= (Text) e.next();
String key= (String) fTextFields.get(t);
t.setText(fOverlayStore.getString(key));
}
RGB rgb= PreferenceConverter.getColor(fOverlayStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND);
fBackgroundColorEditor.setColorValue(rgb);
boolean default_= fOverlayStore.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT);
fBackgroundDefaultRadioButton.setSelection(default_);
fBackgroundCustomRadioButton.setSelection(!default_);
fBackgroundColorButton.setEnabled(!default_);
setEnabled(fBracketHighlightColor, fBracketHighlightButton.getSelection());
setEnabled(fLineHighlightColor, fLineHighlightButton.getSelection());
}
/*
* @see PreferencePage#performOk()
*/
public boolean performOk() {
fFontEditor.store();
fOverlayStore.propagate();
return true;
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fFontEditor.loadDefault();
fOverlayStore.loadDefaults();
initializeFields();
handleListSelection();
super.performDefaults();
fPreviewViewer.invalidateTextPresentation();
}
/*
* @see DialogPage#dispose()
*/
public void dispose() {
if (fJavaTextTools != null) {
fJavaTextTools= null;
}
fFontEditor.setPreferencePage(null);
fFontEditor.setPreferenceStore(null);
if (fOverlayStore != null) {
fOverlayStore.stop();
fOverlayStore= null;
}
super.dispose();
}
private Control addColorButton(Composite parent, String label, String key, int indentation) {
Composite composite= new Composite(parent, SWT.NONE);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= 2;
composite.setLayoutData(gd);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
Label labelControl= new Label(composite, SWT.NONE);
labelControl.setText(label);
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent= indentation;
labelControl.setLayoutData(gd);
ColorEditor editor= new ColorEditor(composite);
Button button= editor.getButton();
button.setData(editor);
gd= new GridData();
gd.horizontalAlignment= GridData.END;
button.setLayoutData(gd);
button.addSelectionListener(fColorButtonListener);
fColorButtons.put(editor, key);
return composite;
}
private Button addCheckBox(Composite parent, String label, String key, int indentation) {
Button checkBox= new Button(parent, SWT.CHECK);
checkBox.setText(label);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent= indentation;
gd.horizontalSpan= 2;
checkBox.setLayoutData(gd);
checkBox.addSelectionListener(fCheckBoxListener);
fCheckBoxes.put(checkBox, key);
return checkBox;
}
private Control addTextField(Composite parent, String label, String key, int textLimit, int indentation) {
Composite composite= new Composite(parent, SWT.NONE);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= 2;
composite.setLayoutData(gd);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
Label labelControl= new Label(composite, SWT.NONE);
labelControl.setText(label);
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent= indentation;
labelControl.setLayoutData(gd);
Text textControl= new Text(composite, SWT.BORDER | SWT.SINGLE);
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= convertWidthInCharsToPixels(textLimit + 1);
gd.horizontalAlignment= GridData.END;
textControl.setLayoutData(gd);
textControl.setTextLimit(textLimit);
textControl.addModifyListener(fTextFieldListener);
fTextFields.put(textControl, key);
return composite;
}
private void addTextFontEditor(Composite parent, String label, String key) {
Composite editorComposite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
editorComposite.setLayout(layout);
fFontEditor= new WorkbenchChainedTextFontFieldEditor(key, label, editorComposite);
fFontEditor.setChangeButtonText(JavaUIMessages.getString("JavaEditorPreferencePage.change")); //$NON-NLS-1$
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= 2;
editorComposite.setLayoutData(gd);
}
private String loadPreviewContentFromFile(String filename) {
String line;
String separator= System.getProperty("line.separator"); //$NON-NLS-1$
StringBuffer buffer= new StringBuffer(512);
BufferedReader reader= null;
try {
reader= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename)));
while ((line= reader.readLine()) != null) {
buffer.append(line);
buffer.append(separator);
}
} catch (IOException io) {
JavaPlugin.log(io);
} finally {
if (reader != null) {
try { reader.close(); } catch (IOException e) {}
}
}
return buffer.toString();
}
}
|
13,507 |
Bug 13507 LinkedPositionUI has a reference to SWT.COLOR_RED
|
LinkedPositionUI(ITextViewer, LinkedPositionManager) - org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI has a reference to SWT.COLOR_RED which will be unreadble if the user sets their background colour to Red. We will be adding a getErrorText colour to JFaceColours in build >20020411. You may want to use that.
|
resolved fixed
|
0ceae1a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-17T12:28:28Z | 2002-04-11T13:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedPositionUI.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.text.link;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* A user interface for <code>LinkedPositionManager</code>, using <code>ITextViewer</code>.
*/
public class LinkedPositionUI implements LinkedPositionListener,
ITextInputListener, ModifyListener, VerifyListener, VerifyKeyListener, PaintListener {
/**
* A listener for notification when the user cancelled the edit operation.
*/
public interface ExitListener {
void exit(boolean accept);
}
// leave flags
private static final int UNINSTALL= 1; // uninstall linked position manager
private static final int COMMIT= 2; // commit changes
private static final int DOCUMENT_CHANGED= 4; // document has changed
private static final int UPDATE_CARET= 8; // update caret
private static final String CARET_POSITION= "LinkedPositionUI.caret.position"; //$NON-NLS-1$
private static final IPositionUpdater fgUpdater= new DefaultPositionUpdater(CARET_POSITION);
private final ITextViewer fViewer;
private final LinkedPositionManager fManager;
private final Color fFrameColor;
private int fFinalCaretOffset= -1; // no final caret offset
private Position fFramePosition;
private int fCaretOffset;
private ExitListener fExitListener;
/**
* Creates a user interface for <code>LinkedPositionManager</code>.
*
* @param viewer the text viewer.
* @param manager the <code>LinkedPositionManager</code> managing a <code>IDocument</code> of the <code>ITextViewer</code>.
*/
public LinkedPositionUI(ITextViewer viewer, LinkedPositionManager manager) {
Assert.isNotNull(viewer);
Assert.isNotNull(manager);
fViewer= viewer;
fManager= manager;
fManager.setLinkedPositionListener(this);
fFrameColor= viewer.getTextWidget().getDisplay().getSystemColor(SWT.COLOR_RED);
}
/**
* Sets the final position of the caret when the linked mode is exited
* successfully by leaving the last linked position using TAB.
*/
public void setFinalCaretOffset(int offset) {
fFinalCaretOffset= offset;
}
/**
* Sets a <code>CancelListener</code> which is notified if the linked mode
* is exited unsuccessfully by hitting ESC.
*/
public void setCancelListener(ExitListener listener) {
fExitListener= listener;
}
/*
* @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, int)
*/
public void setCurrentPosition(Position position, int caretOffset) {
if (!fFramePosition.equals(position)) {
redrawRegion();
fFramePosition= position;
}
fCaretOffset= caretOffset;
}
/**
* Enters the linked mode. The linked mode can be left by calling
* <code>exit</code>.
*
* @see exit(boolean)
*/
public void enter() {
// track final caret
IDocument document= fViewer.getDocument();
document.addPositionCategory(CARET_POSITION);
document.addPositionUpdater(fgUpdater);
try {
if (fFinalCaretOffset != -1)
document.addPosition(CARET_POSITION, new Position(fFinalCaretOffset));
} catch (BadLocationException e) {
openErrorDialog(fViewer.getTextWidget().getShell(), e);
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
fViewer.addTextInputListener(this);
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
extension.prependVerifyKeyListener(this);
StyledText text= fViewer.getTextWidget();
text.addVerifyListener(this);
text.addModifyListener(this);
text.addPaintListener(this);
text.showSelection();
fFramePosition= fManager.getFirstPosition();
if (fFramePosition == null)
leave(UNINSTALL | COMMIT | UPDATE_CARET);
}
/**
* @see LinkedPositionManager.LinkedPositionListener#exit(boolean)
*/
public void exit(boolean success) {
// no UNINSTALL since manager has already uninstalled itself
leave((success ? COMMIT : 0) | UPDATE_CARET);
}
/**
* Returns the cursor selection, after having entered the linked mode.
* <code>enter()</code> must be called prior to a call to this method.
*/
public IRegion getSelectedRegion() {
if (fFramePosition == null)
return new Region(fFinalCaretOffset, 0);
else
return new Region(fFramePosition.getOffset(), fFramePosition.getLength());
}
private void leave(int flags) {
if ((flags & UNINSTALL) != 0)
fManager.uninstall((flags & COMMIT) != 0);
StyledText text= fViewer.getTextWidget();
text.removePaintListener(this);
text.removeModifyListener(this);
text.removeVerifyListener(this);
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
extension.removeVerifyKeyListener(this);
fViewer.removeTextInputListener(this);
try {
IRegion region= fViewer.getVisibleRegion();
IDocument document= fViewer.getDocument();
if (((flags & COMMIT) != 0) &&
((flags & DOCUMENT_CHANGED) == 0) &&
((flags & UPDATE_CARET) != 0))
{
Position[] positions= document.getPositions(CARET_POSITION);
if ((positions != null) && (positions.length != 0)) {
int offset= positions[0].getOffset() - region.getOffset();
if ((offset >= 0) && (offset <= region.getLength()))
text.setSelection(offset, offset);
}
}
document.removePositionUpdater(fgUpdater);
document.removePositionCategory(CARET_POSITION);
if (fExitListener != null)
fExitListener.exit(
((flags & COMMIT) != 0) ||
((flags & DOCUMENT_CHANGED) != 0));
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
if ((flags & DOCUMENT_CHANGED) == 0)
text.redraw();
}
private void next() {
redrawRegion();
fFramePosition= fManager.getNextPosition(fFramePosition.getOffset());
if (fFramePosition == null) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
} else {
selectRegion();
redrawRegion();
}
}
private void previous() {
redrawRegion();
Position position= fManager.getPreviousPosition(fFramePosition.getOffset());
if (position == null) {
fViewer.getTextWidget().getDisplay().beep();
} else {
fFramePosition= position;
selectRegion();
redrawRegion();
}
}
/*
* @see VerifyKeyListener#verifyKey(VerifyEvent)
*/
public void verifyKey(VerifyEvent event) {
switch (event.character) {
// [SHIFT-]TAB = hop between edit boxes
case 0x09:
{
Point selection= fViewer.getTextWidget().getSelection();
IRegion region= fViewer.getVisibleRegion();
int offset= selection.x + region.getOffset();
int length= selection.y - selection.x;
// if tab was treated as a document change, would it exceed variable range?
if (!LinkedPositionManager.includes(fFramePosition, offset, length)) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
return;
}
}
if (event.stateMask == SWT.SHIFT)
previous();
else
next();
event.doit= false;
break;
// ENTER
case 0x0D:
leave(UNINSTALL | COMMIT | UPDATE_CARET);
event.doit= false;
break;
// ESC
case 0x1B:
leave(UNINSTALL | COMMIT);
event.doit= false;
break;
}
}
/*
* @see VerifyListener#verifyText(VerifyEvent)
*/
public void verifyText(VerifyEvent event) {
if (!event.doit)
return;
IRegion region= fViewer.getVisibleRegion();
int offset= event.start + region.getOffset();
int length= event.end - event.start;
// allow changes only within linked positions when coming through UI
if (!fManager.anyPositionIncludes(offset, length))
leave(UNINSTALL | COMMIT);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fFramePosition == null)
return;
IRegion region= fViewer.getVisibleRegion();
// #6824
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() - region.getOffset();
int length= fFramePosition.getLength();
StyledText text= fViewer.getTextWidget();
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
gc.setForeground(fFrameColor);
gc.drawLine(x1, y, x2, y);
}
private static Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private static Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
private void redrawRegion() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() - region.getOffset();
int length= fFramePosition.getLength();
fViewer.getTextWidget().redrawRange(offset, length, true);
}
private void selectRegion() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int start= fFramePosition.getOffset() - region.getOffset();
int end= fFramePosition.getLength() + start;
fViewer.getTextWidget().setSelection(start, end);
}
private void updateCaret() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() + fCaretOffset - region.getOffset();
if ((offset >= 0) && (offset <= region.getLength()))
fViewer.getTextWidget().setCaretOffset(offset);
}
/*
* @see ModifyListener#modifyText(ModifyEvent)
*/
public void modifyText(ModifyEvent e) {
// reposition caret after StyledText
redrawRegion();
updateCaret();
}
private static void openErrorDialog(Shell shell, Exception e) {
MessageDialog.openError(shell, LinkedPositionMessages.getString("LinkedPositionUI.error.title"), e.getMessage()); //$NON-NLS-1$
}
/*
* @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
// 5326: leave linked mode on document change
int flags= UNINSTALL | COMMIT | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED);
leave(flags);
}
/*
* @see ITextInputListener#inputDocumentChanged(IDocument, IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
}
private static boolean includes(IRegion region, Position position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
}
|
12,585 |
Bug 12585 Packages view should not provide file and resource transfer if Java element below CU is selected
| null |
resolved fixed
|
ef87943
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-17T15:03:24Z | 2002-04-02T09:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dnd/DelegatingDragAdapter.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.dnd;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.jface.util.Assert;
/**
* A delegating drag adapter negotiates between a set of <code>TransferDragSourceListener</code>s
* On <code>dragStart</code> the adapter determines the listener to be used for any further
* <code>drag*</code> callback.
*/
public class DelegatingDragAdapter implements DragSourceListener {
private TransferDragSourceListener[] fPossibleListeners;
private List fActiveListeners;
private TransferDragSourceListener fFinishListener;
public DelegatingDragAdapter(TransferDragSourceListener[] listeners) {
Assert.isNotNull(listeners);
fPossibleListeners= listeners;
}
/* non Java-doc
* @see DragSourceListener
*/
public void dragStart(DragSourceEvent event) {
fFinishListener= null;
boolean saveDoit= event.doit;
Object saveData= event.data;
boolean doIt= false;
List transfers= new ArrayList(fPossibleListeners.length);
fActiveListeners= new ArrayList(fPossibleListeners.length);
for (int i= 0; i < fPossibleListeners.length; i++) {
TransferDragSourceListener listener= fPossibleListeners[i];
event.doit= saveDoit;
listener.dragStart(event);
if (event.doit) {
transfers.add(listener.getTransfer());
fActiveListeners.add(listener);
}
doIt= doIt || event.doit;
}
if (doIt) {
((DragSource)event.widget).setTransfer((Transfer[])transfers.toArray(new Transfer[transfers.size()]));
}
event.data= saveData;
event.doit= doIt;
}
/* non Java-doc
* @see DragSourceListener
*/
public void dragSetData(DragSourceEvent event) {
fFinishListener= getListener(event.dataType);
if (fFinishListener != null)
fFinishListener.dragSetData(event);
}
/* non Java-doc
* @see DragSourceListener
*/
public void dragFinished(DragSourceEvent event) {
if (fFinishListener != null) {
fFinishListener.dragFinished(event);
} else {
// If the user presses Escape then we get a dragFinished without
// getting a dragSetDate before.
fFinishListener= getListener(event.dataType);
if (fFinishListener != null)
fFinishListener.dragFinished(event);
}
}
private TransferDragSourceListener getListener(TransferData type) {
if (type == null)
return null;
for (Iterator iter= fActiveListeners.iterator(); iter.hasNext();) {
TransferDragSourceListener listener= (TransferDragSourceListener)iter.next();
if (listener.getTransfer().isSupportedType(type)) {
return listener;
}
}
return null;
}
}
|
12,585 |
Bug 12585 Packages view should not provide file and resource transfer if Java element below CU is selected
| null |
resolved fixed
|
ef87943
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-17T15:03:24Z | 2002-04-02T09:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.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 implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IPath;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ResourceWorkingSetFilter;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.ui.part.ResourceTransfer;
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.IJavaModel;
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.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
/**
* The ViewPart for the ProjectExplorer. It listens to part activation events.
* When selection linking with the editor is enabled the view selection tracks
* the active editor page. Similarly when a resource is selected in the packages
* view the corresponding editor is activated.
*/
public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IPackagesViewPart, IPropertyChangeListener {
public final static String VIEW_ID= JavaUI.ID_PACKAGES;
// Persistance tags.
static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$
static final String TAG_ELEMENT= "element"; //$NON-NLS-1$
static final String TAG_PATH= "path"; //$NON-NLS-1$
static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$
static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$
static final String TAG_FILTERS = "filters"; //$NON-NLS-1$
static final String TAG_FILTER = "filter"; //$NON-NLS-1$
static final String TAG_SHOWLIBRARIES = "showLibraries"; //$NON-NLS-1$
static final String TAG_SHOWBINARIES = "showBinaries"; //$NON-NLS-1$
private JavaElementPatternFilter fPatternFilter= new JavaElementPatternFilter();
private LibraryFilter fLibraryFilter= new LibraryFilter();
private ResourceWorkingSetFilter fWorkingSetFilter;
private PackageExplorerActionGroup fActionSet;
private ProblemTreeViewer fViewer;
private StandardJavaUILabelProvider fJavaElementLabelProvider;
private Menu fContextMenu;
private IMemento fMemento;
private ISelectionChangedListener fSelectionListener;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
private ITreeViewerListener fExpansionListener= new ITreeViewerListener() {
public void treeCollapsed(TreeExpansionEvent event) {
}
public void treeExpanded(TreeExpansionEvent event) {
Object element= event.getElement();
if (element instanceof ICompilationUnit ||
element instanceof IClassFile)
expandMainType(element);
}
};
public PackageExplorerPart() {
}
/* (non-Javadoc)
* Method declared on IViewPart.
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/**
* Initializes the default preferences
*/
public static void initDefaults(IPreferenceStore store) {
store.setDefault(TAG_SHOWLIBRARIES, true);
store.setDefault(TAG_SHOWBINARIES, true);
}
/**
* Returns the package explorer part of the active perspective. If
* there isn't any package explorer part <code>null</code> is returned.
*/
public static PackageExplorerPart getFromActivePerspective() {
IViewPart view= JavaPlugin.getActivePage().findView(VIEW_ID);
if (view instanceof PackageExplorerPart)
return (PackageExplorerPart)view;
return null;
}
/**
* Makes the package explorer part visible in the active perspective. If there
* isn't a package explorer part registered <code>null</code> is returned.
* Otherwise the opened view part is returned.
*/
public static PackageExplorerPart openInActivePerspective() {
try {
return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID);
} catch(PartInitException pe) {
return null;
}
}
public void dispose() {
if (fViewer != null)
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fViewer);
if (fContextMenu != null && !fContextMenu.isDisposed())
fContextMenu.dispose();
getSite().getPage().removePartListener(fPartListener);
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
if (fViewer != null)
fViewer.removeTreeListener(fExpansionListener);
super.dispose();
}
/**
* Implementation of IWorkbenchPart.createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fViewer= new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
boolean showCUChildren= JavaBasePreferencePage.showCompilationUnitChildren();
fViewer.setContentProvider(new JavaElementContentProvider(showCUChildren, false));
JavaPlugin.getDefault().getProblemMarkerManager().addListener(fViewer);
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fJavaElementLabelProvider=
new StandardJavaUILabelProvider(
StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED,
StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
StandardJavaUILabelProvider.getAdornmentProviders(true, null)
);
fViewer.setLabelProvider(new DecoratingLabelProvider(
fJavaElementLabelProvider, PlatformUI.getWorkbench().getDecoratorManager())
);
fViewer.setSorter(new JavaElementSorter());
fViewer.addFilter(new EmptyInnerPackageFilter());
fViewer.setUseHashlookup(true);
fViewer.addFilter(fPatternFilter);
fViewer.addFilter(fLibraryFilter);
addWorkingSetChangeSupport();
IWorkingSet workingSet= getSite().getPage().getWorkingSet();
if (workingSet != null) {
fWorkingSetFilter= new ResourceWorkingSetFilter();
fWorkingSetFilter.setWorkingSet(workingSet);
fViewer.addFilter(fWorkingSetFilter);
}
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getTree());
fViewer.getTree().setMenu(fContextMenu);
// Register viewer with site. This must be done before making the actions.
IWorkbenchPartSite site= getSite();
site.registerContextMenu(menuMgr, fViewer);
site.setSelectionProvider(fViewer);
site.getPage().addPartListener(fPartListener);
if(fMemento != null)
restoreFilters();
else
initFilterFromPreferences();
makeActions(); // call before registering for selection changes
// Set input after filter and sorter has been set. This avoids resorting
// and refiltering.
fViewer.setInput(findInputElement());
initDragAndDrop();
initKeyListener();
updateTitle();
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
handleSelectionChanged(event);
}
};
fViewer.addSelectionChangedListener(fSelectionListener);
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
handleDoubleClick(event);
}
});
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
fViewer.addTreeListener(fExpansionListener);
if (fMemento != null)
restoreState(fMemento);
fMemento= null;
// Set help for the view
JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW);
fillActionBars();
}
private void fillActionBars() {
IActionBars actionBars= getViewSite().getActionBars();
fActionSet.fillActionBars(actionBars);
}
private Object findInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IWorkspace) {
return JavaCore.create(((IWorkspace)input).getRoot());
} else if (input instanceof IContainer) {
return JavaCore.create((IContainer)input);
}
//1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
// we can't handle the input
// fall back to show the workspace
return JavaCore.create(JavaPlugin.getWorkspace().getRoot());
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key.equals(ISelectionProvider.class))
return fViewer;
return super.getAdapter(key);
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
result= JavaElementLabels.getTextLabel(element, StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
IWorkingSet ws= fWorkingSetFilter.getWorkingSet();
if (ws == null)
return result;
String wsstr= PackagesMessages.getFormattedString("PackageExplorer.toolTip", new String[] { ws.getName() }); //$NON-NLS-1$
if (result.length() == 0)
return wsstr;
return PackagesMessages.getFormattedString("PackageExplorer.toolTip2", new String[] { result, ws.getName() }); //$NON-NLS-1$
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
/**
* @see IWorkbenchPart#setFocus()
*/
public void setFocus() {
fViewer.getTree().setFocus();
}
/**
* Returns the shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
private Shell getShell() {
return fViewer.getTree().getShell();
}
/**
* Returns the selection provider.
*/
private ISelectionProvider getSelectionProvider() {
return fViewer;
}
/**
* Returns the current selection.
*/
private ISelection getSelection() {
return fViewer.getSelection();
}
//---- Action handling ----------------------------------------------------------
/**
* Called when the context menu is about to open. Override
* to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
fActionSet.setContext(new ActionContext(getSelection()));
fActionSet.fillContextMenu(menu);
}
private void makeActions() {
fActionSet= new PackageExplorerActionGroup(this);
}
private boolean isSelectionOfType(ISelection s, Class clazz, boolean considerUnderlyingResource) {
if (! (s instanceof IStructuredSelection) || s.isEmpty())
return false;
IStructuredSelection selection= (IStructuredSelection)s;
Iterator iter= selection.iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (clazz.isInstance(o))
return true;
if (considerUnderlyingResource) {
if (! (o instanceof IJavaElement))
return false;
IJavaElement element= (IJavaElement)o;
Object resource= element.getAdapter(IResource.class);
if (! clazz.isInstance(resource))
return false;
}
}
return true;
}
//---- Event handling ----------------------------------------------------------
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE;
final LocalSelectionTransfer lt= LocalSelectionTransfer.getInstance();
Transfer[] transfers= new Transfer[] {
lt,
ResourceTransfer.getInstance(),
FileTransfer.getInstance()};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer),
new FileTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
Control control= fViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(fViewer),
new FileTransferDragAdapter(fViewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
/**
* Handles double clicks in viewer.
* Opens editor if file double-clicked.
*/
private void handleDoubleClick(DoubleClickEvent event) {
fActionSet.handleDoubleClick(event);
}
/**
* Handles selection changed in viewer.
* Updates global actions.
* Links to editor (if option enabled)
*/
private void handleSelectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection= (IStructuredSelection) event.getSelection();
fActionSet.handleSelectionChanged(event);
linkToEditor(selection);
}
public void selectReveal(ISelection selection) {
ISelection javaSelection= convertSelection(selection);
fViewer.setSelection(javaSelection, true);
}
private ISelection convertSelection(ISelection s) {
List converted= new ArrayList();
if (s instanceof StructuredSelection) {
Object[] elements= ((StructuredSelection)s).toArray();
for (int i= 0; i < elements.length; i++) {
Object e= elements[i];
if (e instanceof IJavaElement)
converted.add(e);
else if (e instanceof IResource) {
IJavaElement element= JavaCore.create((IResource)e);
if (element != null)
converted.add(element);
else
converted.add(e);
}
}
}
return new StructuredSelection(converted.toArray());
}
public void selectAndReveal(Object element) {
selectReveal(new StructuredSelection(element));
}
/**
* Returns whether the preference to link selection to active editor is enabled.
*/
boolean isLinkingEnabled() {
return JavaBasePreferencePage.linkPackageSelectionToEditor();
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
//if (!isLinkingEnabled())
// return;
Object obj= selection.getFirstElement();
Object element= null;
if (selection.size() == 1) {
if (obj instanceof IJavaElement) {
IJavaElement cu= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.COMPILATION_UNIT);
if (cu != null)
element= getResourceFor(cu);
if (element == null)
element= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.CLASS_FILE);
}
else if (obj instanceof IFile)
element= obj;
if (element == null)
return;
IWorkbenchPage page= getSite().getPage();
IEditorPart editorArray[]= page.getEditors();
for (int i= 0; i < editorArray.length; ++i) {
IEditorPart editor= editorArray[i];
Object input= getElementOfInput(editor.getEditorInput());
if (input != null && input.equals(element)) {
page.bringToTop(editor);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(editor, (IJavaElement) obj);
return;
}
}
}
}
private IResource getResourceFor(Object element) {
if (element instanceof IJavaElement) {
if (element instanceof IWorkingCopy) {
IWorkingCopy wc= (IWorkingCopy)element;
IJavaElement original= wc.getOriginalElement();
if (original != null)
element= original;
}
try {
element= ((IJavaElement)element).getUnderlyingResource();
} catch (JavaModelException e) {
return null;
}
}
if (!(element instanceof IResource) || ((IResource)element).isPhantom()) {
return null;
}
return (IResource)element;
}
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
saveExpansionState(memento);
saveSelectionState(memento);
saveScrollState(memento, fViewer.getTree());
savePatternFilterState(memento);
saveFilterState(memento);
fActionSet.saveState(memento);
}
protected void saveFilterState(IMemento memento) {
boolean showLibraries= getLibraryFilter().getShowLibraries();
String show= "true"; //$NON-NLS-1$
if (!showLibraries)
show= "false"; //$NON-NLS-1$
memento.putString(TAG_SHOWLIBRARIES, show);
}
protected void savePatternFilterState(IMemento memento) {
String filters[] = getPatternFilter().getPatterns();
if(filters.length > 0) {
IMemento filtersMem = memento.createChild(TAG_FILTERS);
for (int i = 0; i < filters.length; i++){
IMemento child = filtersMem.createChild(TAG_FILTER);
child.putString(TAG_ELEMENT,filters[i]);
}
}
}
protected void saveScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position));
//save horizontal position
bar= tree.getHorizontalBar();
position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position));
}
protected void saveSelectionState(IMemento memento) {
Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
if (elements.length > 0) {
IMemento selectionMem= memento.createChild(TAG_SELECTION);
for (int i= 0; i < elements.length; i++) {
IMemento elementMem= selectionMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= elements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier());
}
}
}
protected void saveExpansionState(IMemento memento) {
Object expandedElements[]= fViewer.getExpandedElements();
if (expandedElements.length > 0) {
IMemento expandedMem= memento.createChild(TAG_EXPANDED);
for (int i= 0; i < expandedElements.length; i++) {
IMemento elementMem= expandedMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= expandedElements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier());
}
}
}
void restoreState(IMemento memento) {
restoreExpansionState(memento);
restoreSelectionState(memento);
restoreScrollState(memento, fViewer.getTree());
fActionSet.restoreState(memento);
}
protected void restoreScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_VERTICAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore, don't set scrollposition
}
}
bar= tree.getHorizontalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_HORIZONTAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore don't set scroll position
}
}
}
protected void restoreSelectionState(IMemento memento) {
IMemento childMem;
childMem= memento.getChild(TAG_SELECTION);
if (childMem != null) {
ArrayList list= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
list.add(element);
}
fViewer.setSelection(new StructuredSelection(list));
}
}
protected void restoreExpansionState(IMemento memento) {
IMemento childMem= memento.getChild(TAG_EXPANDED);
if (childMem != null) {
ArrayList elements= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
elements.add(element);
}
fViewer.setExpandedElements(elements.toArray());
}
}
/**
* Create the KeyListener for doing the refresh on the viewer.
*/
private void initKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
fActionSet.handleKeyEvent(event);
}
});
}
/**
* An editor has been activated. Set the selection in this Packages Viewer
* to be the editor's input, if linking is enabled.
*/
void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled())
return;
Object input= getElementOfInput(editor.getEditorInput());
Object element= null;
if (input instanceof IFile)
element= JavaCore.create((IFile)input);
if (element == null) // try a non Java resource
element= input;
if (element != null) {
// if the current selection is a child of the new
// selection then ignore it.
IStructuredSelection oldSelection= (IStructuredSelection)getSelection();
if (oldSelection.size() == 1) {
Object o= oldSelection.getFirstElement();
if (o instanceof IMember) {
IMember m= (IMember)o;
if (element.equals(m.getCompilationUnit()))
return;
if (element.equals(m.getClassFile()))
return;
}
}
ISelection newSelection= new StructuredSelection(element);
if (!fViewer.getSelection().equals(newSelection)) {
try {
fViewer.removeSelectionChangedListener(fSelectionListener);
fViewer.setSelection(newSelection);
} finally {
fViewer.addSelectionChangedListener(fSelectionListener);
}
}
}
}
/**
* A compilation unit or class was expanded, expand
* the main type.
*/
void expandMainType(Object element) {
try {
IType type= null;
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
IType[] types= cu.getTypes();
if (types.length > 0)
type= types[0];
}
else if (element instanceof IClassFile) {
IClassFile cf= (IClassFile)element;
type= cf.getType();
}
if (type != null) {
final IType type2= type;
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.expandToLevel(type2, 1);
}
});
}
}
} catch(JavaModelException e) {
// no reveal
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
/**
* Returns the Viewer.
*/
TreeViewer getViewer() {
return fViewer;
}
/**
* Returns the pattern filter for this view.
* @return the pattern filter
*/
JavaElementPatternFilter getPatternFilter() {
return fPatternFilter;
}
/**
* Returns the library filter for this view.
* @return the library filter
*/
LibraryFilter getLibraryFilter() {
return fLibraryFilter;
}
void restoreFilters() {
IMemento filtersMem= fMemento.getChild(TAG_FILTERS);
if(filtersMem != null) {
IMemento children[]= filtersMem.getChildren(TAG_FILTER);
String filters[]= new String[children.length];
for (int i = 0; i < children.length; i++) {
filters[i]= children[i].getString(TAG_ELEMENT);
}
getPatternFilter().setPatterns(filters);
} else {
getPatternFilter().setPatterns(new String[0]);
}
//restore library
String show= fMemento.getString(TAG_SHOWLIBRARIES);
if (show != null)
getLibraryFilter().setShowLibraries(show.equals("true")); //$NON-NLS-1$
else
initLibraryFilterFromPreferences();
}
void initFilterFromPreferences() {
initLibraryFilterFromPreferences();
}
void initLibraryFilterFromPreferences() {
JavaPlugin plugin= JavaPlugin.getDefault();
boolean show= plugin.getPreferenceStore().getBoolean(TAG_SHOWLIBRARIES);
getLibraryFilter().setShowLibraries(show);
}
boolean isExpandable(Object element) {
if (fViewer == null)
return false;
return fViewer.isExpandable(element);
}
/**
* Updates the title text and title tool tip.
* Called whenever the input of the viewer changes.
*/
void updateTitle() {
Object input= fViewer.getInput();
String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
if (input == null
|| (input instanceof IJavaModel)) {
setTitle(viewName);
setTitleToolTip(""); //$NON-NLS-1$
} else {
String inputText= JavaElementLabels.getTextLabel(input, StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS);
String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$
setTitle(title);
setTitleToolTip(getToolTipText(input));
}
}
/**
* Sets the decorator for the package explorer.
*
* @param decorator a label decorator or <code>null</code> for no decorations.
* @deprecated To be removed
*/
public void setLabelDecorator(ILabelDecorator decorator) {
if (decorator == null)
fViewer.setLabelProvider(fJavaElementLabelProvider);
else
fViewer.setLabelProvider(new DecoratingLabelProvider(fJavaElementLabelProvider, decorator));
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
boolean refreshViewer= false;
if (event.getProperty() == JavaBasePreferencePage.SHOW_CU_CHILDREN) {
IActionBars actionBars= getViewSite().getActionBars();
fActionSet.fillToolBar(actionBars.getToolBarManager());
actionBars.updateActionBars();
boolean showCUChildren= JavaBasePreferencePage.showCompilationUnitChildren();
((JavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren);
refreshViewer= true;
}
if (refreshViewer)
fViewer.refresh();
}
private IPropertyChangeListener addWorkingSetChangeSupport() {
final IPropertyChangeListener propertyChangeListener= createWorkingSetChangeListener();
final IWorkbenchPage page= getSite().getPage();
fWorkingSetFilter= new ResourceWorkingSetFilter();
fViewer.addFilter(fWorkingSetFilter);
// Register listener on working set
if (page.getWorkingSet() != null)
page.getWorkingSet().addPropertyChangeListener(propertyChangeListener);
// Register listener on page
page.addPropertyChangeListener(propertyChangeListener);
// Register dispose listener which removes the page listener
fViewer.getControl().addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
if (page!= null)
page.removePropertyChangeListener(propertyChangeListener);
}
});
return propertyChangeListener;
}
private IPropertyChangeListener createWorkingSetChangeListener() {
return new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
String property= event.getProperty();
if (IWorkbenchPage.CHANGE_WORKING_SET_REPLACE.equals(property)) {
IWorkingSet newWorkingSet= (IWorkingSet) event.getNewValue();
if (fWorkingSetFilter.getWorkingSet() != null)
fWorkingSetFilter.getWorkingSet().removePropertyChangeListener(this);
fWorkingSetFilter.setWorkingSet(newWorkingSet);
if (newWorkingSet != null)
newWorkingSet.addPropertyChangeListener(this);
fViewer.getControl().setRedraw(false);
fViewer.refresh();
updateTitle();
fViewer.getControl().setRedraw(true);
}
else if (IWorkingSet.CHANGE_WORKING_SET_NAME_CHANGE.equals(property))
updateTitle();
else if (IWorkingSet.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property))
fViewer.refresh();
}
};
}
}
|
14,083 |
Bug 14083 Error exiting Window->Preferences Dialog
|
Just Installed the new Milestone 5 version of Eclipse and wanted to change some Preferences (I changed Java->Code Formatter->Line Splitting->Maximum line length to 100) and when I click on the OK button the following error occurs: "Problems while setting classpath variable. See log for details. Assertion failed; Variable path cannot be null.." Under classpath variables I have 4 variabled (I added none of them, but maybe a project I imported from CVS did?): ECLIPSE_HOME JRE_LIB JRE_SRC JRE_SRCROOT If I want to edit the ECLIPSE_HOME entry, the following error occurs: "An internal error has occured. See error log for more details. Exit workspace?" Under details I see the following exception stack: "java.lang.NullPointerException at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableCreationDialog.<init> (VariableCreationDialog.java:92) at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock.editEntries (VariableBlock.java:231) at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock.access$0 (VariableBlock.java:228) at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock$VariablesAdapter.cu stomButtonPressed(VariableBlock.java:175) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField.buttonPressed (ListDialogField.java:149) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField.doButtonSelecte d(ListDialogField.java:356) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField.access$1 (ListDialogField.java:352) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField$1.widgetSelecte d(ListDialogField.java:319) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.internal.OpenPreferencesAction.run (OpenPreferencesAction.java:47) at org.eclipse.jface.action.Action.runWithEvent(Action.java:590) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:836) at org.eclipse.ui.internal.Workbench.run(Workbench.java:819) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:190) at org.eclipse.core.launcher.Main.run(Main.java:549) at org.eclipse.core.launcher.Main.main(Main.java:390)" If I remove the ECLIPSE_HOME variable, no error occurs after clicking the OK button. BTW, the tool get's nicer and nicer with every release...if you keep going on like this, nobody will buy WebSphere Application Developer :-) Mirko
|
resolved fixed
|
ca84d62
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T12:44:26Z | 2002-04-18T08:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/CPVariableElement.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import org.eclipse.core.runtime.IPath;
public class CPVariableElement {
private String fName;
private IPath fPath;
private boolean fIsReserved;
public CPVariableElement(String name, IPath path, boolean reserved) {
fName= name;
fPath= path;
fIsReserved= reserved;
}
/**
* Gets the path
* @return Returns a IPath
*/
public IPath getPath() {
return fPath;
}
/**
* Sets the path
* @param path The path to set
*/
public void setPath(IPath path) {
fPath= path;
}
/**
* Gets the name
* @return Returns a String
*/
public String getName() {
return fName;
}
/**
* Sets the name
* @param name The name to set
*/
public void setName(String name) {
fName= name;
}
/*
* @see Object#equals()
*/
public boolean equals(Object other) {
if (other.getClass().equals(getClass())) {
CPVariableElement elem= (CPVariableElement)other;
return fName.equals(elem.fName);
}
return false;
}
/*
* @see Object#hashCode()
*/
public int hashCode() {
return fName.hashCode();
}
/**
* Returns true if variable is reserved
* @return Returns a boolean
*/
public boolean isReserved() {
return fIsReserved;
}
/**
* Sets the isReserved
* @param isReserved The state to set
*/
public void setReserved(boolean isReserved) {
fIsReserved= isReserved;
}
}
|
14,083 |
Bug 14083 Error exiting Window->Preferences Dialog
|
Just Installed the new Milestone 5 version of Eclipse and wanted to change some Preferences (I changed Java->Code Formatter->Line Splitting->Maximum line length to 100) and when I click on the OK button the following error occurs: "Problems while setting classpath variable. See log for details. Assertion failed; Variable path cannot be null.." Under classpath variables I have 4 variabled (I added none of them, but maybe a project I imported from CVS did?): ECLIPSE_HOME JRE_LIB JRE_SRC JRE_SRCROOT If I want to edit the ECLIPSE_HOME entry, the following error occurs: "An internal error has occured. See error log for more details. Exit workspace?" Under details I see the following exception stack: "java.lang.NullPointerException at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableCreationDialog.<init> (VariableCreationDialog.java:92) at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock.editEntries (VariableBlock.java:231) at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock.access$0 (VariableBlock.java:228) at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock$VariablesAdapter.cu stomButtonPressed(VariableBlock.java:175) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField.buttonPressed (ListDialogField.java:149) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField.doButtonSelecte d(ListDialogField.java:356) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField.access$1 (ListDialogField.java:352) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField$1.widgetSelecte d(ListDialogField.java:319) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.internal.OpenPreferencesAction.run (OpenPreferencesAction.java:47) at org.eclipse.jface.action.Action.runWithEvent(Action.java:590) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:836) at org.eclipse.ui.internal.Workbench.run(Workbench.java:819) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:190) at org.eclipse.core.launcher.Main.run(Main.java:549) at org.eclipse.core.launcher.Main.main(Main.java:390)" If I remove the ECLIPSE_HOME variable, no error occurs after clicking the OK button. BTW, the tool get's nicer and nicer with every release...if you keep going on like this, nobody will buy WebSphere Application Developer :-) Mirko
|
resolved fixed
|
ca84d62
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T12:44:26Z | 2002-04-18T08:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariableBlock.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
public class VariableBlock {
private ListDialogField fVariablesList;
private Control fControl;
/**
* Constructor for VariableBlock
*/
public VariableBlock(boolean inPreferencePage, String initSelection) {
String[] buttonLabels= new String[] {
/* 0 */ NewWizardMessages.getString("VariableBlock.vars.add.button"), //$NON-NLS-1$
/* 1 */ NewWizardMessages.getString("VariableBlock.vars.edit.button"), //$NON-NLS-1$
/* 2 */ null,
/* 3 */ NewWizardMessages.getString("VariableBlock.vars.remove.button") //$NON-NLS-1$
};
VariablesAdapter adapter= new VariablesAdapter();
CPVariableElementLabelProvider labelProvider= new CPVariableElementLabelProvider(!inPreferencePage);
fVariablesList= new ListDialogField(adapter, buttonLabels, labelProvider);
fVariablesList.setDialogFieldListener(adapter);
fVariablesList.setLabelText(NewWizardMessages.getString("VariableBlock.vars.label")); //$NON-NLS-1$
fVariablesList.setRemoveButtonIndex(3);
fVariablesList.enableButton(1, false);
fVariablesList.setViewerSorter(new ViewerSorter() {
public int compare(Viewer viewer, Object e1, Object e2) {
if (e1 instanceof CPVariableElement && e2 instanceof CPVariableElement) {
return ((CPVariableElement)e1).getName().compareTo(((CPVariableElement)e2).getName());
}
return super.compare(viewer, e1, e2);
}
});
CPVariableElement initSelectedElement= null;
String[] reservedName= getReservedVariableNames();
ArrayList reserved= new ArrayList(reservedName.length);
addAll(reservedName, reserved);
String[] entries= JavaCore.getClasspathVariableNames();
ArrayList elements= new ArrayList(entries.length);
for (int i= 0; i < entries.length; i++) {
String name= entries[i];
CPVariableElement elem;
IPath entryPath= JavaCore.getClasspathVariable(name);
elem= new CPVariableElement(name, entryPath, reserved.contains(name));
elements.add(elem);
if (name.equals(initSelection)) {
initSelectedElement= elem;
}
}
fVariablesList.setElements(elements);
if (initSelectedElement != null) {
ISelection sel= new StructuredSelection(initSelectedElement);
fVariablesList.selectElements(sel);
} else {
fVariablesList.selectFirstElement();
}
}
private String[] getReservedVariableNames() {
return new String[] {
JavaRuntime.JRELIB_VARIABLE,
JavaRuntime.JRESRC_VARIABLE,
JavaRuntime.JRESRCROOT_VARIABLE,
};
}
public Control createContents(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fVariablesList }, true, 0, 0);
LayoutUtil.setHorizontalGrabbing(fVariablesList.getListControl(null));
fControl= composite;
return composite;
}
public void addDoubleClickListener(IDoubleClickListener listener) {
fVariablesList.getTableViewer().addDoubleClickListener(listener);
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
fVariablesList.getTableViewer().addSelectionChangedListener(listener);
}
private Shell getShell() {
if (fControl != null) {
return fControl.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private class VariablesAdapter implements IDialogFieldListener, IListAdapter {
// -------- IListAdapter --------
public void customButtonPressed(DialogField field, int index) {
switch (index) {
case 0: /* add */
editEntries(null);
break;
case 1: /* edit */
List selected= fVariablesList.getSelectedElements();
editEntries((CPVariableElement)selected.get(0));
break;
}
}
public void selectionChanged(DialogField field) {
doSelectionChanged(field);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
}
}
private boolean containsReserved(List selected) {
for (int i= selected.size()-1; i >= 0; i--) {
if (((CPVariableElement)selected.get(i)).isReserved()) {
return true;
}
}
return false;
}
private static void addAll(Object[] objs, Collection dest) {
for (int i= 0; i < objs.length; i++) {
dest.add(objs[i]);
}
}
private void doSelectionChanged(DialogField field) {
List selected= fVariablesList.getSelectedElements();
boolean isSingleSelected= selected.size() == 1;
boolean containsReserved= containsReserved(selected);
// edit
fVariablesList.enableButton(1, isSingleSelected && !containsReserved);
// remove button
fVariablesList.enableButton(3, !containsReserved);
}
private void editEntries(CPVariableElement entry) {
List existingEntries= fVariablesList.getElements();
VariableCreationDialog dialog= new VariableCreationDialog(getShell(), entry, existingEntries);
if (dialog.open() != dialog.OK) {
return;
}
CPVariableElement newEntry= dialog.getClasspathElement();
if (entry == null) {
fVariablesList.addElement(newEntry);
entry= newEntry;
} else {
entry.setName(newEntry.getName());
entry.setPath(newEntry.getPath());
fVariablesList.refresh();
}
fVariablesList.selectElements(new StructuredSelection(entry));
}
public List getSelectedElements() {
return fVariablesList.getSelectedElements();
}
public void performDefaults() {
fVariablesList.removeAllElements();
String[] reservedName= getReservedVariableNames();
for (int i= 0; i < reservedName.length; i++) {
CPVariableElement elem= new CPVariableElement(reservedName[i], null, true);
elem.setReserved(true);
fVariablesList.addElement(elem);
}
}
public boolean performOk() {
List toRemove= new ArrayList();
toRemove.addAll(Arrays.asList(JavaCore.getClasspathVariableNames()));
// remove all unchanged
List elements= fVariablesList.getElements();
for (int i= elements.size()-1; i >= 0; i--) {
CPVariableElement curr= (CPVariableElement) elements.get(i);
if (curr.isReserved()) {
elements.remove(curr);
} else {
IPath path= curr.getPath();
IPath prevPath= JavaCore.getClasspathVariable(curr.getName());
if (prevPath != null && prevPath.equals(path)) {
elements.remove(curr);
}
}
toRemove.remove(curr.getName());
}
int steps= elements.size() + toRemove.size();
if (steps > 0) {
IRunnableWithProgress runnable= new VariableBlockRunnable(toRemove, elements);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, runnable);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), NewWizardMessages.getString("VariableBlock.operation_errror.title"), NewWizardMessages.getString("VariableBlock.operation_errror.message")); //$NON-NLS-1$ //$NON-NLS-2$
return false;
} catch (InterruptedException e) {
return true;
}
}
return true;
}
private class VariableBlockRunnable implements IRunnableWithProgress {
private List fToRemove;
private List fToChange;
public VariableBlockRunnable(List toRemove, List toChange) {
fToRemove= toRemove;
fToChange= toChange;
}
/*
* @see IRunnableWithProgress#run(IProgressMonitor)
*/
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
int steps= fToChange.size() + fToRemove.size();
monitor.beginTask(NewWizardMessages.getString("VariableBlock.operation_desc"), steps); //$NON-NLS-1$
try {
for (int i= 0; i < fToChange.size(); i++) {
CPVariableElement curr= (CPVariableElement) fToChange.get(i);
SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1);
JavaCore.setClasspathVariable(curr.getName(), curr.getPath(), subMonitor);
if (monitor.isCanceled()) {
return;
}
}
for (int i= 0; i < fToRemove.size(); i++) {
SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1);
JavaCore.removeClasspathVariable((String) fToRemove.get(i), subMonitor);
if (monitor.isCanceled()) {
return;
}
}
} catch (JavaModelException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
}
}
|
14,083 |
Bug 14083 Error exiting Window->Preferences Dialog
|
Just Installed the new Milestone 5 version of Eclipse and wanted to change some Preferences (I changed Java->Code Formatter->Line Splitting->Maximum line length to 100) and when I click on the OK button the following error occurs: "Problems while setting classpath variable. See log for details. Assertion failed; Variable path cannot be null.." Under classpath variables I have 4 variabled (I added none of them, but maybe a project I imported from CVS did?): ECLIPSE_HOME JRE_LIB JRE_SRC JRE_SRCROOT If I want to edit the ECLIPSE_HOME entry, the following error occurs: "An internal error has occured. See error log for more details. Exit workspace?" Under details I see the following exception stack: "java.lang.NullPointerException at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableCreationDialog.<init> (VariableCreationDialog.java:92) at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock.editEntries (VariableBlock.java:231) at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock.access$0 (VariableBlock.java:228) at org.eclipse.jdt.internal.ui.wizards.buildpaths.VariableBlock$VariablesAdapter.cu stomButtonPressed(VariableBlock.java:175) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField.buttonPressed (ListDialogField.java:149) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField.doButtonSelecte d(ListDialogField.java:356) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField.access$1 (ListDialogField.java:352) at org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField$1.widgetSelecte d(ListDialogField.java:319) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.internal.OpenPreferencesAction.run (OpenPreferencesAction.java:47) at org.eclipse.jface.action.Action.runWithEvent(Action.java:590) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:836) at org.eclipse.ui.internal.Workbench.run(Workbench.java:819) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:190) at org.eclipse.core.launcher.Main.run(Main.java:549) at org.eclipse.core.launcher.Main.main(Main.java:390)" If I remove the ECLIPSE_HOME variable, no error occurs after clicking the OK button. BTW, the tool get's nicer and nicer with every release...if you keep going on like this, nobody will buy WebSphere Application Developer :-) Mirko
|
resolved fixed
|
ca84d62
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T12:44:26Z | 2002-04-18T08:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariableCreationDialog.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.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.JavaConventions;
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.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.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.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;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.swt.layout.GridLayout;
public class VariableCreationDialog extends StatusDialog {
private IDialogSettings fDialogSettings;
private StringDialogField fNameField;
private StatusInfo fNameStatus;
private StringButtonDialogField fPathField;
private StatusInfo fPathStatus;
private SelectionButtonDialogField fDirButton;
private CPVariableElement fElement;
private List fExistingNames;
public VariableCreationDialog(Shell parent, CPVariableElement element, List existingNames) {
super(parent);
if (element == null) {
setTitle(NewWizardMessages.getString("VariableCreationDialog.titlenew")); //$NON-NLS-1$
} else {
setTitle(NewWizardMessages.getString("VariableCreationDialog.titleedit")); //$NON-NLS-1$
}
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
fElement= element;
fNameStatus= new StatusInfo();
fPathStatus= new StatusInfo();
NewVariableAdapter adapter= new NewVariableAdapter();
fNameField= new StringDialogField();
fNameField.setDialogFieldListener(adapter);
fNameField.setLabelText(NewWizardMessages.getString("VariableCreationDialog.name.label")); //$NON-NLS-1$
fPathField= new StringButtonDialogField(adapter);
fPathField.setDialogFieldListener(adapter);
fPathField.setLabelText(NewWizardMessages.getString("VariableCreationDialog.path.label")); //$NON-NLS-1$
fPathField.setButtonLabel(NewWizardMessages.getString("VariableCreationDialog.path.file.button")); //$NON-NLS-1$
fDirButton= new SelectionButtonDialogField(SWT.PUSH);
fDirButton.setDialogFieldListener(adapter);
fDirButton.setLabelText(NewWizardMessages.getString("VariableCreationDialog.path.dir.button")); //$NON-NLS-1$
fExistingNames= existingNames;
if (element != null) {
fNameField.setText(element.getName());
fPathField.setText(element.getPath().toString());
fExistingNames.remove(element.getName());
} else {
fNameField.setText(""); //$NON-NLS-1$
fPathField.setText(""); //$NON-NLS-1$
}
}
/*
* @see Windows#configureShell
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.VARIABLE_CREATION_DIALOG);
}
public CPVariableElement getClasspathElement() {
return new CPVariableElement(fNameField.getText(), new Path(fPathField.getText()), false);
}
/*
* @see Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite)super.createDialogArea(parent);
PixelConverter converter= new PixelConverter(parent);
Composite inner= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.numColumns= 3;
inner.setLayout(layout);
int fieldWidthHint= converter.convertWidthInCharsToPixels(50);
fNameField.doFillIntoGrid(inner, 2);
LayoutUtil.setWidthHint(fNameField.getTextControl(null), fieldWidthHint);
LayoutUtil.setHorizontalGrabbing(fNameField.getTextControl(null));
DialogField.createEmptySpace(inner, 1);
fPathField.doFillIntoGrid(inner, 3);
LayoutUtil.setWidthHint(fPathField.getTextControl(null), fieldWidthHint);
DialogField.createEmptySpace(inner, 2);
fDirButton.doFillIntoGrid(inner, 1);
DialogField focusField= (fElement == null) ? fNameField : fPathField;
focusField.postSetFocusOnDialogField(parent.getDisplay());
return composite;
}
// -------- NewVariableAdapter --------
private class NewVariableAdapter implements IDialogFieldListener, IStringButtonAdapter {
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
doFieldUpdated(field);
}
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
doChangeControlPressed(field);
}
}
private void doChangeControlPressed(DialogField field) {
if (field == fPathField) {
IPath path= chooseExtJarFile();
if (path != null) {
fPathField.setText(path.toString());
}
}
}
private void doFieldUpdated(DialogField field) {
if (field == fNameField) {
fNameStatus= nameUpdated();
} else if (field == fPathField) {
fPathStatus= pathUpdated();
} else if (field == fDirButton) {
IPath path= chooseExtDirectory();
if (path != null) {
fPathField.setText(path.toString());
}
}
updateStatus(StatusUtil.getMoreSevere(fPathStatus, fNameStatus));
}
private StatusInfo nameUpdated() {
StatusInfo status= new StatusInfo();
String name= fNameField.getText();
if (name.length() == 0) {
status.setError(NewWizardMessages.getString("VariableCreationDialog.error.entername")); //$NON-NLS-1$
return status;
}
IStatus val= JavaConventions.validateIdentifier(name);
if (val.matches(IStatus.ERROR)) {
status.setError(NewWizardMessages.getFormattedString("VariableCreationDialog.error.invalidname", val.getMessage())); //$NON-NLS-1$
} else if (nameConflict(name)) {
status.setError(NewWizardMessages.getString("VariableCreationDialog.error.nameexists")); //$NON-NLS-1$
}
return status;
}
private boolean nameConflict(String name) {
if (fElement != null && fElement.getName().equals(name)) {
return false;
}
for (int i= 0; i < fExistingNames.size(); i++) {
CPVariableElement elem= (CPVariableElement)fExistingNames.get(i);
if (name.equals(elem.getName())){
return true;
}
}
return false;
}
private StatusInfo pathUpdated() {
StatusInfo status= new StatusInfo();
String path= fPathField.getText();
if (path.length() > 0) { // empty path is ok
if (!Path.ROOT.isValidPath(path)) {
status.setError(NewWizardMessages.getString("VariableCreationDialog.error.invalidpath")); //$NON-NLS-1$
} else if (!new File(path).exists()) {
status.setWarning(NewWizardMessages.getString("VariableCreationDialog.warning.pathnotexists")); //$NON-NLS-1$
}
}
return status;
}
private String getInitPath() {
String initPath= fPathField.getText();
if (initPath.length() == 0) {
initPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR);
if (initPath == null) {
initPath= ""; //$NON-NLS-1$
}
} else {
IPath entryPath= new Path(initPath);
if (ArchiveFileFilter.isArchivePath(entryPath)) {
entryPath.removeLastSegments(1);
}
initPath= entryPath.toOSString();
}
return initPath;
}
/*
* Open a dialog to choose a jar from the file system
*/
private IPath chooseExtJarFile() {
String initPath= getInitPath();
FileDialog dialog= new FileDialog(getShell());
dialog.setText(NewWizardMessages.getString("VariableCreationDialog.extjardialog.text")); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(initPath);
String res= dialog.open();
if (res != null) {
fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, dialog.getFilterPath());
return new Path(res).makeAbsolute();
}
return null;
}
private IPath chooseExtDirectory() {
String initPath= getInitPath();
DirectoryDialog dialog= new DirectoryDialog(getShell());
dialog.setText(NewWizardMessages.getString("VariableCreationDialog.extdirdialog.text")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("VariableCreationDialog.extdirdialog.message")); //$NON-NLS-1$
dialog.setFilterPath(initPath);
String res= dialog.open();
if (res != null) {
fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, dialog.getFilterPath());
return new Path(res);
}
return null;
}
}
|
10,022 |
Bug 10022 Incorrect "Build" popup action enablement
|
If "Build" action in the context sensitive popup menu in the Java perspective is always enabled. Even if the user goes to Preferences -> Workbench and selects "Perform build automatically on resource modification" the build menu option still appears in the Java popup menus. I believe this is incorrect. No need for a manual build if the build is already done, automatically. Mazen Faraj.
|
resolved fixed
|
72d2138
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T12:51:03Z | 2002-02-20T15:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/BuildActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.BuildAction;
import org.eclipse.ui.actions.RefreshAction;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.ui.IContextMenuConstants;
/**
* Contributes all build related actions to the context menu and installs action handlers
* for them in the global menu bar.
*
* @since 2.0
*/
public class BuildActionGroup extends ActionGroup{
private BuildAction fBuildAction;
private BuildAction fFullBuildAction;
private RefreshAction fRefreshAction;
/**
* Creates a new <code>BuildActionGroup</code>.
*
* @param part the view part that owns this action group
*/
public BuildActionGroup(IViewPart part) {
Shell shell= part.getSite().getShell();
ISelectionProvider provider= part.getSite().getSelectionProvider();
fBuildAction= new BuildAction(shell,
IncrementalProjectBuilder.INCREMENTAL_BUILD);
fBuildAction.setText(ActionMessages.getString("BuildAction.label")); //$NON-NLS-1$
fFullBuildAction= new BuildAction(shell,
IncrementalProjectBuilder.FULL_BUILD);
fFullBuildAction.setText(ActionMessages.getString("RebuildAction.label")); //$NON-NLS-1$
fRefreshAction= new RefreshAction(shell);
provider.addSelectionChangedListener(fBuildAction);
provider.addSelectionChangedListener(fFullBuildAction);
provider.addSelectionChangedListener(fRefreshAction);
}
/**
* Returns the refresh action managed by this group.
*
* @return the refresh action. If this group doesn't manage a refresh action
* <code>null</code> is returned.
*/
public RefreshAction getRefreshAction() {
return fRefreshAction;
}
/* (non-Javadoc)
* Method declared in ActionGroup
*/
public void fillActionBars(IActionBars actionBar) {
super.fillActionBars(actionBar);
setGlobalActionHandlers(actionBar);
}
/* (non-Javadoc)
* Method declared in ActionGroup
*/
public void fillContextMenu(IMenuManager menu) {
super.fillContextMenu(menu);
appendToGroup(menu, fFullBuildAction);
appendToGroup(menu, fRefreshAction);
}
private void setGlobalActionHandlers(IActionBars actionBar) {
actionBar.setGlobalActionHandler(IWorkbenchActionConstants.BUILD_PROJECT, fBuildAction);
actionBar.setGlobalActionHandler(IWorkbenchActionConstants.REBUILD_PROJECT, fFullBuildAction);
actionBar.setGlobalActionHandler(IWorkbenchActionConstants.REFRESH, fRefreshAction);
}
private void appendToGroup(IMenuManager menu, IAction action) {
if (action.isEnabled())
menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, action);
}
}
|
11,448 |
Bug 11448 extract method: incorrect on anonymous inner types
|
class A { void m(){ Object u= /*[*/new Object(){}/*]*/; } } this is extracted to a method with return type A which causes a compile error
|
resolved fixed
|
9d6ec9d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:01:48Z | 2002-03-15T11:00:00Z |
org.eclipse.jdt.ui/core
| |
11,448 |
Bug 11448 extract method: incorrect on anonymous inner types
|
class A { void m(){ Object u= /*[*/new Object(){}/*]*/; } } this is extracted to a method with return type A which causes a compile error
|
resolved fixed
|
9d6ec9d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:01:48Z | 2002-03-15T11:00:00Z |
extension/org/eclipse/jdt/internal/corext/dom/Bindings.java
| |
11,448 |
Bug 11448 extract method: incorrect on anonymous inner types
|
class A { void m(){ Object u= /*[*/new Object(){}/*]*/; } } this is extracted to a method with return type A which causes a compile error
|
resolved fixed
|
9d6ec9d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:01:48Z | 2002-03-15T11:00:00Z |
org.eclipse.jdt.ui/core
| |
11,448 |
Bug 11448 extract method: incorrect on anonymous inner types
|
class A { void m(){ Object u= /*[*/new Object(){}/*]*/; } } this is extracted to a method with return type A which causes a compile error
|
resolved fixed
|
9d6ec9d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:01:48Z | 2002-03-15T11:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java
| |
11,626 |
Bug 11626 extract method: needs a regression test for 11622/11537
| null |
resolved fixed
|
9d16086
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:29:20Z | 2002-03-19T12:13:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/expression_in/A_test620.java
| |
11,626 |
Bug 11626 extract method: needs a regression test for 11622/11537
| null |
resolved fixed
|
9d16086
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:29:20Z | 2002-03-19T12:13:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/expression_in/B.java
| |
11,626 |
Bug 11626 extract method: needs a regression test for 11622/11537
| null |
resolved fixed
|
9d16086
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:29:20Z | 2002-03-19T12:13:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/expression_out/A_test620.java
| |
11,626 |
Bug 11626 extract method: needs a regression test for 11622/11537
| null |
resolved fixed
|
9d16086
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:29:20Z | 2002-03-19T12:13:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/expression_out/B.java
| |
11,626 |
Bug 11626 extract method: needs a regression test for 11622/11537
| null |
resolved fixed
|
9d16086
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:29:20Z | 2002-03-19T12:13:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
11,626 |
Bug 11626 extract method: needs a regression test for 11622/11537
| null |
resolved fixed
|
9d16086
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:29:20Z | 2002-03-19T12:13:20Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTestSetup.java
| |
11,626 |
Bug 11626 extract method: needs a regression test for 11622/11537
| null |
resolved fixed
|
9d16086
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:29:20Z | 2002-03-19T12:13:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
11,626 |
Bug 11626 extract method: needs a regression test for 11622/11537
| null |
resolved fixed
|
9d16086
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T16:29:20Z | 2002-03-19T12:13:20Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java
| |
11,853 |
Bug 11853 extract method: incorrectly allowed on constructor invocation
|
tests 180 and 181 fail - disabled them for now just in case i'll put them here: public class A_test180 { public A_test180() { /*]*/this(10); foo();/*[*/ } public A_test180(int i) { super(); } public void foo() { } } public class A_test181 { public A_test181() { /*]*/super(); foo();/*[*/ } public void foo() { } }
|
resolved fixed
|
6cdf011
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T17:01:29Z | 2002-03-20T16:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/A.java
|
public class A{
public int value;
boolean m(){
return a().length != 3;
}
int[] a(){
return null;
}
}
|
11,853 |
Bug 11853 extract method: incorrectly allowed on constructor invocation
|
tests 180 and 181 fail - disabled them for now just in case i'll put them here: public class A_test180 { public A_test180() { /*]*/this(10); foo();/*[*/ } public A_test180(int i) { super(); } public void foo() { } } public class A_test181 { public A_test181() { /*]*/super(); foo();/*[*/ } public void foo() { } }
|
resolved fixed
|
6cdf011
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T17:01:29Z | 2002-03-20T16:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
11,853 |
Bug 11853 extract method: incorrectly allowed on constructor invocation
|
tests 180 and 181 fail - disabled them for now just in case i'll put them here: public class A_test180 { public A_test180() { /*]*/this(10); foo();/*[*/ } public A_test180(int i) { super(); } public void foo() { } } public class A_test181 { public A_test181() { /*]*/super(); foo();/*[*/ } public void foo() { } }
|
resolved fixed
|
6cdf011
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T17:01:29Z | 2002-03-20T16:00:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java
| |
11,853 |
Bug 11853 extract method: incorrectly allowed on constructor invocation
|
tests 180 and 181 fail - disabled them for now just in case i'll put them here: public class A_test180 { public A_test180() { /*]*/this(10); foo();/*[*/ } public A_test180(int i) { super(); } public void foo() { } } public class A_test181 { public A_test181() { /*]*/super(); foo();/*[*/ } public void foo() { } }
|
resolved fixed
|
6cdf011
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T17:01:29Z | 2002-03-20T16:00:00Z |
org.eclipse.jdt.ui/core
| |
11,853 |
Bug 11853 extract method: incorrectly allowed on constructor invocation
|
tests 180 and 181 fail - disabled them for now just in case i'll put them here: public class A_test180 { public A_test180() { /*]*/this(10); foo();/*[*/ } public A_test180(int i) { super(); } public void foo() { } } public class A_test181 { public A_test181() { /*]*/super(); foo();/*[*/ } public void foo() { } }
|
resolved fixed
|
6cdf011
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-18T17:01:29Z | 2002-03-20T16:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java
| |
14,112 |
Bug 14112 Show in Navigator doesn't work for non-java resources
|
1) select logo.gif in JUnit 2) show in navigator -> action
|
resolved fixed
|
72e1faa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-19T10:37:18Z | 2002-04-18T14:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/ShowInNavigatorViewAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.ui.views.navigator.ResourceNavigator;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class ShowInNavigatorViewAction extends SelectionDispatchAction {
private JavaEditor fEditor;
/**
* Creates a new <code>ShowInNavigatorViewAction</code>.
*
* @param site the site providing context information for this action
*/
public ShowInNavigatorViewAction(UnifiedSite site) {
super(site);
setText(ActionMessages.getString("ShowInNavigatorView.label")); //$NON-NLS-1$
}
/**
* Creates a new <code>ShowInNavigatorViewAction</code>.
* <p>
* Note: This constructor is for internal use only. Clients should not call this constructor.
* </p>
*/
public ShowInNavigatorViewAction(JavaEditor editor) {
this(UnifiedSite.create(editor.getEditorSite()));
fEditor= editor;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
setEnabled(fEditor != null);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
try {
setEnabled(getResource(getElement(selection)) != null);
} catch (JavaModelException e) {
JavaPlugin.log(e);
setEnabled(false);
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(ITextSelection selection) {
IJavaElement element= SelectionConverter.codeResolveOrInputHandled(fEditor,
getShell(), getDialogTitle(), ActionMessages.getString("ShowInNavigatorView.dialog.message")); //$NON-NLS-1$
if (element != null)
run(element);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
run(getElement(selection));
}
private void run(IJavaElement element) {
try {
IResource resource= getResource(element);
if (resource == null)
return;
IWorkbenchPage page= getSite().getWorkbenchWindow().getActivePage();
IViewPart view= page.showView(IPageLayout.ID_RES_NAV);
if (view instanceof ISetSelectionTarget) {
ISelection selection= new StructuredSelection(resource);
((ISetSelectionTarget)view).selectReveal(selection);
}
} catch(PartInitException e) {
ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.getString("ShowInNavigatorView.error.activation_failed")); //$NON-NLS-1$
} catch(JavaModelException e) {
ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.getString("ShowInNavigatorView.error.conversion_failed")); //$NON-NLS-1$
}
}
private IJavaElement getElement(IStructuredSelection selection) {
if (selection.size() != 1)
return null;
Object element= selection.getFirstElement();
if (!(element instanceof IJavaElement))
return null;
return (IJavaElement)element;
}
private IResource getResource(IJavaElement element) throws JavaModelException {
element= OpenActionUtil.getElementToOpen(element);
if (element == null)
return null;
return element.getCorrespondingResource();
}
private static String getDialogTitle() {
return ActionMessages.getString("ShowInNavigatorView.dialog.title"); //$NON-NLS-1$
}
}
|
11,882 |
Bug 11882 structured selection: remembering history should stop on 'whole-cu-selected' case
|
credit goes to Erich for finding this one when you press alt+up many times you select the whole cu when you press it again a couple of times then it takes the same number of times to bring it down again with alt+down it should stop stacking ranges when the range covers the full cu
|
resolved fixed
|
9328a0f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-19T12:29:36Z | 2002-03-20T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/structureselection/StructureSelectionAction.java
|
package org.eclipse.jdt.internal.ui.javaeditor.structureselection;
import java.util.Collection;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.internal.corext.SourceRange;
import org.eclipse.jdt.internal.corext.dom.Selection;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
public abstract class StructureSelectionAction extends Action {
public static final String NEXT= "SelectNextElement"; //$NON-NLS-1$
public static final String PREVIOUS= "SelectPreviousElement"; //$NON-NLS-1$
public static final String ENCLOSING= "SelectEnclosingElement"; //$NON-NLS-1$
public static final String HISTORY= "RestoreLastSelection"; //$NON-NLS-1$
private CompilationUnitEditor fEditor;
private SelectionHistory fSelectionHistory;
protected StructureSelectionAction(String text, CompilationUnitEditor editor, SelectionHistory history) {
super(text);
Assert.isNotNull(editor);
Assert.isNotNull(history);
fEditor= editor;
fSelectionHistory= history;
}
/*
* This constructor is for testing purpose only.
*/
protected StructureSelectionAction() {
super(""); //$NON-NLS-1$
}
/* (non-JavaDoc)
* Method declared in IAction.
*/
public final void run() {
ITextSelection selection= getTextSelection();
fSelectionHistory.remember(new SourceRange(selection.getOffset(), selection.getLength()));
ISourceRange newRange= getNewSelectionRange(createSourceRange(selection), getCompilationUnit());
try {
fSelectionHistory.ignoreSelectionChanges();
fEditor.selectAndReveal(newRange.getOffset(), newRange.getLength());
} finally {
fSelectionHistory.listenToSelectionChanges();
}
}
public final ISourceRange getNewSelectionRange(ISourceRange oldSourceRange, ICompilationUnit cu){
try{
if (! cu.isStructureKnown())
return oldSourceRange;
CompilationUnit root= AST.parseCompilationUnit(cu, false);
Selection selection= Selection.createFromStartLength(oldSourceRange.getOffset(), oldSourceRange.getLength());
StructureSelectionAnalyzer selAnalyzer= new StructureSelectionAnalyzer(selection, true);
root.accept(selAnalyzer);
return internalGetNewSelectionRange(oldSourceRange, cu, selAnalyzer);
} catch (JavaModelException e){
JavaPlugin.log(e); //dialog would be too heavy here
return new SourceRange(oldSourceRange.getOffset(), oldSourceRange.getLength());
}
}
/**
* This is the default implementation - it goes up one level in the AST.
* Subclasses may implement different behavior and/or use this implementation as a fallback for cases they do not handle..
*/
abstract ISourceRange internalGetNewSelectionRange(ISourceRange oldSourceRange, ICompilationUnit cu, StructureSelectionAnalyzer selAnalyzer) throws JavaModelException;
protected final ICompilationUnit getCompilationUnit() {
return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(fEditor.getEditorInput());
}
protected final ITextSelection getTextSelection() {
return (ITextSelection)fEditor.getSelectionProvider().getSelection();
}
protected static ISourceRange getLastCoveringNodeRange(ISourceRange oldSourceRange, ICompilationUnit cu, StructureSelectionAnalyzer selAnalyzer) throws JavaModelException {
if (selAnalyzer.getLastCoveringNode() == null)
return oldSourceRange;
else
return getSelectedNodeSourceRange(cu, selAnalyzer.getLastCoveringNode());
}
protected static ISourceRange getSelectedNodeSourceRange(ICompilationUnit cu, ASTNode nodeToSelect) throws JavaModelException {
int offset= nodeToSelect.getStartPosition();
int end= Math.min(cu.getSourceRange().getLength(), nodeToSelect.getStartPosition() + nodeToSelect.getLength() - 1);
return createSourceRange(offset, end);
}
//-- private helper methods
private static ISourceRange createSourceRange(ITextSelection ts){
if (ts.getLength() == 0) //to allow 0-length selection
return new SourceRange(ts.getOffset(), 1);
else
return new SourceRange(ts.getOffset(), ts.getLength());
}
//-- helper methods for this class and subclasses
static ISourceRange createSourceRange(int offset, int end){
int length= end - offset + 1;
if (length == 0) //to allow 0-length selection
length= 1;
return new SourceRange(Math.max(0, offset), length);
}
static ASTNode[] getChildNodes(ASTNode node){
if (node instanceof Block)
return convertToNodeArray(((Block)node).statements());
if (node instanceof TypeDeclaration)
return convertToNodeArray(((TypeDeclaration)node).bodyDeclarations());
if (node instanceof CompilationUnit)
return convertToNodeArray(((CompilationUnit)node).types());
return null;
}
private static ASTNode[] convertToNodeArray(Collection statements){
return (ASTNode[]) statements.toArray(new ASTNode[statements.size()]);
}
static int findIndex(Object[] array, Object o){
for (int i= 0; i < array.length; i++) {
Object object= array[i];
if (object == o)
return i;
}
return -1;
}
}
|
14,236 |
Bug 14236 Unable to log info messages during jar packaging
|
Using the 04/18 Integration build, I still can't get an info message into the status maintained by JarFileExportOperation. In my JarWriter implementation, the close() method is throwing a CoreException which contains a status whose severity is set to IStatus.INFO. However, note that JarFileExportOperation.addToStatus() only accepts ERROR and WARNING (and only when they are being logged respectively which they are for my package data).
|
resolved fixed
|
202c3f9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-19T16:07:06Z | 2002-04-19T15:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/CreateJarActionDelegate.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionReader;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.ProblemDialog;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class CreateJarActionDelegate extends JarPackageActionDelegate {
/*
* @see IActionDelegate
*/
public void run(IAction action) {
IFile[] descriptions= getDescriptionFiles(getSelection());
MultiStatus mergedStatus;
int length= descriptions.length;
if (length < 1)
return;
// Create read multi status
String message;
if (length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
MultiStatus readStatus= new MultiStatus(JavaPlugin.getPluginId(), 0, message, null); //$NON-NLS-1$
JarPackageData[] jarPackages= readJarPackages(descriptions, readStatus);
if (jarPackages.length > 0) {
IStatus status= export(jarPackages);
if (status == null)
return; // cancelled
if (readStatus.getSeverity() == IStatus.ERROR)
message= readStatus.getMessage();
else
message= status.getMessage();
// Create new status because we want another message - no API to set message
mergedStatus= new MultiStatus(JavaPlugin.getPluginId(), status.getCode(), readStatus.getChildren(), message, null);
mergedStatus.merge(status);
} else
mergedStatus= readStatus;
if (!mergedStatus.isOK())
ProblemDialog.open(getShell(), JarPackagerMessages.getString("CreateJarActionDelegate.jarExport.title"), null, mergedStatus); //$NON-NLS-1$
}
private JarPackageData[] readJarPackages(IFile[] descriptions, MultiStatus readStatus) {
List jarPackagesList= new ArrayList(descriptions.length);
for (int i= 0; i < descriptions.length; i++) {
JarPackageData jarPackage= readJarPackage(descriptions[i], readStatus);
if (jarPackage != null)
jarPackagesList.add(jarPackage);
}
return (JarPackageData[])jarPackagesList.toArray(new JarPackageData[jarPackagesList.size()]);
}
private IStatus export(JarPackageData[] jarPackages) {
Shell shell= getShell();
IJarExportRunnable op= jarPackages[0].createJarExportRunnable(jarPackages, shell);
try {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(shell);
dialog.run(true, true, op);
} catch (InvocationTargetException ex) {
if (ex.getTargetException() != null) {
ExceptionHandler.handle(ex, shell, JarPackagerMessages.getString("CreateJarActionDelegate.jarExportError.title"), JarPackagerMessages.getString("CreateJarActionDelegate.jarExportError.message")); //$NON-NLS-2$ //$NON-NLS-1$
return null;
}
} catch (InterruptedException e) {
// do nothing on cancel
return null;
}
return op.getStatus();
}
/**
* Reads the JAR package spec from file.
*/
protected JarPackageData readJarPackage(IFile description, MultiStatus readStatus) {
Assert.isLegal(description.isAccessible());
Assert.isNotNull(description.getFileExtension());
Assert.isLegal(description.getFileExtension().equals(JarPackagerUtil.DESCRIPTION_EXTENSION));
JarPackageData jarPackage= new JarPackageData();
IJarDescriptionReader reader= null;
try {
reader= jarPackage.createJarDescriptionReader(description.getContents());
// Do not save - only generate JAR
reader.read(jarPackage);
jarPackage.setSaveManifest(false);
jarPackage.setSaveDescription(false);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorReadingFile", description.getFullPath(), ex.getStatus().getException().getLocalizedMessage()); //$NON-NLS-1$
addToStatus(readStatus, jarPackage, message, ex);
return null;
} finally {
if ((jarPackage == null || jarPackage.logWarnings()) && reader != null)
// AddWarnings
readStatus.addAll(reader.getStatus());
try {
if (reader != null)
reader.close();
}
catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorClosingJarPackageDescriptionReader", description.getFullPath()); //$NON-NLS-1$
addToStatus(readStatus, jarPackage, message, ex);
}
}
return jarPackage;
}
protected void addToStatus(MultiStatus multiStatus, JarPackageData jarPackage, String defaultMessage, CoreException ex) {
IStatus status= ex.getStatus();
int severity= status.getSeverity();
if (jarPackage == null || (severity == IStatus.ERROR && jarPackage.logErrors()) || (severity == IStatus.WARNING && jarPackage.logWarnings())) {
String message= ex.getLocalizedMessage();
if (message == null || message.length() < 1) {
status= new Status(status.getSeverity(), status.getPlugin(), status.getCode(), defaultMessage, ex);
}
multiStatus.add(status);
}
}
}
|
14,236 |
Bug 14236 Unable to log info messages during jar packaging
|
Using the 04/18 Integration build, I still can't get an info message into the status maintained by JarFileExportOperation. In my JarWriter implementation, the close() method is throwing a CoreException which contains a status whose severity is set to IStatus.INFO. However, note that JarFileExportOperation.addToStatus() only accepts ERROR and WARNING (and only when they are being logged respectively which they are for my package data).
|
resolved fixed
|
202c3f9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-19T16:07:06Z | 2002-04-19T15:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionWriter;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.ui.jarpackager.JarWriter;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaStatusConstants;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IJarExportRunnable {
private static class MessageMultiStatus extends MultiStatus {
MessageMultiStatus(String pluginId, int code, String message, Throwable exception) {
super(pluginId, code, message, exception);
}
/*
* allows to change the message
*/
protected void setMessage(String message) {
super.setMessage(message);
}
}
private static final String COMPILER_SOURCE_FILE_ATTR = "org.eclipse.jdt.core.compiler.debug.sourceFile"; //$NON-NLS-1$
private JarWriter fJarWriter;
private JarPackageData fJarPackage;
private JarPackageData[] fJarPackages;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private Set fExportedClassContainers;
private MessageMultiStatus fStatus;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData jarPackage, Shell parent) {
this(new JarPackageData[] {jarPackage}, parent);
}
/**
* Creates an instance of this class.
*
* @param jarPackages an array with JAR package data objects
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData[] jarPackages, Shell parent) {
this(parent);
fJarPackages= jarPackages;
}
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fStatus= new MessageMultiStatus(JavaPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
}
protected void addToStatus(CoreException ex) {
IStatus status= ex.getStatus();
int severity= status.getSeverity();
if (fJarPackage == null || (severity == IStatus.ERROR && fJarPackage.logErrors()) || (severity == IStatus.WARNING && fJarPackage.logWarnings())) {
String message= ex.getLocalizedMessage();
if (message == null || message.length() < 1) {
message= JarPackagerMessages.getString("JarFileExportOperation.coreErrorDuringExport"); //$NON-NLS-1$
status= new Status(status.getSeverity(), status.getPlugin(), status.getCode(), message, ex);
}
fStatus.add(status);
}
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addWarning(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logWarnings())
fStatus.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logErrors())
fStatus.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return count;
}
}
else
resource= (IResource)element;
if (resource.getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)resource);
}
return count;
}
private int getTotalChildCount(IContainer container) {
IResource[] members;
try {
members= container.members();
} catch (CoreException ex) {
return 0;
}
int count= 0;
for (int i= 0; i < members.length; i++) {
if (members[i].getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)members[i]);
}
return count;
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= findPackageFragmentRoot(jProject, resource.getFullPath().removeLastSegments(1));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
if (mustUseSourceFolderHierarchy() && !pkgRoot.getElementName().equals(pkgRoot.DEFAULT_PACKAGEROOT_PATH))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else if (element instanceof IPackageFragment)
exportPackageFragment(progressMonitor, (IPackageFragment)element);
else
exportContainer(progressMonitor, (IContainer)resource);
}
private void exportPackageFragment(IProgressMonitor progressMonitor, IPackageFragment pkgFragment) throws java.lang.InterruptedException {
Object[] children;
try {
children= pkgFragment.getChildren();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
children= pkgFragment.getNonJavaResources();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", pkgFragment.toString()), e); //$NON-NLS-1$
}
}
private void exportContainer(IProgressMonitor progressMonitor, IContainer container) throws java.lang.InterruptedException {
if (container.getType() == IResource.FOLDER && isOutputFolder((IFolder)container))
return;
IResource[] children= null;
try {
children= container.members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", container.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private IPackageFragmentRoot findPackageFragmentRoot(IJavaProject jProject, IPath path) throws JavaModelException {
if (jProject == null || path == null || path.segmentCount() <= 0)
return null;
IPackageFragmentRoot pkgRoot= jProject.findPackageFragmentRoot(path);
if (pkgRoot != null)
return pkgRoot;
else
return findPackageFragmentRoot(jProject, path.removeLastSegments(1));
}
private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
boolean isNonJavaResource= !isInJavaProject || pkgRoot == null;
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == pkgRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", destinationPath.toString())); //$NON-NLS-1$
fJarWriter.write((IFile) resource, destinationPath);
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
private boolean isOutputFolder(IFolder folder) {
try {
IJavaProject javaProject= JavaCore.create(folder.getProject());
IPath outputFolderPath= javaProject.getOutputLocation();
return folder.getFullPath().equals(outputFolderPath);
} catch (JavaModelException ex) {
return false;
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", classFilePath.toString())); //$NON-NLS-1$
fJarWriter.write(file, classFilePath);
}
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
fExportedClassContainers= new HashSet(10);
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++)
exportElement(fJarPackage.getElements()[i], progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
// Allow JAR Package to provide its own strategy
IFile[] classFiles= fJarPackage.findClassfilesFor(file);
if (classFiles != null)
return Arrays.asList(classFiles).iterator();
if (!isJavaFile(file))
return Collections.EMPTY_LIST.iterator();
IPath outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
// Java CU - search files with .class ending
boolean hasErrors= hasCompileErrors(file);
boolean hasWarnings= hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fExportedClassContainers.contains(classContainer))
return Collections.EMPTY_LIST.iterator();
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
if (fJavaNameToClassFilesMap == null) {
// Could not fully build map. fallback is to export whole directory
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.missingSourceFileAttributeExportedAll", classContainer.getLocation().toFile()); //$NON-NLS-1$
addWarning(msg, null);
fExportedClassContainers.add(classContainer);
return getClassesIn(classContainer);
}
fClassFilesMapContainer= classContainer;
}
ArrayList classFileList= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFileList == null || classFileList.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFileList.iterator();
}
private Iterator getClassesIn(IContainer classContainer) throws CoreException {
IResource[] resources= classContainer.members();
List files= new ArrayList(resources.length);
for (int i= 0; i < resources.length; i++)
if (resources[i].getType() == IResource.FILE && isClassFile(resources[i]))
files.add(resources[i]);
return files.iterator();
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (!isCompilerGeneratingSourceFileAttribute())
return null;
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
if (cfReader.sourceFileName() == null) {
/*
* Can't fully build the map because one or more
* class file does not contain the name of its
* source file.
*/
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", classFile.getLocation().toFile()), null); //$NON-NLS-1$
return null;
}
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* The result is a status object containing individual
* status objects.
*
* @return the status of this operation
*/
public IStatus getStatus() {
String message= null;
switch (fStatus.getSeverity()) {
case IStatus.OK:
message= ""; //$NON-NLS-1$
break;
case IStatus.INFO:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithInfo"); //$NON-NLS-1$
break;
case IStatus.WARNING:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"); //$NON-NLS-1$
break;
case IStatus.ERROR:
if (fJarPackages.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
break;
default:
// defensive code in case new severity is defined
message= ""; //$NON-NLS-1$
break;
}
fStatus.setMessage(message);
return fStatus;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.areErrorsExported())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int count= fJarPackages.length;
progressMonitor.beginTask("", count); //$NON-NLS-1$
try {
for (int i= 0; i < count; i++) {
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1);
fJarPackage= fJarPackages[i];
if (fJarPackage != null)
singleRun(subProgressMonitor);
}
} finally {
progressMonitor.done();
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
int totalWork= countSelectedElements();
if (!isAutoBuilding() && fJarPackage.isBuildingIfNeeded()) {
int subMonitorTicks= totalWork/10;
totalWork += subMonitorTicks;
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, subMonitorTicks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
buildProjects(subProgressMonitor);
} else
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
fJarWriter= fJarPackage.createJarWriter(fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (CoreException ex) {
addToStatus(ex);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (CoreException ex) {
addToStatus(ex);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getElements() == null || fJarPackage.getElements().length == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isManifestAccessible()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
IFile[] unsavedFiles= getUnsavedFiles();
if (unsavedFiles.length > 0)
return saveModifiedResourcesIfUserConfirms(unsavedFiles);
return true;
}
/**
* Returns the files which are not saved and which are
* part of the files being exported.
*
* @return an array of unsaved files
*/
private IFile[] getUnsavedFiles() {
IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors();
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
List selection= JarPackagerUtil.asResources(fJarPackage.getElements());
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (selection.contains(dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[])unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* Asks the user to confirm to save the modified resources.
*
* @return true if user pressed OK.
*/
private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) {
if (dirtyFiles == null || dirtyFiles.length == 0)
return true;
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(fParentShell, dirtyFiles);
final int[] intResult= new int[1];
Runnable runnable= new Runnable() {
public void run() {
intResult[0]= dlg.open();
}
};
display.syncExec(runnable);
return intResult[0] == IDialogConstants.OK_ID;
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles))
return saveModifiedResources(dirtyFiles);
// Report unsaved files
for (int i= 0; i < dirtyFiles.length; i++)
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFiles[i].getFullPath()), null); //$NON-NLS-1$
return false;
}
/**
* Save all of the editors in the workbench.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) {
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
final boolean[] retVal= new boolean[1];
Runnable runnable= new Runnable() {
public void run() {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IWorkspaceDescription description= workspace.getDescription();
boolean autoBuild= description.isAutoBuilding();
description.setAutoBuilding(false);
try {
workspace.setDescription(description);
// This save operation can not be canceled.
try {
new ProgressMonitorDialog(fParentShell).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
retVal[0]= true;
} finally {
description.setAutoBuilding(autoBuild);
workspace.setDescription(description);
}
} catch (InvocationTargetException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
} catch (InterruptedException ex) {
Assert.isTrue(false); // Can't happen. Operation isn't cancelable.
retVal[0]= false;
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
}
}
};
display.syncExec(runnable);
return retVal[0];
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= JavaPlugin.getDirtyEditors();
pm.beginTask(JarPackagerMessages.getString("JarFileExportOperation.savingModifiedResources"), editorsToSave.length); //$NON-NLS-1$
try {
List dirtyFilesList= Arrays.asList(dirtyFiles);
for (int i= 0; i < editorsToSave.length; i++) {
if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)editorsToSave[i].getEditorInput()).getFile();
if (dirtyFilesList.contains((dirtyFile)))
editorsToSave[i].doSave(new SubProgressMonitor(pm, 1));
}
pm.worked(1);
}
} finally {
pm.done();
}
}
};
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
IJarDescriptionWriter writer= fJarPackage.createJarDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
writer.write(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile= fJarPackage.getDescriptionFile();
if (descriptionFile.isAccessible() && (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, descriptionFile.getFullPath().toString())))
descriptionFile.setContents(fileInput, true, true, null);
else {
descriptionFile.create(fileInput, true, null);
}
} finally {
if (fileInput != null)
fileInput.close();
if (writer != null)
writer.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
IFile manifestFile= fJarPackage.getManifestFile();
if (manifestFile.isAccessible() && (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, manifestFile.getFullPath().toString())))
manifestFile.setContents(fileInput, true, true, null);
else {
manifestFile.create(fileInput, true, null);
}
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
private boolean isAutoBuilding() {
return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
}
private boolean isCompilerGeneratingSourceFileAttribute() {
Object value= JavaCore.getOptions().get(COMPILER_SOURCE_FILE_ATTR);
if (value instanceof String)
return "generate".equalsIgnoreCase((String)value); //$NON-NLS-1$
else
return true; // default
}
private void buildProjects(IProgressMonitor progressMonitor) {
Set builtProjects= new HashSet(10);
Object[] elements= fJarPackage.getElements();
for (int i= 0; i < elements.length; i++) {
IProject project= null;
Object element= elements[i];
if (element instanceof IResource)
project= ((IResource)element).getProject();
else if (element instanceof IJavaElement)
project= ((IJavaElement)element).getJavaProject().getProject();
if (project != null && !builtProjects.contains(project)) {
try {
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, progressMonitor);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringProjectBuild", project.getFullPath()); //$NON-NLS-1$
addError(message, ex);
} finally {
// don't try to build same project a second time even if it failed
builtProjects.add(project);
}
}
}
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileErrors(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
return true;
}
return false;
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileWarnings(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_WARNING)
return true;
}
return false;
}
private boolean mustUseSourceFolderHierarchy() {
return fJarPackage.useSourceFolderHierarchy() && fJarPackage.areJavaFilesExported() && !fJarPackage.areClassFilesExported();
}
}
|
14,093 |
Bug 14093 exception in search results view
|
M5 sorry, no steps my search results view stopped working (would display no entries) then i found this in the log java.lang.NullPointerException at org.eclipse.jdt.internal.ui.search.GroupByKeyComputer.getJavaElement (GroupByKeyComputer.java:56) at org.eclipse.jdt.internal.ui.search.GroupByKeyComputer.computeGroupByKey (GroupByKeyComputer.java:28) at org.eclipse.search.internal.ui.SearchManager.handleAddMatch (SearchManager.java:375) at org.eclipse.search.internal.ui.SearchManager.handleSearchMarkerChanged (SearchManager.java:359) at org.eclipse.search.internal.ui.SearchManager.handleSearchMarkersChanged (SearchManager.java:348) at org.eclipse.search.internal.ui.SearchManager.access$2 (SearchManager.java:337) at org.eclipse.search.internal.ui.SearchManager$7.run (SearchManager.java:472) 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:482) 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:62) at org.eclipse.core.internal.resources.Workspace.broadcastChanges (Workspace.java:134) at org.eclipse.core.internal.resources.Workspace.endOperation (Workspace.java(Compiled Code)) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1348) at org.eclipse.ui.actions.WorkspaceModifyOperation.run (WorkspaceModifyOperation.java:78) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.executeChange (PerformChangeOperation.java:143) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:132) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:713) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:330) at org.eclipse.jdt.internal.ui.refactoring.PreviewWizardPage.performFinish (PreviewWizardPage.java:310) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:461) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:356) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.RefactoringSupportFactory$RenameSupport. rename(RefactoringSupportFactory.java:73) at org.eclipse.jdt.internal.ui.reorg.RenameAction.run (RenameAction.java:37) at org.eclipse.jface.action.Action.runWithEvent(Action.java:590) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:819) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:190) at org.eclipse.core.launcher.Main.run(Main.java:549) at org.eclipse.core.launcher.Main.main(Main.java:390)
|
resolved fixed
|
c59926d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-19T16:10:29Z | 2002-04-18T11:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/GroupByKeyComputer.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.search;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.search.ui.IGroupByKeyComputer;
import org.eclipse.jdt.core.IJavaElement;
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.util.ExceptionHandler;
public class GroupByKeyComputer implements IGroupByKeyComputer {
IJavaElement fLastJavaElement= null;;
String fLastHandle= null;;
public Object computeGroupByKey(IMarker marker) {
if (marker == null)
return null;
IJavaElement jElement= getJavaElement(marker);
if (jElement != null && jElement.exists()) {
// no help from JavaModel to rename yet
// return getJavaElement(marker);
return fLastHandle;
}
return null;
}
private String getJavaElementHandleId(IMarker marker) {
try {
return (String)marker.getAttribute(IJavaSearchUIConstants.ATT_JE_HANDLE_ID);
} catch (CoreException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.markerAttributeAccess.title"), SearchMessages.getString("Search.Error.markerAttributeAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$
return null;
}
}
private IJavaElement getJavaElement(IMarker marker) {
String handle= getJavaElementHandleId(marker);
if (handle == null) {
fLastHandle= null;
fLastJavaElement= null;
return null;
}
if (!handle.equals(fLastHandle)) {
fLastJavaElement= SearchUtil.getJavaElement(marker);
fLastHandle= fLastJavaElement.getHandleIdentifier();
}
return fLastJavaElement;
}
}
|
14,281 |
Bug 14281 Java search page layout of Limit To
|
The Limit To box should be top aligned with the Search For box
|
resolved fixed
|
77e6484
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-22T08:34:51Z | 2002-04-20T16:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.search;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.search.ui.ISearchPage;
import org.eclipse.search.ui.ISearchPageContainer;
import org.eclipse.search.ui.ISearchResultViewEntry;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.RowLayouter;
public class JavaSearchPage extends DialogPage implements ISearchPage, IJavaSearchConstants {
public static final String EXTENSION_POINT_ID= "org.eclipse.jdt.ui.JavaSearchPage"; //$NON-NLS-1$
// Dialog store id constants
private final static String PAGE_NAME= "JavaSearchPage"; //$NON-NLS-1$
private final static String STORE_CASE_SENSITIVE= PAGE_NAME + "CASE_SENSITIVE"; //$NON-NLS-1$
private static List fgPreviousSearchPatterns= new ArrayList(20);
private SearchPatternData fInitialData;
private IStructuredSelection fStructuredSelection;
private IJavaElement fJavaElement;
private boolean fFirstTime= true;
private IDialogSettings fDialogSettings;
private boolean fIsCaseSensitive;
private Combo fPattern;
private ISearchPageContainer fContainer;
private Button fCaseSensitive;
private Button[] fSearchFor;
private String[] fSearchForText= {
SearchMessages.getString("SearchPage.searchFor.type"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.method"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.package"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.constructor"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.field")}; //$NON-NLS-1$
private Button[] fLimitTo;
private String[] fLimitToText= {
SearchMessages.getString("SearchPage.limitTo.declarations"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.implementors"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.references"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.allOccurrences"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.readReferences"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.writeReferences")}; //$NON-NLS-1$
private class SearchPatternData {
int searchFor;
int limitTo;
String pattern;
boolean isCaseSensitive;
IJavaElement javaElement;
int scope;
IWorkingSet[] workingSets;
public SearchPatternData(int s, int l, String p, IJavaElement element) {
this(s, l, p, fIsCaseSensitive || element != null, element, ISearchPageContainer.WORKSPACE_SCOPE, null);
}
public SearchPatternData(int s, int l, String p, boolean i, IJavaElement element, int scope, IWorkingSet[] workingSets) {
searchFor= s;
limitTo= l;
pattern= p;
isCaseSensitive= i;
javaElement= element;
this.scope= scope;
this.workingSets= workingSets;
}
}
//---- Action Handling ------------------------------------------------
public boolean performAction() {
SearchUI.activateSearchResultView();
SearchPatternData data= getPatternData();
IWorkspace workspace= JavaPlugin.getWorkspace();
// Setup search scope
IJavaSearchScope scope= null;
String scopeDescription= ""; //$NON-NLS-1$
switch (getContainer().getSelectedScope()) {
case ISearchPageContainer.WORKSPACE_SCOPE:
scopeDescription= SearchMessages.getString("WorkspaceScope"); //$NON-NLS-1$
scope= SearchEngine.createWorkspaceScope();
break;
case ISearchPageContainer.SELECTION_SCOPE:
scopeDescription= SearchMessages.getString("SelectionScope"); //$NON-NLS-1$
scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(fStructuredSelection);
break;
case ISearchPageContainer.WORKING_SET_SCOPE:
IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets();
// should not happen - just to be sure
if (workingSets == null || workingSets.length < 1)
return false;
scopeDescription= SearchMessages.getFormattedString("WorkingSetScope", SearchUtil.toString(workingSets)); //$NON-NLS-1$
scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getContainer().getSelectedWorkingSets());
ElementSearchAction.updateLRUWorkingSets(getContainer().getSelectedWorkingSets());
}
JavaSearchResultCollector collector= new JavaSearchResultCollector();
JavaSearchOperation op= null;
if (data.javaElement != null && getPattern().equals(fInitialData.pattern))
op= new JavaSearchOperation(workspace, data.javaElement, data.limitTo, scope, scopeDescription, collector);
else {
data.javaElement= null;
op= new JavaSearchOperation(workspace, data.pattern, data.isCaseSensitive, data.searchFor, data.limitTo, scope, scopeDescription, collector);
}
Shell shell= getControl().getShell();
try {
getContainer().getRunnableContext().run(true, true, op);
} catch (InvocationTargetException ex) {
ExceptionHandler.handle(ex, shell, SearchMessages.getString("Search.Error.search.title"), SearchMessages.getString("Search.Error.search.message")); //$NON-NLS-2$ //$NON-NLS-1$
return false;
} catch (InterruptedException ex) {
return false;
}
return true;
}
private int getLimitTo() {
for (int i= 0; i < fLimitTo.length; i++) {
if (fLimitTo[i].getSelection())
return i;
}
return -1;
}
private void setLimitTo(int searchFor) {
fLimitTo[DECLARATIONS].setEnabled(true);
fLimitTo[IMPLEMENTORS].setEnabled(false);
fLimitTo[REFERENCES].setEnabled(true);
fLimitTo[ALL_OCCURRENCES].setEnabled(true);
fLimitTo[READ_ACCESSES].setEnabled(false);
fLimitTo[WRITE_ACCESSES].setEnabled(false);
if (!(searchFor == TYPE || searchFor == INTERFACE) && fLimitTo[IMPLEMENTORS].getSelection()) {
fLimitTo[IMPLEMENTORS].setSelection(false);
fLimitTo[REFERENCES].setSelection(true);
}
if (!(searchFor == FIELD) && (getLimitTo() == READ_ACCESSES || getLimitTo() == WRITE_ACCESSES)) {
fLimitTo[getLimitTo()].setSelection(false);
fLimitTo[REFERENCES].setSelection(true);
}
switch (searchFor) {
case TYPE | INTERFACE:
fLimitTo[IMPLEMENTORS].setEnabled(true);
case FIELD:
fLimitTo[READ_ACCESSES].setEnabled(true);
fLimitTo[WRITE_ACCESSES].setEnabled(true);
break;
default :
break;
}
}
private String[] getPreviousSearchPatterns() {
// Search results are not persistent
int patternCount= fgPreviousSearchPatterns.size();
String [] patterns= new String[patternCount];
for (int i= 0; i < patternCount; i++)
patterns[i]= ((SearchPatternData) fgPreviousSearchPatterns.get(patternCount - 1 - i)).pattern;
return patterns;
}
private int getSearchFor() {
for (int i= 0; i < fSearchFor.length; i++) {
if (fSearchFor[i].getSelection())
return i;
}
Assert.isTrue(false, "shouldNeverHappen"); //$NON-NLS-1$
return -1;
}
private String getPattern() {
return fPattern.getText();
}
/**
* Return search pattern data and update previous searches.
* An existing entry will be updated.
*/
private SearchPatternData getPatternData() {
String pattern= getPattern();
SearchPatternData match= null;
int i= 0;
int size= fgPreviousSearchPatterns.size();
while (match == null && i < size) {
match= (SearchPatternData) fgPreviousSearchPatterns.get(i);
i++;
if (!pattern.equals(match.pattern))
match= null;
};
if (match == null) {
match= new SearchPatternData(
getSearchFor(),
getLimitTo(),
pattern,
fCaseSensitive.getSelection(),
fJavaElement,
getContainer().getSelectedScope(),
getContainer().getSelectedWorkingSets());
fgPreviousSearchPatterns.add(match);
}
else {
match.searchFor= getSearchFor();
match.limitTo= getLimitTo();
match.isCaseSensitive= fCaseSensitive.getSelection();
match.javaElement= fJavaElement;
match.scope= getContainer().getSelectedScope();
match.workingSets= getContainer().getSelectedWorkingSets();
};
return match;
}
/*
* Implements method from IDialogPage
*/
public void setVisible(boolean visible) {
if (visible && fPattern != null) {
if (fFirstTime) {
fFirstTime= false;
// Set item and text here to prevent page from resizing
fPattern.setItems(getPreviousSearchPatterns());
initSelections();
}
fPattern.setFocus();
getContainer().setPerformActionEnabled(fPattern.getText().length() > 0 && getContainer().hasValidScope());
}
super.setVisible(visible);
}
public boolean isValid() {
return true;
}
//---- Widget creation ------------------------------------------------
/**
* Creates the page's content.
*/
public void createControl(Composite parent) {
readConfiguration();
GridData gd;
Composite result= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2; layout.makeColumnsEqualWidth= true;
layout.horizontalSpacing= 10;
result.setLayout(layout);
RowLayouter layouter= new RowLayouter(layout.numColumns);
gd= new GridData();
gd.horizontalAlignment= gd.FILL;
layouter.setDefaultGridData(gd, 0);
layouter.setDefaultGridData(gd, 1);
layouter.setDefaultSpan();
layouter.perform(createExpression(result));
layouter.perform(createSearchFor(result), createLimitTo(result), -1);
SelectionAdapter javaElementInitializer= new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
if (getSearchFor() == fInitialData.searchFor)
fJavaElement= fInitialData.javaElement;
else
fJavaElement= null;
setLimitTo(getSearchFor());
updateCaseSensitiveCheckbox();
}
};
fSearchFor[TYPE].addSelectionListener(javaElementInitializer);
fSearchFor[METHOD].addSelectionListener(javaElementInitializer);
fSearchFor[FIELD].addSelectionListener(javaElementInitializer);
fSearchFor[CONSTRUCTOR].addSelectionListener(javaElementInitializer);
fSearchFor[PACKAGE].addSelectionListener(javaElementInitializer);
setControl(result);
WorkbenchHelp.setHelp(result, IJavaHelpContextIds.JAVA_SEARCH_PAGE);
}
private Control createExpression(Composite parent) {
Group result= new Group(parent, SWT.NONE);
result.setText(SearchMessages.getString("SearchPage.expression.label")); //$NON-NLS-1$
GridLayout layout= new GridLayout();
layout.numColumns= 2;
result.setLayout(layout);
// Pattern combo
fPattern= new Combo(result, SWT.SINGLE | SWT.BORDER);
fPattern.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handlePatternSelected();
}
});
fPattern.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
getContainer().setPerformActionEnabled(getPattern().length() > 0 && getContainer().hasValidScope());
updateCaseSensitiveCheckbox();
}
});
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= convertWidthInCharsToPixels(30);
gd.horizontalSpan= 2;
fPattern.setLayoutData(gd);
// Pattern info
Label label= new Label(result, SWT.LEFT);
label.setText(SearchMessages.getString("SearchPage.expression.pattern")); //$NON-NLS-1$
// Ignore case checkbox
fCaseSensitive= new Button(result, SWT.CHECK);
fCaseSensitive.setText(SearchMessages.getString("SearchPage.expression.caseSensitive")); //$NON-NLS-1$
gd= new GridData(); gd.horizontalAlignment= gd.END;
fCaseSensitive.setLayoutData(gd);
fCaseSensitive.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fIsCaseSensitive= fCaseSensitive.getSelection();
writeConfiguration();
}
});
return result;
}
private void updateCaseSensitiveCheckbox() {
if (fInitialData != null && getPattern().equals(fInitialData.pattern) && fJavaElement != null) {
fCaseSensitive.setEnabled(false);
fCaseSensitive.setSelection(true);
}
else {
fCaseSensitive.setEnabled(true);
fCaseSensitive.setSelection(fIsCaseSensitive);
}
}
private void handlePatternSelected() {
if (fPattern.getSelectionIndex() < 0)
return;
int index= fgPreviousSearchPatterns.size() - 1 - fPattern.getSelectionIndex();
fInitialData= (SearchPatternData) fgPreviousSearchPatterns.get(index);
for (int i= 0; i < fSearchFor.length; i++)
fSearchFor[i].setSelection(false);
for (int i= 0; i < fLimitTo.length; i++)
fLimitTo[i].setSelection(false);
fSearchFor[fInitialData.searchFor].setSelection(true);
setLimitTo(fInitialData.searchFor);
fLimitTo[fInitialData.limitTo].setSelection(true);
fPattern.setText(fInitialData.pattern);
fIsCaseSensitive= fInitialData.isCaseSensitive;
fJavaElement= fInitialData.javaElement;
fCaseSensitive.setEnabled(fJavaElement == null);
fCaseSensitive.setSelection(fInitialData.isCaseSensitive);
if (fInitialData.workingSets != null)
getContainer().setSelectedWorkingSets(fInitialData.workingSets);
else
getContainer().setSelectedScope(fInitialData.scope);
}
private Control createSearchFor(Composite parent) {
Group result= new Group(parent, SWT.NONE);
result.setText(SearchMessages.getString("SearchPage.searchFor.label")); //$NON-NLS-1$
GridLayout layout= new GridLayout();
layout.numColumns= 3;
result.setLayout(layout);
result.setLayoutData(new GridData(GridData.FILL_VERTICAL));
fSearchFor= new Button[fSearchForText.length];
for (int i= 0; i < fSearchForText.length; i++) {
Button button= new Button(result, SWT.RADIO);
button.setText(fSearchForText[i]);
fSearchFor[i]= button;
}
return result;
}
private Control createLimitTo(Composite parent) {
Group result= new Group(parent, SWT.NONE);
result.setText(SearchMessages.getString("SearchPage.limitTo.label")); //$NON-NLS-1$
GridLayout layout= new GridLayout();
layout.numColumns= 2;
result.setLayout(layout);
fLimitTo= new Button[fLimitToText.length];
for (int i= 0; i < fLimitToText.length; i++) {
Button button= new Button(result, SWT.RADIO);
button.setText(fLimitToText[i]);
fLimitTo[i]= button;
}
return result;
}
private void initSelections() {
fStructuredSelection= asStructuredSelection();
fInitialData= tryStructuredSelection(fStructuredSelection);
if (fInitialData == null)
fInitialData= trySimpleTextSelection(getContainer().getSelection());
if (fInitialData == null)
fInitialData= getDefaultInitValues();
fJavaElement= fInitialData.javaElement;
fCaseSensitive.setSelection(fInitialData.isCaseSensitive);
fCaseSensitive.setEnabled(fInitialData.javaElement == null);
fSearchFor[fInitialData.searchFor].setSelection(true);
setLimitTo(fInitialData.searchFor);
fLimitTo[fInitialData.limitTo].setSelection(true);
fPattern.setText(fInitialData.pattern);
}
private SearchPatternData tryStructuredSelection(IStructuredSelection selection) {
if (selection == null)
return null;
Object o= selection.getFirstElement();
if (o instanceof IJavaElement) {
return determineInitValuesFrom((IJavaElement)o);
} else if (o instanceof ISearchResultViewEntry) {
IJavaElement element= SearchUtil.getJavaElement(((ISearchResultViewEntry)o).getSelectedMarker());
return determineInitValuesFrom(element);
} else if (o instanceof IAdaptable) {
IJavaElement element= (IJavaElement)((IAdaptable)o).getAdapter(IJavaElement.class);
if (element != null) {
return determineInitValuesFrom(element);
} else {
IWorkbenchAdapter adapter= (IWorkbenchAdapter)((IAdaptable)o).getAdapter(IWorkbenchAdapter.class);
if (adapter != null)
return new SearchPatternData(TYPE, REFERENCES, adapter.getLabel(o), null);
}
}
return null;
}
private IJavaElement getJavaElement(IMarker marker) {
try {
return JavaCore.create((String)marker.getAttribute(IJavaSearchUIConstants.ATT_JE_HANDLE_ID));
} catch (CoreException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.createJavaElement.title"), SearchMessages.getString("Search.Error.createJavaElement.message")); //$NON-NLS-2$ //$NON-NLS-1$
return null;
}
}
private SearchPatternData determineInitValuesFrom(IJavaElement element) {
if (element == null)
return null;
int searchFor= UNKNOWN;
int limitTo= UNKNOWN;
String pattern= null;
switch (element.getElementType()) {
case IJavaElement.PACKAGE_FRAGMENT:
searchFor= PACKAGE;
limitTo= REFERENCES;
pattern= element.getElementName();
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
searchFor= PACKAGE;
limitTo= REFERENCES;
pattern= element.getElementName();
break;
case IJavaElement.PACKAGE_DECLARATION:
searchFor= PACKAGE;
limitTo= REFERENCES;
pattern= element.getElementName();
break;
case IJavaElement.IMPORT_DECLARATION:
pattern= element.getElementName();
IImportDeclaration declaration= (IImportDeclaration)element;
if (declaration.isOnDemand()) {
searchFor= PACKAGE;
int index= pattern.lastIndexOf('.');
pattern= pattern.substring(0, index);
} else {
searchFor= TYPE;
}
limitTo= DECLARATIONS;
break;
case IJavaElement.TYPE:
searchFor= TYPE;
limitTo= REFERENCES;
pattern= JavaModelUtil.getFullyQualifiedName((IType)element);
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit cu= (ICompilationUnit)element;
String mainTypeName= element.getElementName().substring(0, element.getElementName().indexOf(".")); //$NON-NLS-1$
IType mainType= cu.getType(mainTypeName);
mainTypeName= JavaModelUtil.getTypeQualifiedName(mainType);
try {
mainType= JavaModelUtil.findTypeInCompilationUnit(cu, mainTypeName);
if (mainType == null) {
// fetch type which is declared first in the file
IType[] types= cu.getTypes();
if (types.length > 0)
mainType= types[0];
else
break;
}
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$
break;
}
searchFor= TYPE;
element= mainType;
limitTo= REFERENCES;
pattern= JavaModelUtil.getFullyQualifiedName((IType)mainType);
break;
case IJavaElement.CLASS_FILE:
IClassFile cf= (IClassFile)element;
try {
mainType= cf.getType();
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$
break;
}
if (mainType == null)
break;
element= mainType;
searchFor= TYPE;
limitTo= REFERENCES;
pattern= JavaModelUtil.getFullyQualifiedName(mainType);
break;
case IJavaElement.FIELD:
searchFor= FIELD;
limitTo= REFERENCES;
IType type= ((IField)element).getDeclaringType();
StringBuffer buffer= new StringBuffer();
buffer.append(JavaModelUtil.getFullyQualifiedName(type));
buffer.append('.');
buffer.append(element.getElementName());
pattern= buffer.toString();
break;
case IJavaElement.METHOD:
searchFor= METHOD;
try {
IMethod method= (IMethod)element;
if (method.isConstructor())
searchFor= CONSTRUCTOR;
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$
break;
}
limitTo= REFERENCES;
pattern= PrettySignature.getMethodSignature((IMethod)element);
break;
}
if (searchFor != UNKNOWN && limitTo != UNKNOWN && pattern != null)
return new SearchPatternData(searchFor, limitTo, pattern, element);
return null;
}
private SearchPatternData trySimpleTextSelection(ISelection selection) {
SearchPatternData result= null;
if (selection instanceof ITextSelection) {
BufferedReader reader= new BufferedReader(new StringReader(((ITextSelection)selection).getText()));
String text;
try {
text= reader.readLine();
if (text == null)
text= ""; //$NON-NLS-1$
} catch (IOException ex) {
text= ""; //$NON-NLS-1$
}
result= new SearchPatternData(TYPE, REFERENCES, text, null);
}
return result;
}
private SearchPatternData getDefaultInitValues() {
return new SearchPatternData(TYPE, REFERENCES, "", null); //$NON-NLS-1$
}
/*
* Implements method from ISearchPage
*/
public void setContainer(ISearchPageContainer container) {
fContainer= container;
}
/**
* Returns the search page's container.
*/
private ISearchPageContainer getContainer() {
return fContainer;
}
/**
* Returns the structured selection from the selection.
*/
private IStructuredSelection asStructuredSelection() {
IWorkbenchWindow wbWindow= PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (wbWindow != null) {
IWorkbenchPage page= wbWindow.getActivePage();
if (page != null) {
IWorkbenchPart part= page.getActivePart();
if (part != null)
try {
return SelectionConverter.getStructuredSelection(part);
} catch (JavaModelException ex) {
}
}
}
return StructuredSelection.EMPTY;
}
//--------------- Configuration handling --------------
/**
* Returns the page settings for this Java search page.
*
* @return the page settings to be used
*/
private IDialogSettings getDialogSettings() {
IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings();
fDialogSettings= settings.getSection(PAGE_NAME);
if (fDialogSettings == null)
fDialogSettings= settings.addNewSection(PAGE_NAME);
return fDialogSettings;
}
/**
* Initializes itself from the stored page settings.
*/
private void readConfiguration() {
IDialogSettings s= getDialogSettings();
fIsCaseSensitive= s.getBoolean(STORE_CASE_SENSITIVE);
}
/**
* Stores it current configuration in the dialog store.
*/
private void writeConfiguration() {
IDialogSettings s= getDialogSettings();
s.put(STORE_CASE_SENSITIVE, fIsCaseSensitive);
}
}
|
14,120 |
Bug 14120 Main Class problem in JAR export wizard
|
M5 Build --Part 1-- 1. Add a new project called "MyProject" 2. Add a new class to the default package called "MyClass" with main method public class MyClass { public static void main(String[] args) { } } 3. File->Export->JAR File, choose everything from MyProject. 4. Set JAR file to c:\temp\MyTest.jar 5. Press 'Next' twice 6. Browse and choose the only main class: MyClass 7. Click 'Finish' Than the dialog appeared as "JAR creation failed". In the detail section "Main class is not valid" Retyping the Main Class results in "The selected main class is not selected for export or has no main method" --Part 2-- Cancel the export dialog and add a plain text file called 'MyManifest' with following content: Manifest-Version: 1.0 Main-Class: MyClass Now, repeat the export process with only 1 difference: Use MyManifest as manifest file. Everything works fine now.
|
resolved fixed
|
9f3790b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-22T09:27:23Z | 2002-04-18T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarPackagerUtil.java
| |
14,120 |
Bug 14120 Main Class problem in JAR export wizard
|
M5 Build --Part 1-- 1. Add a new project called "MyProject" 2. Add a new class to the default package called "MyClass" with main method public class MyClass { public static void main(String[] args) { } } 3. File->Export->JAR File, choose everything from MyProject. 4. Set JAR file to c:\temp\MyTest.jar 5. Press 'Next' twice 6. Browse and choose the only main class: MyClass 7. Click 'Finish' Than the dialog appeared as "JAR creation failed". In the detail section "Main class is not valid" Retyping the Main Class results in "The selected main class is not selected for export or has no main method" --Part 2-- Cancel the export dialog and add a plain text file called 'MyManifest' with following content: Manifest-Version: 1.0 Main-Class: MyClass Now, repeat the export process with only 1 difference: Use MyManifest as manifest file. Everything works fine now.
|
resolved fixed
|
9f3790b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-22T09:27:23Z | 2002-04-18T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/jarpackager/JarPackageData.java
| |
11,673 |
Bug 11673 ESC does not cancel Apply when changing compiler options
|
build 20020319 Workbench->Preferences->Java->Compiler 1) Start with the default settings 2) Change "Unused local variables" to "Warning" 3) Hit Apply button 4) Dialog shows up asking if user wants a full rebuild 5) Hit Cancel to exit yes/no dialog 6) Hit cancel to exit preferences 7) Go back to the same preferences page 8) "Unused local variables" was set to "Warning" The expected behaviour was to cancel the dialog (none of the options) and cancel the preferences without modifying anything. It seems that ESC is the same as hitting NO in that dialog.
|
resolved fixed
|
e34c5fc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-22T09:40:25Z | 2002-03-19T20:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
/*
* The page for setting the compiler options.
*/
public class CompilerPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
// Preference store keys, see JavaCore.getOptions
private static final String PREF_LOCAL_VARIABLE_ATTR= "org.eclipse.jdt.core.compiler.debug.localVariable"; //$NON-NLS-1$
private static final String PREF_LINE_NUMBER_ATTR= "org.eclipse.jdt.core.compiler.debug.lineNumber"; //$NON-NLS-1$
private static final String PREF_SOURCE_FILE_ATTR= "org.eclipse.jdt.core.compiler.debug.sourceFile"; //$NON-NLS-1$
private static final String PREF_CODEGEN_UNUSED_LOCAL= "org.eclipse.jdt.core.compiler.codegen.unusedLocal"; //$NON-NLS-1$
private static final String PREF_CODEGEN_TARGET_PLATFORM= "org.eclipse.jdt.core.compiler.codegen.targetPlatform"; //$NON-NLS-1$
private static final String PREF_PB_UNREACHABLE_CODE= "org.eclipse.jdt.core.compiler.problem.unreachableCode"; //$NON-NLS-1$
private static final String PREF_PB_INVALID_IMPORT= "org.eclipse.jdt.core.compiler.problem.invalidImport"; //$NON-NLS-1$
private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= "org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod"; //$NON-NLS-1$
private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= "org.eclipse.jdt.core.compiler.problem.methodWithConstructorName"; //$NON-NLS-1$
private static final String PREF_PB_DEPRECATION= "org.eclipse.jdt.core.compiler.problem.deprecation"; //$NON-NLS-1$
private static final String PREF_PB_HIDDEN_CATCH_BLOCK= "org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock"; //$NON-NLS-1$
private static final String PREF_PB_UNUSED_LOCAL= "org.eclipse.jdt.core.compiler.problem.unusedLocal"; //$NON-NLS-1$
private static final String PREF_PB_UNUSED_PARAMETER= "org.eclipse.jdt.core.compiler.problem.unusedParameter"; //$NON-NLS-1$
private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= "org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation"; //$NON-NLS-1$
private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= "org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral"; //$NON-NLS-1$
private static final String PREF_PB_ASSERT_AS_IDENTIFIER= "org.eclipse.jdt.core.compiler.problem.assertIdentifier"; //$NON-NLS-1$
private static final String PREF_SOURCE_COMPATIBILITY= "org.eclipse.jdt.core.compiler.source"; //$NON-NLS-1$
private static final String PREF_COMPLIANCE= "org.eclipse.jdt.core.compiler.compliance"; //$NON-NLS-1$
private static final String INTR_DEFAULT_COMPLIANCE= "internal.default.compliance"; //$NON-NLS-1$
// values
private static final String GENERATE= "generate"; //$NON-NLS-1$
private static final String DO_NOT_GENERATE= "do not generate"; //$NON-NLS-1$
private static final String PRESERVE= "preserve"; //$NON-NLS-1$
private static final String OPTIMIZE_OUT= "optimize out"; //$NON-NLS-1$
private static final String VERSION_1_1= "1.1"; //$NON-NLS-1$
private static final String VERSION_1_2= "1.2"; //$NON-NLS-1$
private static final String VERSION_1_3= "1.3"; //$NON-NLS-1$
private static final String VERSION_1_4= "1.4"; //$NON-NLS-1$
private static final String ERROR= "error"; //$NON-NLS-1$
private static final String WARNING= "warning"; //$NON-NLS-1$
private static final String IGNORE= "ignore"; //$NON-NLS-1$
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_SOURCE_COMPATIBILITY, PREF_COMPLIANCE
};
}
/**
* Initializes the current options (read from preference store)
*/
public static void initDefaults(IPreferenceStore store) {
Hashtable hashtable= JavaCore.getDefaultOptions();
Hashtable currOptions= JavaCore.getOptions();
String[] allKeys= getAllKeys();
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String defValue= (String) hashtable.get(key);
if (defValue != null) {
store.setDefault(key, defValue);
} else {
JavaPlugin.logErrorMessage("CompilerPreferencePage: value is null: " + key); //$NON-NLS-1$
}
// update the JavaCore options from the pref store
String val= store.getString(key);
if (val != null) {
currOptions.put(key, val);
}
}
JavaCore.setOptions(currOptions);
}
private static class ControlData {
private String fKey;
private String[] fValues;
public ControlData(String key, String[] values) {
fKey= key;
fValues= values;
}
public String getKey() {
return fKey;
}
public String getValue(boolean selection) {
int index= selection ? 0 : 1;
return fValues[index];
}
public String getValue(int index) {
return fValues[index];
}
public int getSelection(String value) {
for (int i= 0; i < fValues.length; i++) {
if (value.equals(fValues[i])) {
return i;
}
}
throw new IllegalArgumentException();
}
}
private Hashtable fWorkingValues;
private ArrayList fCheckBoxes;
private ArrayList fComboBoxes;
private SelectionListener fSelectionListener;
private ArrayList fComplianceControls;
public CompilerPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("CompilerPreferencePage.description")); //$NON-NLS-1$
fWorkingValues= JavaCore.getOptions();
fWorkingValues.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance());
fCheckBoxes= new ArrayList();
fComboBoxes= new ArrayList();
fComplianceControls= new ArrayList();
fSelectionListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
controlChanged(e.widget);
}
};
}
/**
* @see IWorkbenchPreferencePage#init()
*/
public void init(IWorkbench workbench) {
}
/**
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
// added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.COMPILER_PREFERENCE_PAGE);
}
/**
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
TabFolder folder= new TabFolder(parent, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite warningsComposite= createWarningsTabContent(folder);
Composite codeGenComposite= createCodeGenTabContent(folder);
Composite complianceComposite= createComplianceTabContent(folder);
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerPreferencePage.warnings.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_WARNING));
item.setControl(warningsComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerPreferencePage.generation.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE));
item.setControl(codeGenComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerPreferencePage.compliance.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_LIBRARY));
item.setControl(complianceComposite);
validateSettings(null, null);
return folder;
}
private Composite createWarningsTabContent(Composite folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
JavaUIMessages.getString("CompilerPreferencePage.error"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerPreferencePage.warning"), //$NON-NLS-1$
JavaUIMessages.getString("CompilerPreferencePage.ignore") //$NON-NLS-1$
};
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite warningsComposite= new Composite(folder, SWT.NULL);
warningsComposite.setLayout(layout);
Label description= new Label(warningsComposite, SWT.WRAP);
description.setText(JavaUIMessages.getString("CompilerPreferencePage.warnings.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 2;
gd.widthHint= convertWidthInCharsToPixels(60);
description.setLayoutData(gd);
String label= JavaUIMessages.getString("CompilerPreferencePage.pb_unreachable_code.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNREACHABLE_CODE, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_invalid_import.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_INVALID_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_method_naming.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_deprecation.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_hidden_catchblock.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_local.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_parameter.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_synth_access_emul.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_non_externalized_strings.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
return warningsComposite;
}
private Composite createCodeGenTabContent(Composite folder) {
String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE };
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite codeGenComposite= new Composite(folder, SWT.NULL);
codeGenComposite.setLayout(layout);
String label= JavaUIMessages.getString("CompilerPreferencePage.variable_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_LOCAL_VARIABLE_ATTR, generateValues, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.line_number_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_LINE_NUMBER_ATTR, generateValues, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.source_file_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_SOURCE_FILE_ATTR, generateValues, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.codegen_unused_local.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }, 0);
return codeGenComposite;
}
private Composite createComplianceTabContent(Composite folder) {
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite complianceComposite= new Composite(folder, SWT.NULL);
complianceComposite.setLayout(layout);
String[] values34= new String[] { VERSION_1_3, VERSION_1_4 };
String[] values34Labels= new String[] {
JavaUIMessages.getString("CompilerPreferencePage.version13"), //$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.FILL_HORIZONTAL);
gd.horizontalIndent= indent;
Label labelControl= new Label(parent, SWT.NONE);
labelControl.setText(label);
labelControl.setLayoutData(gd);
Combo comboBox= new Combo(parent, SWT.READ_ONLY);
comboBox.setItems(valueLabels);
comboBox.setData(data);
comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
comboBox.addSelectionListener(fSelectionListener);
String currValue= (String)fWorkingValues.get(key);
comboBox.select(data.getSelection(currValue));
fComboBoxes.add(comboBox);
}
private void controlChanged(Widget widget) {
ControlData data= (ControlData) widget.getData();
String newValue= null;
if (widget instanceof Button) {
newValue= data.getValue(((Button)widget).getSelection());
} else if (widget instanceof Combo) {
newValue= data.getValue(((Combo)widget).getSelectionIndex());
} else {
return;
}
fWorkingValues.put(data.getKey(), newValue);
validateSettings(data.getKey(), newValue);
}
private boolean checkValue(String key, String value) {
return value.equals(fWorkingValues.get(key));
}
/* (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)) {
return;
}
} else {
updateComplianceEnableState();
}
updateStatus(getValidation());
}
private IStatus getValidation() {
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;
}
/*
* Update the compliance controls' enable state
*/
private void updateComplianceEnableState() {
boolean enabled= checkValue(INTR_DEFAULT_COMPLIANCE, USER);
for (int i= fComplianceControls.size() - 1; i >= 0; i--) {
Control curr= (Control) fComplianceControls.get(i);
curr.setEnabled(enabled);
}
}
/*
* Set the default compliance values derived from the chosen level
*/
private void updateComplianceDefaultSettings() {
Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE);
if (VERSION_1_3.equals(complianceLevel)) {
fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE);
fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_3);
fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1);
} else if (VERSION_1_4.equals(complianceLevel)) {
fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR);
fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_4);
fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4);
}
updateControls();
}
/*
* Evaluate if the current compliance setting correspond to a default setting
*/
private String getCurrentCompliance() {
Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE);
if ((VERSION_1_3.equals(complianceLevel)
&& checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE)
&& checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_3)
&& checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1))
|| (VERSION_1_4.equals(complianceLevel)
&& checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)
&& checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)
&& checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4))) {
return DEFAULT;
}
return USER;
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
String[] allKeys= getAllKeys();
// preserve other options
// store in JCore and the preferences
Hashtable actualOptions= JavaCore.getOptions();
IPreferenceStore store= getPreferenceStore();
boolean hasChanges= false;
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String val= (String) fWorkingValues.get(key);
String oldVal= (String) actualOptions.get(key);
hasChanges= hasChanges | !val.equals(oldVal);
actualOptions.put(key, val);
store.setValue(key, val);
}
JavaCore.setOptions(actualOptions);
if (hasChanges) {
String title= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.message"); //$NON-NLS-1$
if (MessageDialog.openQuestion(getShell(), title, message)) {
doFullBuild();
}
}
return super.performOk();
}
private void doFullBuild() {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InterruptedException e) {
// cancelled by user
} catch (InvocationTargetException e) {
String title= JavaUIMessages.getString("CompilerPreferencePage.builderror.title"); //$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));
}
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
}
|
11,673 |
Bug 11673 ESC does not cancel Apply when changing compiler options
|
build 20020319 Workbench->Preferences->Java->Compiler 1) Start with the default settings 2) Change "Unused local variables" to "Warning" 3) Hit Apply button 4) Dialog shows up asking if user wants a full rebuild 5) Hit Cancel to exit yes/no dialog 6) Hit cancel to exit preferences 7) Go back to the same preferences page 8) "Unused local variables" was set to "Warning" The expected behaviour was to cancel the dialog (none of the options) and cancel the preferences without modifying anything. It seems that ESC is the same as hitting NO in that dialog.
|
resolved fixed
|
e34c5fc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-22T09:40:25Z | 2002-03-19T20:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaBuilderPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.lang.reflect.InvocationTargetException;
import java.util.Hashtable;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
public class JavaBuilderPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private StringDialogField fResourceFilterField;
private StatusInfo fResourceFilterStatus;
private Hashtable fWorkingValues;
private static final String PREF_RESOURCE_FILTER= "org.eclipse.jdt.core.builder.resourceCopyExclusionFilter"; //$NON-NLS-1$
private static String[] getAllKeys() {
return new String[] {
PREF_RESOURCE_FILTER
};
}
public JavaBuilderPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("JavaBuilderPreferencePage.description")); //$NON-NLS-1$
fWorkingValues= JavaCore.getOptions();
IDialogFieldListener listener= new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
doValidation();
}
};
fResourceFilterField= new StringDialogField();
fResourceFilterField.setDialogFieldListener(listener);
fResourceFilterField.setLabelText(JavaUIMessages.getString("JavaBuilderPreferencePage.filter.label")); //$NON-NLS-1$
updateControls();
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
initializeDialogUnits(parent);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
DialogField resourceFilterLabel= new DialogField();
resourceFilterLabel.setLabelText(JavaUIMessages.getString("JavaBuilderPreferencePage.filter.description")); //$NON-NLS-1$
resourceFilterLabel.doFillIntoGrid(composite, 2);
LayoutUtil.setWidthHint(resourceFilterLabel.getLabelControl(null), convertWidthInCharsToPixels(80));
fResourceFilterField.doFillIntoGrid(composite, 2);
LayoutUtil.setHorizontalGrabbing(fResourceFilterField.getTextControl(null));
LayoutUtil.setWidthHint(fResourceFilterField.getTextControl(null), convertWidthInCharsToPixels(50));
return composite;
}
/**
* Initializes the current options (read from preference store)
*/
public static void initDefaults(IPreferenceStore store) {
Hashtable hashtable= JavaCore.getDefaultOptions();
Hashtable currOptions= JavaCore.getOptions();
String[] allKeys= getAllKeys();
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String defValue= (String) hashtable.get(key);
if (defValue != null) {
store.setDefault(key, defValue);
} else {
JavaPlugin.logErrorMessage("JavaBuilderPreferencePage: value is null: " + key); //$NON-NLS-1$
}
// update the JavaCore options from the pref store
String val= store.getString(key);
if (val != null) {
currOptions.put(key, val);
}
}
JavaCore.setOptions(currOptions);
}
/*
* @see IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
String[] allKeys= getAllKeys();
// preserve other options
// store in JCore and the preferences
Hashtable actualOptions= JavaCore.getOptions();
IPreferenceStore store= getPreferenceStore();
boolean hasChanges= false;
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String val= (String) fWorkingValues.get(key);
String oldVal= (String) actualOptions.get(key);
hasChanges= hasChanges | !val.equals(oldVal);
actualOptions.put(key, val);
store.setValue(key, val);
}
JavaCore.setOptions(actualOptions);
if (hasChanges) {
String title= JavaUIMessages.getString("JavaBuilderPreferencePage.needsbuild.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("JavaBuilderPreferencePage.needsbuild.message"); //$NON-NLS-1$
if (MessageDialog.openQuestion(getShell(), title, message)) {
doFullBuild();
}
}
return super.performOk();
}
private void doValidation() {
IStatus status= validateResourceFilters();
updateStatus(status);
}
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().trim();
}
return res;
}
private IStatus validateResourceFilters() {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
String text= fResourceFilterField.getText();
String[] filters= getFilters(text);
for (int i= 0; i < filters.length; i++) {
String fileName= filters[i].replace('*', 'x');
IStatus status= workspace.validateName(fileName, IResource.FILE);
if (status.matches(IStatus.ERROR)) {
String message= JavaUIMessages.getFormattedString("JavaBuilderPreferencePage.filter.invalidsegment.error", status.getMessage()); //$NON-NLS-1$
return new StatusInfo(IStatus.ERROR, message);
}
}
StringBuffer buf= new StringBuffer();
for (int i= 0; i < filters.length; i++) {
if (i > 0) {
buf.append(',');
}
buf.append(filters[i]);
}
fWorkingValues.put(PREF_RESOURCE_FILTER, buf.toString());
return new StatusInfo();
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
private void doFullBuild() {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InterruptedException e) {
// cancelled by user
} catch (InvocationTargetException e) {
String title= JavaUIMessages.getString("JavaBuilderPreferencePage.builderror.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("JavaBuilderPreferencePage.builderror.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fWorkingValues= JavaCore.getDefaultOptions();
updateControls();
doValidation();
super.performDefaults();
}
private void updateControls() {
// update the UI
String[] filters= getFilters((String) fWorkingValues.get(PREF_RESOURCE_FILTER));
StringBuffer buf= new StringBuffer();
for (int i= 0; i < filters.length; i++) {
if (i > 0) {
buf.append(", "); //$NON-NLS-1$
}
buf.append(filters[i]);
}
fResourceFilterField.setText(buf.toString());
}
}
|
13,242 |
Bug 13242 quick fix: method name not offered
|
void d(){ class D{ void fs(){ dsss(); //error }; } } d is not offered as a fix
|
resolved fixed
|
119bb95
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-22T10:13:35Z | 2002-04-10T12:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NameMatcher.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
public class NameMatcher {
/**
* Returns a similarity value of the two names.
* The range of is from 0 to 256. no similarity is negative
*/
public static boolean isSimilarName(String name1, String name2) {
return getSimilarity(name1, name2) >= 0;
}
/**
* Returns a similarity value of the two names.
* The range of is from 0 to 256. no similarity is negative
*/
public static int getSimilarity(String name1, String name2) {
if (name1.length() > name2.length()) {
String tmp= name1;
name1= name2;
name2= tmp;
}
int name1len= name1.length();
int name2len= name2.length();
int nMatched= 0;
int i= 0;
while (i < name1len && isSimilarChar(name1.charAt(i), name2.charAt(i))) {
i++;
nMatched++;
}
int k= name1len;
int diff= name2len - name1len;
while (k > i && isSimilarChar(name1.charAt(k - 1), name2.charAt(k + diff - 1))) {
k--;
nMatched++;
}
if (name2len - nMatched > nMatched) {
return -1;
}
int tolerance= name1len / 4 + 1;
return (tolerance - (k - i)) * 256 / tolerance;
}
private static boolean isSimilarChar(char ch1, char ch2) {
return Character.toLowerCase(ch1) == Character.toLowerCase(ch2);
}
private static void test(String name1, String name2) {
int sim= getSimilarity(name1, name2);
System.out.println(name1 + " - " + name2 + " : " + sim); //$NON-NLS-1$ //$NON-NLS-2$
}
public static void main(String[] arguments) {
test("runner", "gunner"); //$NON-NLS-1$ //$NON-NLS-2$
test("rundner", "gunner"); //$NON-NLS-1$ //$NON-NLS-2$
test("rundner", "rund"); //$NON-NLS-1$ //$NON-NLS-2$
test("test", "rund"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
|
13,269 |
Bug 13269 Incorrect operation order in jarpackager
| null |
resolved fixed
|
7a8abf9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-22T10:26:34Z | 2002-04-10T14:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionWriter;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.ui.jarpackager.JarWriter;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaStatusConstants;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IJarExportRunnable {
private static class MessageMultiStatus extends MultiStatus {
MessageMultiStatus(String pluginId, int code, String message, Throwable exception) {
super(pluginId, code, message, exception);
}
/*
* allows to change the message
*/
protected void setMessage(String message) {
super.setMessage(message);
}
}
private static final String COMPILER_SOURCE_FILE_ATTR = "org.eclipse.jdt.core.compiler.debug.sourceFile"; //$NON-NLS-1$
private JarWriter fJarWriter;
private JarPackageData fJarPackage;
private JarPackageData[] fJarPackages;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private Set fExportedClassContainers;
private MessageMultiStatus fStatus;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData jarPackage, Shell parent) {
this(new JarPackageData[] {jarPackage}, parent);
}
/**
* Creates an instance of this class.
*
* @param jarPackages an array with JAR package data objects
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData[] jarPackages, Shell parent) {
this(parent);
fJarPackages= jarPackages;
}
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fStatus= new MessageMultiStatus(JavaPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
}
protected void addToStatus(CoreException ex) {
IStatus status= ex.getStatus();
int severity= status.getSeverity();
if (fJarPackage == null || severity == IStatus.INFO || (severity == IStatus.ERROR && fJarPackage.logErrors()) || (severity == IStatus.WARNING && fJarPackage.logWarnings())) {
String message= ex.getLocalizedMessage();
if (message == null || message.length() < 1) {
message= JarPackagerMessages.getString("JarFileExportOperation.coreErrorDuringExport"); //$NON-NLS-1$
status= new Status(status.getSeverity(), status.getPlugin(), status.getCode(), message, ex);
}
fStatus.add(status);
}
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addWarning(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logWarnings())
fStatus.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logErrors())
fStatus.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return count;
}
}
else
resource= (IResource)element;
if (resource.getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)resource);
}
return count;
}
private int getTotalChildCount(IContainer container) {
IResource[] members;
try {
members= container.members();
} catch (CoreException ex) {
return 0;
}
int count= 0;
for (int i= 0; i < members.length; i++) {
if (members[i].getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)members[i]);
}
return count;
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= findPackageFragmentRoot(jProject, resource.getFullPath().removeLastSegments(1));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
if (mustUseSourceFolderHierarchy() && !pkgRoot.getElementName().equals(pkgRoot.DEFAULT_PACKAGEROOT_PATH))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else if (element instanceof IPackageFragment)
exportPackageFragment(progressMonitor, (IPackageFragment)element);
else
exportContainer(progressMonitor, (IContainer)resource);
}
private void exportPackageFragment(IProgressMonitor progressMonitor, IPackageFragment pkgFragment) throws java.lang.InterruptedException {
Object[] children;
try {
children= pkgFragment.getChildren();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
children= pkgFragment.getNonJavaResources();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", pkgFragment.toString()), e); //$NON-NLS-1$
}
}
private void exportContainer(IProgressMonitor progressMonitor, IContainer container) throws java.lang.InterruptedException {
if (container.getType() == IResource.FOLDER && isOutputFolder((IFolder)container))
return;
IResource[] children= null;
try {
children= container.members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", container.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private IPackageFragmentRoot findPackageFragmentRoot(IJavaProject jProject, IPath path) throws JavaModelException {
if (jProject == null || path == null || path.segmentCount() <= 0)
return null;
IPackageFragmentRoot pkgRoot= jProject.findPackageFragmentRoot(path);
if (pkgRoot != null)
return pkgRoot;
else
return findPackageFragmentRoot(jProject, path.removeLastSegments(1));
}
private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
boolean isNonJavaResource= !isInJavaProject || pkgRoot == null;
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == pkgRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", destinationPath.toString())); //$NON-NLS-1$
fJarWriter.write((IFile) resource, destinationPath);
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
private boolean isOutputFolder(IFolder folder) {
try {
IJavaProject javaProject= JavaCore.create(folder.getProject());
IPath outputFolderPath= javaProject.getOutputLocation();
return folder.getFullPath().equals(outputFolderPath);
} catch (JavaModelException ex) {
return false;
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", classFilePath.toString())); //$NON-NLS-1$
fJarWriter.write(file, classFilePath);
}
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
fExportedClassContainers= new HashSet(10);
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++)
exportElement(fJarPackage.getElements()[i], progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
// Allow JAR Package to provide its own strategy
IFile[] classFiles= fJarPackage.findClassfilesFor(file);
if (classFiles != null)
return Arrays.asList(classFiles).iterator();
if (!isJavaFile(file))
return Collections.EMPTY_LIST.iterator();
IPath outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
// Java CU - search files with .class ending
boolean hasErrors= hasCompileErrors(file);
boolean hasWarnings= hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fExportedClassContainers.contains(classContainer))
return Collections.EMPTY_LIST.iterator();
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
if (fJavaNameToClassFilesMap == null) {
// Could not fully build map. fallback is to export whole directory
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.missingSourceFileAttributeExportedAll", classContainer.getLocation().toFile()); //$NON-NLS-1$
addWarning(msg, null);
fExportedClassContainers.add(classContainer);
return getClassesIn(classContainer);
}
fClassFilesMapContainer= classContainer;
}
ArrayList classFileList= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFileList == null || classFileList.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFileList.iterator();
}
private Iterator getClassesIn(IContainer classContainer) throws CoreException {
IResource[] resources= classContainer.members();
List files= new ArrayList(resources.length);
for (int i= 0; i < resources.length; i++)
if (resources[i].getType() == IResource.FILE && isClassFile(resources[i]))
files.add(resources[i]);
return files.iterator();
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (!isCompilerGeneratingSourceFileAttribute())
return null;
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
if (cfReader.sourceFileName() == null) {
/*
* Can't fully build the map because one or more
* class file does not contain the name of its
* source file.
*/
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", classFile.getLocation().toFile()), null); //$NON-NLS-1$
return null;
}
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* The result is a status object containing individual
* status objects.
*
* @return the status of this operation
*/
public IStatus getStatus() {
String message= null;
switch (fStatus.getSeverity()) {
case IStatus.OK:
message= ""; //$NON-NLS-1$
break;
case IStatus.INFO:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithInfo"); //$NON-NLS-1$
break;
case IStatus.WARNING:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"); //$NON-NLS-1$
break;
case IStatus.ERROR:
if (fJarPackages.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
break;
default:
// defensive code in case new severity is defined
message= ""; //$NON-NLS-1$
break;
}
fStatus.setMessage(message);
return fStatus;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.areErrorsExported())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int count= fJarPackages.length;
progressMonitor.beginTask("", count); //$NON-NLS-1$
try {
for (int i= 0; i < count; i++) {
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1);
fJarPackage= fJarPackages[i];
if (fJarPackage != null)
singleRun(subProgressMonitor);
}
} finally {
progressMonitor.done();
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
int totalWork= countSelectedElements();
if (!isAutoBuilding() && fJarPackage.isBuildingIfNeeded()) {
int subMonitorTicks= totalWork/10;
totalWork += subMonitorTicks;
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, subMonitorTicks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
buildProjects(subProgressMonitor);
} else
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
fJarWriter= fJarPackage.createJarWriter(fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (CoreException ex) {
addToStatus(ex);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (CoreException ex) {
addToStatus(ex);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getElements() == null || fJarPackage.getElements().length == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isManifestAccessible()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
IFile[] unsavedFiles= getUnsavedFiles();
if (unsavedFiles.length > 0)
return saveModifiedResourcesIfUserConfirms(unsavedFiles);
return true;
}
/**
* Returns the files which are not saved and which are
* part of the files being exported.
*
* @return an array of unsaved files
*/
private IFile[] getUnsavedFiles() {
IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors();
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
List selection= JarPackagerUtil.asResources(fJarPackage.getElements());
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (selection.contains(dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[])unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* Asks the user to confirm to save the modified resources.
*
* @return true if user pressed OK.
*/
private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) {
if (dirtyFiles == null || dirtyFiles.length == 0)
return true;
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(fParentShell, dirtyFiles);
final int[] intResult= new int[1];
Runnable runnable= new Runnable() {
public void run() {
intResult[0]= dlg.open();
}
};
display.syncExec(runnable);
return intResult[0] == IDialogConstants.OK_ID;
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles))
return saveModifiedResources(dirtyFiles);
// Report unsaved files
for (int i= 0; i < dirtyFiles.length; i++)
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFiles[i].getFullPath()), null); //$NON-NLS-1$
return false;
}
/**
* Save all of the editors in the workbench.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) {
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
final boolean[] retVal= new boolean[1];
Runnable runnable= new Runnable() {
public void run() {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IWorkspaceDescription description= workspace.getDescription();
boolean autoBuild= description.isAutoBuilding();
description.setAutoBuilding(false);
try {
workspace.setDescription(description);
// This save operation can not be canceled.
try {
new ProgressMonitorDialog(fParentShell).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
retVal[0]= true;
} finally {
description.setAutoBuilding(autoBuild);
workspace.setDescription(description);
}
} catch (InvocationTargetException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
} catch (InterruptedException ex) {
Assert.isTrue(false); // Can't happen. Operation isn't cancelable.
retVal[0]= false;
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
}
}
};
display.syncExec(runnable);
return retVal[0];
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= JavaPlugin.getDirtyEditors();
pm.beginTask(JarPackagerMessages.getString("JarFileExportOperation.savingModifiedResources"), editorsToSave.length); //$NON-NLS-1$
try {
List dirtyFilesList= Arrays.asList(dirtyFiles);
for (int i= 0; i < editorsToSave.length; i++) {
if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)editorsToSave[i].getEditorInput()).getFile();
if (dirtyFilesList.contains((dirtyFile)))
editorsToSave[i].doSave(new SubProgressMonitor(pm, 1));
}
pm.worked(1);
}
} finally {
pm.done();
}
}
};
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
IJarDescriptionWriter writer= fJarPackage.createJarDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
writer.write(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile= fJarPackage.getDescriptionFile();
if (descriptionFile.isAccessible() && (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, descriptionFile.getFullPath().toString())))
descriptionFile.setContents(fileInput, true, true, null);
else {
descriptionFile.create(fileInput, true, null);
}
} finally {
if (fileInput != null)
fileInput.close();
if (writer != null)
writer.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
IFile manifestFile= fJarPackage.getManifestFile();
if (manifestFile.isAccessible() && (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, manifestFile.getFullPath().toString())))
manifestFile.setContents(fileInput, true, true, null);
else {
manifestFile.create(fileInput, true, null);
}
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
private boolean isAutoBuilding() {
return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
}
private boolean isCompilerGeneratingSourceFileAttribute() {
Object value= JavaCore.getOptions().get(COMPILER_SOURCE_FILE_ATTR);
if (value instanceof String)
return "generate".equalsIgnoreCase((String)value); //$NON-NLS-1$
else
return true; // default
}
private void buildProjects(IProgressMonitor progressMonitor) {
Set builtProjects= new HashSet(10);
Object[] elements= fJarPackage.getElements();
for (int i= 0; i < elements.length; i++) {
IProject project= null;
Object element= elements[i];
if (element instanceof IResource)
project= ((IResource)element).getProject();
else if (element instanceof IJavaElement)
project= ((IJavaElement)element).getJavaProject().getProject();
if (project != null && !builtProjects.contains(project)) {
try {
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, progressMonitor);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringProjectBuild", project.getFullPath()); //$NON-NLS-1$
addError(message, ex);
} finally {
// don't try to build same project a second time even if it failed
builtProjects.add(project);
}
}
}
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileErrors(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
return true;
}
return false;
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileWarnings(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_WARNING)
return true;
}
return false;
}
private boolean mustUseSourceFolderHierarchy() {
return fJarPackage.useSourceFolderHierarchy() && fJarPackage.areJavaFilesExported() && !fJarPackage.areClassFilesExported();
}
}
|
12,780 |
Bug 12780 JAR which is generated inside workspace does not appear
|
Summary says it all. It is there after a refresh from local.
|
resolved fixed
|
5201074
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-22T12:37:53Z | 2002-04-04T14:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/jarpackager/JarWriter.java
| |
12,676 |
Bug 12676 Code assist for type in javadoc does not show type itself
|
1. Open CU for X 2. add Javadoc for class X 3. enter @see 4. enter SPACE 5. open code assist ==> X not in list though X#... is allowed
|
resolved fixed
|
fafeb67
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-22T13:45:07Z | 2002-04-03T13:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocCompletionEvaluator.java
|
package org.eclipse.jdt.internal.ui.text.javadoc;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jdt.core.CompletionRequestorAdapter;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposal;
import org.eclipse.jdt.internal.ui.text.java.ProposalInfo;
public class JavaDocCompletionEvaluator {
protected final static String[] fgTagProposals= {
"@author", //$NON-NLS-1$
"@deprecated", //$NON-NLS-1$
"@exception", //$NON-NLS-1$
"@link", //$NON-NLS-1$
"@param", //$NON-NLS-1$
"@return", //$NON-NLS-1$
"@see", "@serial", "@serialData", "@serialField", "@since", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$
"@throws", //$NON-NLS-1$
"@version" //$NON-NLS-1$
};
protected final static String[] fgHTMLProposals= {
"<code>", "</code>", //$NON-NLS-2$ //$NON-NLS-1$
"<br>", //$NON-NLS-1$
"<b>", "</b>", //$NON-NLS-2$ //$NON-NLS-1$
"<i>", "</i>", //$NON-NLS-2$ //$NON-NLS-1$
"<pre>", "</pre>" //$NON-NLS-2$ //$NON-NLS-1$
};
private ICompilationUnit fCompilationUnit;
private IDocument fDocument;
private int fCurrentPos;
private int fCurrentLength;
private JavaElementLabelProvider fLabelProvider;
private List fResult;
private boolean fRestrictToMatchingCase;
public JavaDocCompletionEvaluator(ICompilationUnit cu, IDocument doc, int pos, int length) {
fCompilationUnit= cu;
fDocument= doc;
fCurrentPos= pos;
fCurrentLength= length;
fResult= new ArrayList();
fRestrictToMatchingCase= false;
}
/**
* Tells this evaluator to restrict is proposals to those
* starting with matching cases.
*
* @param restrict <code>true</code> if proposals should be restricted
*/
public void restrictProposalsToMatchingCases(boolean restrict) {
fRestrictToMatchingCase= restrict;
}
private static boolean isWordPart(char ch) {
return Character.isJavaIdentifierPart(ch) || (ch == '#') || (ch == '.') || (ch == '/');
}
private static int findCharBeforeWord(IDocument doc, int lineBeginPos, int pos) {
int currPos= pos - 1;
if (currPos > lineBeginPos) {
try {
while (currPos > lineBeginPos && isWordPart(doc.getChar(currPos))) {
currPos--;
}
return currPos;
} catch (BadLocationException e) {
}
}
return pos;
}
private static int findLastWhitespace(IDocument doc, int lineBeginPos, int pos) {
try {
int currPos= pos - 1;
while (currPos >= lineBeginPos && Character.isWhitespace(doc.getChar(currPos))) {
currPos--;
}
return currPos + 1;
} catch (BadLocationException e) {
}
return pos;
}
private static int findClosingCharacter(IDocument doc, int pos, int end, char endChar) throws BadLocationException {
int curr= pos;
while (curr < end && (doc.getChar(curr) != endChar)) {
curr++;
}
if (curr < end) {
return curr + 1;
}
return pos;
}
private static int findReplaceEndPos(IDocument doc, String newText, String oldText, int pos) {
if (oldText.length() == 0 || oldText.equals(newText)) {
return pos;
}
try {
IRegion lineInfo= doc.getLineInformationOfOffset(pos);
int end= lineInfo.getOffset() + lineInfo.getLength();
if (newText.endsWith(">")) { //$NON-NLS-1$
// for html, search the tag end character
return findClosingCharacter(doc, pos, end, '>');
} else {
char ch= 0;
int pos1= pos;
while (pos1 < end && Character.isJavaIdentifierPart(ch= doc.getChar(pos1))) {
pos1++;
}
if (pos1 < end) {
// for method references, search the closing bracket
if ((ch == '(') && newText.endsWith(")")) { //$NON-NLS-1$
return findClosingCharacter(doc, pos1, end, ')');
}
}
return pos1;
}
} catch (BadLocationException e) {
e.printStackTrace();
}
return pos;
}
public JavaCompletionProposal[] computeProposals() throws JavaModelException {
fLabelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_POST_QUALIFIED | JavaElementLabelProvider.SHOW_PARAMETERS);
try {
evalProposals();
return (JavaCompletionProposal[]) fResult.toArray(new JavaCompletionProposal[fResult.size()]);
} finally {
fLabelProvider.dispose();
fResult.clear();
}
}
private void evalProposals() throws JavaModelException {
try {
IRegion info= fDocument.getLineInformationOfOffset(fCurrentPos);
int lineBeginPos= info.getOffset();
int word1Begin= findCharBeforeWord(fDocument, lineBeginPos, fCurrentPos);
if (word1Begin == fCurrentPos) {
return;
}
char firstChar= fDocument.getChar(word1Begin);
if (firstChar == '@') {
String prefix= fDocument.get(word1Begin, fCurrentPos - word1Begin);
addProposals(prefix, fgTagProposals, JavaPluginImages.IMG_OBJS_JAVADOCTAG);
return;
} else if (firstChar == '<') {
String prefix= fDocument.get(word1Begin, fCurrentPos - word1Begin);
addProposals(prefix, fgHTMLProposals, JavaPluginImages.IMG_OBJS_HTMLTAG);
return;
} else if (!Character.isWhitespace(firstChar)) {
return;
}
String prefix= fDocument.get(word1Begin + 1, fCurrentPos - word1Begin - 1);
// could be a composed java doc construct (@param, @see ...)
int word2End= findLastWhitespace(fDocument, lineBeginPos, word1Begin);
if (word2End != lineBeginPos) {
// find the word before the prefix
int word2Begin= findCharBeforeWord(fDocument, lineBeginPos, word2End);
if (fDocument.getChar(word2Begin) == '@') {
String tag= fDocument.get(word2Begin, word2End - word2Begin);
if (addArgumentProposals(tag, prefix)) {
return;
}
}
}
addAllTags(prefix);
} catch (BadLocationException e) {
// ignore
}
}
private boolean prefixMatches(String prefix, String proposal) {
if (fRestrictToMatchingCase) {
return proposal.startsWith(prefix);
} else if (proposal.length() >= prefix.length()) {
return prefix.equalsIgnoreCase(proposal.substring(0, prefix.length()));
}
return false;
}
private void addAllTags(String prefix) {
String jdocPrefix= "@" + prefix; //$NON-NLS-1$
for (int i= 0; i < fgTagProposals.length; i++) {
String curr= fgTagProposals[i];
if (prefixMatches(jdocPrefix, curr)) {
fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG), null));
}
}
String htmlPrefix= "<" + prefix; //$NON-NLS-1$
for (int i= 0; i < fgHTMLProposals.length; i++) {
String curr= fgHTMLProposals[i];
if (prefixMatches(htmlPrefix, curr)) {
fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_HTMLTAG), null));
}
}
}
private void addProposals(String prefix, String[] choices, String imageName) {
for (int i= 0; i < choices.length; i++) {
String curr= choices[i];
if (prefixMatches(prefix, curr)) {
fResult.add(createCompletion(curr, prefix, curr, JavaPluginImages.get(imageName), null));
}
}
}
private void addProposals(String prefix, IJavaElement[] choices) {
for (int i= 0; i < choices.length; i++) {
IJavaElement elem= choices[i];
String curr= getReplaceString(elem);
if (prefixMatches(prefix, curr)) {
ProposalInfo info= (elem instanceof IMember) ? new ProposalInfo((IMember) elem) : null;
fResult.add(createCompletion(curr, prefix, fLabelProvider.getText(elem), fLabelProvider.getImage(elem), info));
}
}
}
private String getReplaceString(IJavaElement elem) {
if (elem instanceof IMethod) {
IMethod meth= (IMethod)elem;
StringBuffer buf= new StringBuffer();
buf.append(meth.getElementName());
buf.append('(');
String[] types= meth.getParameterTypes();
int last= types.length - 1;
for (int i= 0; i <= last; i++) {
buf.append(Signature.toString(types[i]));
if (i != last) {
buf.append(", "); //$NON-NLS-1$
}
}
buf.append(')');
return buf.toString();
} else {
return elem.getElementName();
}
}
/**
* Returns true if case is handeled
*/
private boolean addArgumentProposals(String tag, String argument) throws JavaModelException {
if ("@see".equals(tag) || "@link".equals(tag)) { //$NON-NLS-2$ //$NON-NLS-1$
evalSeeTag(argument);
return true;
} else if ("@param".equals(tag)) { //$NON-NLS-1$
IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos);
if (elem instanceof IMethod) {
String[] names= ((IMethod)elem).getParameterNames();
addProposals(argument, names, JavaPluginImages.IMG_MISC_DEFAULT);
}
return true;
} else if ("@throws".equals(tag) || "@exception".equals(tag)) { //$NON-NLS-2$ //$NON-NLS-1$
IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos);
if (elem instanceof IMethod) {
String[] exceptions= ((IMethod)elem).getExceptionTypes();
for (int i= 0; i < exceptions.length; i++) {
String curr= Signature.toString(exceptions[i]);
if (prefixMatches(argument, curr)) {
fResult.add(createCompletion(curr, argument, curr, JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS), null));
}
}
}
return true;
} else if ("@serialData".equals(tag)) { //$NON-NLS-1$
IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos);
if (elem instanceof IField) {
String name= ((IField)elem).getElementName();
fResult.add(createCompletion(name, argument, name, fLabelProvider.getImage(elem), null));
}
return true;
}
return false;
}
private void evalSeeTag(String arg) throws JavaModelException {
int wordStart= fCurrentPos - arg.length();
int pidx= arg.indexOf('#');
if (pidx == -1) {
evalTypeNameCompletions(wordStart);
} else {
IType parent= null;
if (pidx > 0) {
// method or field
parent= getTypeNameResolve(wordStart, wordStart + pidx);
} else {
// '@see #foo'
IJavaElement elem= fCompilationUnit.getElementAt(wordStart);
if (elem != null) {
parent= (IType) elem.getAncestor(IJavaElement.TYPE);
}
}
if (parent != null) {
int nidx= arg.indexOf('(', pidx);
if (nidx == -1) {
nidx= arg.length();
}
String prefix= arg.substring(pidx + 1, nidx);
addProposals(prefix, parent.getMethods());
addProposals(prefix, parent.getFields());
}
}
}
private void evalTypeNameCompletions(int wordStart) throws JavaModelException {
ICompilationUnit preparedCU= createPreparedCU(wordStart, fCurrentPos);
if (preparedCU != null) {
CompletionRequestorAdapter requestor= new CompletionRequestorAdapter() {
public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int start, int end, int severity) {
fResult.add(createSeeTypeCompletion(true, start, end, completionName, className, packageName));
}
public void acceptInterface(char[] packageName, char[] interfaceName, char[] completionName, int modifiers, int start, int end, int severity) {
fResult.add(createSeeTypeCompletion(false, start, end, completionName, interfaceName, packageName));
}
public void acceptType(char[] packageName, char[] typeName, char[] completionName, int start, int end, int severity) {
fResult.add(createSeeTypeCompletion(true, start, end, completionName, typeName, packageName));
}
};
try {
preparedCU.codeComplete(fCurrentPos, requestor);
} finally {
preparedCU.destroy();
}
}
}
private IType getTypeNameResolve(int wordStart, int wordEnd) throws JavaModelException {
ICompilationUnit preparedCU= createPreparedCU(wordStart, wordEnd);
if (preparedCU != null) {
try {
IJavaElement[] elements= preparedCU.codeSelect(wordStart, wordEnd - wordStart);
if (elements != null && elements.length == 1 && elements[0] instanceof IType) {
return (IType) elements[0];
}
} finally {
preparedCU.getBuffer().setContents(fCompilationUnit.getBuffer().getCharacters());
preparedCU.destroy();
}
}
return null;
}
private ICompilationUnit createPreparedCU(int wordStart, int wordEnd) throws JavaModelException {
IJavaElement elem= fCompilationUnit.getElementAt(fCurrentPos);
if (!(elem instanceof ISourceReference)) {
return null;
}
int startpos= ((ISourceReference)elem).getSourceRange().getOffset();
char[] content= (char[]) fCompilationUnit.getBuffer().getCharacters().clone();
if (elem instanceof IType && (((IType)elem).getDeclaringType() == null) && (wordStart + 6 < content.length)) {
content[startpos++]= 'i'; content[startpos++]= 'm'; content[startpos++]= 'p';
content[startpos++]= 'o'; content[startpos++]= 'r'; content[startpos++]= 't';
}
if (wordStart < content.length) {
for (int i= startpos; i < wordStart; i++) {
content[i]= ' ';
}
}
ICompilationUnit cu= fCompilationUnit;
if (cu.isWorkingCopy()) {
cu= (ICompilationUnit) cu.getOriginalElement();
}
/*
* Explicitly create a new working copy.
*/
ICompilationUnit newCU= (ICompilationUnit) cu.getWorkingCopy();
newCU.getBuffer().setContents(content);
return newCU;
}
private JavaCompletionProposal createCompletion(String newText, String oldText, String labelText, Image image, ProposalInfo proposalInfo) {
int offset= fCurrentPos - oldText.length();
int length= fCurrentLength + oldText.length();
if (fCurrentLength == 0)
length= findReplaceEndPos(fDocument, newText, oldText, fCurrentPos) - offset;
JavaCompletionProposal proposal= new JavaCompletionProposal(newText, offset, length, image, labelText, 0);
proposal.setProposalInfo(proposalInfo);
proposal.setTriggerCharacters( new char[] { '#' });
return proposal;
}
private JavaCompletionProposal createSeeTypeCompletion(boolean isClass, int start, int end, char[] completion, char[] typeName, char[] containerName) {
ProposalInfo proposalInfo= new ProposalInfo(fCompilationUnit.getJavaProject(), containerName, typeName);
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(typeName);
if (containerName != null) {
nameBuffer.append(" - "); //$NON-NLS-1$
if (containerName.length > 0) {
nameBuffer.append(containerName);
} else {
nameBuffer.append(JavaDocMessages.getString("CompletionEvaluator.default_package")); //$NON-NLS-1$
}
}
String imageKey= isClass ? JavaPluginImages.IMG_OBJS_CLASS : JavaPluginImages.IMG_OBJS_INTERFACE;
int compLen= completion.length;
if (compLen > 0 && completion[compLen - 1] == ';') {
compLen--; // remove the semicolon from import proposals
}
JavaCompletionProposal proposal= new JavaCompletionProposal(new String(completion, 0, compLen), start, end - start, JavaPluginImages.get(imageKey), nameBuffer.toString(), 0);
proposal.setProposalInfo(proposalInfo);
proposal.setTriggerCharacters( new char[] { '#' });
return proposal;
}
}
|
13,196 |
Bug 13196 [Browsing] Consequences of changes
|
From the user's perspective, there is an unexpected behavioral difference when manipulation source in the type hierarchy and in the method list of the browser perspective. 1) open Java Browsing Perspective 2) select a type 3) select a method in the method list view 4) delete the method (context menu of the method list view) -> editor becomes dirty (ok) 5) select another type 6) open type hierarchy on this type, dock the hierachy view 7) select a method in the method list view 8) select the same method in the hierarchy view 9) delete the method (context menu of the hierarchy view) -> method is deleted on file system, type list view, method list view, editor are all cleared Note: This is not the case when the editor is dirty. Then both manipulations behave the same. Expected behavior: If there is an open editor, all manipulations should just work on the working copy shown in the editor.
|
resolved fixed
|
2f621a6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-22T14:14:38Z | 2002-04-10T12:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/MethodsViewer.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Table;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GenerateGroup;
import org.eclipse.jdt.internal.ui.actions.OpenJavaElementAction;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.util.SelectionUtil;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.MemberFilterActionGroup;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider;
/**
* Method viewer shows a list of methods of a input type.
* Offers filter actions.
* No dependency to the type hierarchy view
*/
public class MethodsViewer extends ProblemTableViewer {
private static final String TAG_SHOWINHERITED= "showinherited"; //$NON-NLS-1$
private static final String TAG_VERTICAL_SCROLL= "mv_vertical_scroll"; //$NON-NLS-1$
private static final int LABEL_BASEFLAGS= StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS;
private MemberFilterActionGroup fMemberFilterActionGroup;
private JavaUILabelProvider fLabelProvider;
private OpenJavaElementAction fOpen;
private ShowInheritedMembersAction fShowInheritedMembersAction;
private ContextMenuGroup[] fStandardGroups;
public MethodsViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) {
super(new Table(parent, SWT.MULTI));
fLabelProvider= new StandardJavaUILabelProvider(
StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS,
StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS,
StandardJavaUILabelProvider.getAdornmentProviders(true, new HierarchyAdornmentProvider(lifeCycle))
);
setLabelProvider(new DecoratingLabelProvider(fLabelProvider, PlatformUI.getWorkbench().getDecoratorManager()));
setContentProvider(new MethodsContentProvider(lifeCycle));
fOpen= new OpenJavaElementAction(this);
addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
fOpen.run();
}
});
fMemberFilterActionGroup= new MemberFilterActionGroup(this, "HierarchyMethodView"); //$NON-NLS-1$
fShowInheritedMembersAction= new ShowInheritedMembersAction(this, false);
showInheritedMethods(false);
fStandardGroups= new ContextMenuGroup[] {
new JavaSearchGroup(), new GenerateGroup()
};
setSorter(new JavaElementSorter());
JavaUIHelp.setHelp(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
}
/**
* Show inherited methods
*/
public void showInheritedMethods(boolean on) {
MethodsContentProvider cprovider= (MethodsContentProvider) getContentProvider();
try {
getTable().setRedraw(false);
cprovider.showInheritedMethods(on);
fShowInheritedMembersAction.setChecked(on);
if (fLabelProvider != null) {
if (on) {
fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() | JavaElementLabels.ALL_POST_QUALIFIED);
} else {
fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() & (-1 ^ JavaElementLabels.ALL_POST_QUALIFIED));
}
refresh();
}
} catch (JavaModelException e) {
ExceptionHandler.handle(e, getControl().getShell(), TypeHierarchyMessages.getString("MethodsViewer.toggle.error.title"), TypeHierarchyMessages.getString("MethodsViewer.toggle.error.message")); //$NON-NLS-2$ //$NON-NLS-1$
} finally {
getTable().setRedraw(true);
}
}
/*
* @see Viewer#inputChanged(Object, Object)
*/
protected void inputChanged(Object input, Object oldInput) {
super.inputChanged(input, oldInput);
}
/**
* Returns <code>true</code> if inherited methods are shown.
*/
public boolean isShowInheritedMethods() {
return ((MethodsContentProvider) getContentProvider()).isShowInheritedMethods();
}
/**
* Saves the state of the filter actions
*/
public void saveState(IMemento memento) {
fMemberFilterActionGroup.saveState(memento);
memento.putString(TAG_SHOWINHERITED, String.valueOf(isShowInheritedMethods()));
ScrollBar bar= getTable().getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_VERTICAL_SCROLL, String.valueOf(position));
}
/**
* Restores the state of the filter actions
*/
public void restoreState(IMemento memento) {
fMemberFilterActionGroup.restoreState(memento);
boolean set= Boolean.valueOf(memento.getString(TAG_SHOWINHERITED)).booleanValue();
showInheritedMethods(set);
ScrollBar bar= getTable().getVerticalBar();
if (bar != null) {
Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL);
if (vScroll != null) {
bar.setSelection(vScroll.intValue());
}
}
}
/**
* Attaches a contextmenu listener to the table
*/
public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(menuListener);
Menu menu= menuMgr.createContextMenu(getTable());
getTable().setMenu(menu);
viewSite.registerContextMenu(popupId, menuMgr, this);
}
/**
* Fills up the context menu with items for the method viewer
* Should be called by the creator of the context menu
*/
public void contributeToContextMenu(IMenuManager menu) {
if (fOpen.canActionBeAdded()) {
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpen);
}
ContextMenuGroup.add(menu, fStandardGroups, this);
}
/**
* Fills up the tool bar with items for the method viewer
* Should be called by the creator of the tool bar
*/
public void contributeToToolBar(ToolBarManager tbm) {
tbm.add(fShowInheritedMembersAction);
tbm.add(new Separator());
fMemberFilterActionGroup.contributeToToolBar(tbm);
}
/*
* @see StructuredViewer#handleInvalidSelection(ISelection, ISelection)
*/
protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) {
// on change of input, try to keep selected methods stable by selecting a method with the same
// signature: See #5466
List oldSelections= SelectionUtil.toList(invalidSelection);
List newSelections= SelectionUtil.toList(newSelection);
if (!oldSelections.isEmpty()) {
ArrayList newSelectionElements= new ArrayList(newSelections);
try {
Object[] currElements= getFilteredChildren(getInput());
for (int i= 0; i < oldSelections.size(); i++) {
Object curr= oldSelections.get(i);
if (curr instanceof IMethod && !newSelections.contains(curr)) {
IMethod method= (IMethod) curr;
if (method.exists()) {
IMethod similar= findSimilarMethod(method, currElements);
if (similar != null) {
newSelectionElements.add(similar);
}
}
}
}
newSelection= new StructuredSelection(newSelectionElements);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
setSelection(newSelection);
updateSelection(newSelection);
}
private IMethod findSimilarMethod(IMethod meth, Object[] elements) throws JavaModelException {
String name= meth.getElementName();
String[] paramTypes= meth.getParameterTypes();
boolean isConstructor= meth.isConstructor();
for (int i= 0; i < elements.length; i++) {
Object curr= elements[i];
if (curr instanceof IMethod && JavaModelUtil.isSameMethodSignature(name, paramTypes, isConstructor, (IMethod) curr)) {
return (IMethod) curr;
}
}
return null;
}
}
|
9,891 |
Bug 9891 'show in packages view' - surprising behavior
|
in the editor, when there's no selection or the selection cannot be resolved - 'show in packages view' finds the cu in the packages view. when the selection resolves to sth - it shows the cu that declares the thing the selection resolves to. this is highly surprising - i do not pay any attention to the current selection when using this useful action. these 2 things are really 2 different action - that's how i see it.
|
resolved fixed
|
971fa6e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-22T16:09:38Z | 2002-02-15T10:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/ShowInPackageViewAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart;
/**
* This action reveals the currently selected Java element in the packages
* view. The Java element can be represeented by either
* <ul>
* <li>a text selection inside a Java editor, or </li>
* <li>a structured selection of a view part showing Java elements</li>
* </ul>
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class ShowInPackageViewAction extends SelectionDispatchAction {
private JavaEditor fEditor;
/**
* Creates a new <code>ShowInPackageViewAction</code>.
*
* @param site the site providing context information for this action
*/
public ShowInPackageViewAction(UnifiedSite site) {
super(site);
setText(ActionMessages.getString("ShowInPackageViewAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("ShowInPackageViewAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("ShowInPackageViewAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.SHOW_IN_PACKAGEVIEW_ACTION);
}
/**
* Creates a new <code>ShowInPackageViewAction</code>.
* <p>
* Note: This constructor is for internal use only. Clients should not call this constructor.
* </p>
*/
public ShowInPackageViewAction(JavaEditor editor) {
this(UnifiedSite.create(editor.getEditorSite()));
fEditor= editor;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
setEnabled(fEditor != null);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(checkEnabled(selection));
}
private boolean checkEnabled(IStructuredSelection selection) {
if (selection.size() != 1)
return false;
return selection.getFirstElement() instanceof IJavaElement;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(ITextSelection selection) {
IJavaElement element= SelectionConverter.codeResolveOrInputHandled(fEditor, getShell(), getDialogTitle(), ActionMessages.getString("ShowInPackageViewAction.select_name")); //$NON-NLS-1$
if (element != null)
run(element);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
if (!checkEnabled(selection))
return;
run((IJavaElement)selection.getFirstElement());
}
private void run(IJavaElement element) {
if (element == null)
return;
try {
element= OpenActionUtil.getElementToOpen(element);
if (element == null)
return;
PackageExplorerPart view= PackageExplorerPart.openInActivePerspective();
if (view != null) {
view.selectReveal(new StructuredSelection(element));
return;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
String message= ActionMessages.getString("ShowInPackageViewAction.error.message"); //$NON-NLS-1$
ErrorDialog.openError(getShell(), getDialogTitle(), message, e.getStatus());
}
}
private static String getDialogTitle() {
return ActionMessages.getString("ShowInPackageViewAction.dialog.title"); //$NON-NLS-1$
}
}
|
14,228 |
Bug 14228 Too easy to create duplicate methods
|
Build 20020418 - I was browsing some source (not even actively editing). - Suddenly I noticed there was a squiggle on one of the constructors. - Hover told me that there were two methods (sp) with the same name. - Scrolled down to see that, in fact, I did have another copy of the constructor. Strange. How did this ever compile? - It turns out I must have inadvertently dragged the constructor a little bit in the Outline. - With the new DnD support in the Outline, it is far too easy to create duplicates.
|
resolved fixed
|
7db8bed
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-23T13:43:23Z | 2002-04-19T15:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/SelectionTransferDropAdapter.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
import org.eclipse.jdt.internal.corext.refactoring.Assert;
import org.eclipse.jdt.internal.corext.refactoring.reorg.CopyRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.reorg.DeleteSourceReferencesAction;
import org.eclipse.jdt.internal.ui.reorg.MockUnifiedSite;
import org.eclipse.jdt.internal.ui.reorg.JdtMoveAction;
import org.eclipse.jdt.internal.ui.reorg.ReorgActionFactory;
import org.eclipse.jdt.internal.ui.reorg.SimpleSelectionProvider;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class SelectionTransferDropAdapter extends JdtViewerDropAdapter implements TransferDropTargetListener {
private List fElements;
private MoveRefactoring fMoveRefactoring;
private int fCanMoveElements;
private CopyRefactoring fCopyRefactoring;
private int fCanCopyElements;
public SelectionTransferDropAdapter(StructuredViewer viewer) {
super(viewer, DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND);
}
//---- TransferDropTargetListener interface ---------------------------------------
public Transfer getTransfer() {
return LocalSelectionTransfer.getInstance();
}
//---- Actual DND -----------------------------------------------------------------
public void dragEnter(DropTargetEvent event) {
clear();
super.dragEnter(event);
}
public void dragLeave(DropTargetEvent event) {
clear();
super.dragLeave(event);
}
private void clear() {
fElements= null;
fMoveRefactoring= null;
fCanMoveElements= 0;
fCopyRefactoring= null;
fCanCopyElements= 0;
}
public void validateDrop(Object target, DropTargetEvent event, int operation) {
event.detail= DND.DROP_NONE;
if (fElements == null) {
ISelection s= LocalSelectionTransfer.getInstance().getSelection();
if (!(s instanceof IStructuredSelection))
return;
fElements= ((IStructuredSelection)s).toList();
}
try {
if (operation == DND.DROP_COPY) {
event.detail= handleValidateCopy(target, event);
} else if (operation == DND.DROP_MOVE) {
event.detail= handleValidateMove(target, event);
}
} catch (JavaModelException e){
ExceptionHandler.handle(e, PackagesMessages.getString("SelectionTransferDropAdapter.error.title"), PackagesMessages.getString("SelectionTransferDropAdapter.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
event.detail= DND.DROP_NONE;
}
}
public void drop(Object target, DropTargetEvent event) {
try{
if (event.detail == DND.DROP_MOVE) {
handleDropMove(target, event);
if (! canPasteSourceReferences(target, event))
return;
DeleteSourceReferencesAction delete= ReorgActionFactory.createDeleteSourceReferencesAction(getDragableSourceReferences());
delete.setAskForDeleteConfirmation(false);
delete.setCanDeleteGetterSetter(false);
delete.update();
if (delete.isEnabled())
delete.run();
} else if (event.detail == DND.DROP_COPY) {
handleDropCopy(target, event);
}
} catch (JavaModelException e){
ExceptionHandler.handle(e, PackagesMessages.getString("SelectionTransferDropAdapter.error.title"), PackagesMessages.getString("SelectionTransferDropAdapter.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} finally{
// The drag source listener must not perform any operation
// since this drop adapter did the remove of the source even
// if we moved something.
event.detail= DND.DROP_NONE;
}
}
private int handleValidateMove(Object target, DropTargetEvent event) throws JavaModelException{
if (target == null)
return DND.DROP_NONE;
if (canPasteSourceReferences(target, event))
return DND.DROP_COPY; //XXX for now
if (fMoveRefactoring == null){
fMoveRefactoring= new MoveRefactoring(fElements, JavaPreferencesSettings.getCodeGenerationSettings());
}
if (!canMoveElements())
return DND.DROP_NONE;
if (fMoveRefactoring.isValidDestination(target))
return DND.DROP_MOVE;
else
return DND.DROP_NONE;
}
private boolean canMoveElements() {
if (fCanMoveElements == 0) {
fCanMoveElements= 2;
if (! canActivate(fMoveRefactoring))
fCanMoveElements= 1;
}
return fCanMoveElements == 2;
}
private boolean canActivate(ReorgRefactoring ref){
try{
return ref.checkActivation(new NullProgressMonitor()).isOK();
} catch(JavaModelException e){
ExceptionHandler.handle(e, PackagesMessages.getString("SelectionTransferDropAdapter.error.title"), PackagesMessages.getString("SelectionTransferDropAdapter.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
private void handleDropMove(final Object target, DropTargetEvent event) throws JavaModelException{
if (canPasteSourceReferences(target, event)){
pasteSourceReferences(target, event);
return;
}
new DragNDropMoveAction(new SimpleSelectionProvider(fElements), target).run();
}
private void pasteSourceReferences(final Object target, DropTargetEvent event) {
SelectionDispatchAction pasteAction= ReorgActionFactory.createPasteAction(getDragableSourceReferences(), target);
pasteAction.update();
if (!pasteAction.isEnabled()){
event.detail= DND.DROP_NONE;
return;
}
pasteAction.run();
return;
}
private int handleValidateCopy(Object target, DropTargetEvent event) throws JavaModelException{
if (canPasteSourceReferences(target, event))
return DND.DROP_COPY;
if (fCopyRefactoring == null)
fCopyRefactoring= new CopyRefactoring(fElements);
if (!canCopyElements())
return DND.DROP_NONE;
if (fCopyRefactoring.isValidDestination(target))
return DND.DROP_COPY;
else
return DND.DROP_NONE;
}
private boolean canPasteSourceReferences(Object target, DropTargetEvent event) throws JavaModelException{
ISourceReference[] elements= getDragableSourceReferences();
if (elements.length != fElements.size())
return false;
SelectionDispatchAction pasteAction= ReorgActionFactory.createPasteAction(elements, target);
pasteAction.update();
return pasteAction.isEnabled();
}
private ISourceReference[] getDragableSourceReferences(){
List result= new ArrayList(fElements.size());
for(Iterator iter= fElements.iterator(); iter.hasNext();){
Object each= iter.next();
if (isDragableSourceReferences(each))
result.add(each);
}
return (ISourceReference[])result.toArray(new ISourceReference[result.size()]);
}
private static boolean isDragableSourceReferences(Object element) {
if (!(element instanceof ISourceReference))
return false;
if (!(element instanceof IJavaElement))
return false;
if (element instanceof ICompilationUnit)
return false;
return true;
}
private boolean canCopyElements() {
if (fCanCopyElements == 0) {
fCanCopyElements= 2;
if (!canActivate(fCopyRefactoring))
fCanCopyElements= 1;
}
return fCanCopyElements == 2;
}
private void handleDropCopy(final Object target, DropTargetEvent event) throws JavaModelException{
if (canPasteSourceReferences(target, event)){
pasteSourceReferences(target, event);
return;
}
SelectionDispatchAction action= ReorgActionFactory.createDnDCopyAction(fElements, ResourceUtil.getResource(target));
action.run();
}
//--
private static class DragNDropMoveAction extends JdtMoveAction{
private Object fTarget;
private static final int PREVIEW_ID= IDialogConstants.CLIENT_ID + 1;
public DragNDropMoveAction(ISelectionProvider provider, Object target){
super(new MockUnifiedSite(provider));
Assert.isNotNull(target);
fTarget= target;
}
protected Object selectDestination(ReorgRefactoring ref) {
return fTarget;
}
protected boolean isOkToProceed(ReorgRefactoring refactoring) throws JavaModelException{
if (!super.isOkToProceed(refactoring))
return false;
return askIfUpdateReferences((MoveRefactoring)refactoring);
}
//returns false iff canceled or error
private boolean askIfUpdateReferences(MoveRefactoring ref) throws JavaModelException{
if (! ref.canUpdateReferences()){
setShowPreview(false);
return true;
}
switch (askIfUpdateReferences()){
case IDialogConstants.CANCEL_ID:
setShowPreview(false);
return false;
case IDialogConstants.NO_ID:
ref.setUpdateReferences(false);
setShowPreview(false);
return true;
case IDialogConstants.YES_ID:
ref.setUpdateReferences(true);
setShowPreview(false);
return true;
case PREVIEW_ID:
ref.setUpdateReferences(true);
setShowPreview(true);
return true;
default:
Assert.isTrue(false); //not expected to get here
return false;
}
}
private static int askIfUpdateReferences(){
Shell shell= JavaPlugin.getActiveWorkbenchShell().getShell();
String title= PackagesMessages.getString("SelectionTransferDropAdapter.dialog.title"); //$NON-NLS-1$
String preview= PackagesMessages.getString("SelectionTransferDropAdapter.dialog.preview.label"); //$NON-NLS-1$
String question= PackagesMessages.getString("SelectionTransferDropAdapter.dialog.question"); //$NON-NLS-1$
String[] labels= new String[] {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL,
preview, IDialogConstants.CANCEL_LABEL };
final MessageDialog dialog = new MessageDialog(shell, title, null, question, MessageDialog.QUESTION, labels, 2); //preview is default
shell.getDisplay().syncExec(new Runnable() {
public void run() {
dialog.open();
}
});
int result = dialog.getReturnCode();
if (result == 0)
return IDialogConstants.YES_ID;
if (result == 1)
return IDialogConstants.NO_ID;
if (result == 2)
return PREVIEW_ID;
return IDialogConstants.CANCEL_ID;
}
}
}
|
14,390 |
Bug 14390 npe on sorting in outline
|
20020418+ (20020418.2) java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.initializeHighlightColor (LinkedPositionUI.java:109) at org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.propertyChange (LinkedPositionUI.java:100) at org.eclipse.ui.plugin.AbstractUIPlugin$CompatibilityPreferenceStore.fireProperty ChangeEvent(AbstractUIPlugin.java:247) at org.eclipse.ui.plugin.AbstractUIPlugin$1.propertyChange (AbstractUIPlugin.java:188) at org.eclipse.core.runtime.Preferences.firePropertyChangeEvent (Preferences.java:505) at org.eclipse.core.runtime.Preferences.setValue(Preferences.java:563) at org.eclipse.ui.plugin.AbstractUIPlugin$CompatibilityPreferenceStore.setValue (AbstractUIPlugin.java:457) at org.eclipse.jdt.internal.ui.javaeditor.JavaOutlinePage$LexicalSortingAction.valu eChanged(JavaOutlinePage.java:569) at org.eclipse.jdt.internal.ui.javaeditor.JavaOutlinePage$LexicalSortingAction.run (JavaOutlinePage.java:558) at org.eclipse.jface.action.Action.runWithEvent(Action.java:590) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:816) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:643) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:349) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:195) at org.eclipse.core.launcher.Main.run(Main.java:541) at org.eclipse.core.launcher.Main.main(Main.java:396)
|
resolved fixed
|
6663ac0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-23T14:25:04Z | 2002-04-23T11:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedPositionUI.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.text.link;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
/**
* A user interface for <code>LinkedPositionManager</code>, using <code>ITextViewer</code>.
*/
public class LinkedPositionUI implements LinkedPositionListener,
ITextInputListener, ModifyListener, VerifyListener, VerifyKeyListener, PaintListener, IPropertyChangeListener {
/**
* A listener for notification when the user cancelled the edit operation.
*/
public interface ExitListener {
void exit(boolean accept);
}
// leave flags
private static final int UNINSTALL= 1; // uninstall linked position manager
private static final int COMMIT= 2; // commit changes
private static final int DOCUMENT_CHANGED= 4; // document has changed
private static final int UPDATE_CARET= 8; // update caret
private static final String CARET_POSITION= "LinkedPositionUI.caret.position"; //$NON-NLS-1$
private static final IPositionUpdater fgUpdater= new DefaultPositionUpdater(CARET_POSITION);
private static final IPreferenceStore fgStore= JavaPlugin.getDefault().getPreferenceStore();
private final ITextViewer fViewer;
private final LinkedPositionManager fManager;
private Color fFrameColor;
private int fFinalCaretOffset= -1; // no final caret offset
private Position fFramePosition;
private int fCaretOffset;
private ExitListener fExitListener;
/**
* Creates a user interface for <code>LinkedPositionManager</code>.
*
* @param viewer the text viewer.
* @param manager the <code>LinkedPositionManager</code> managing a <code>IDocument</code> of the <code>ITextViewer</code>.
*/
public LinkedPositionUI(ITextViewer viewer, LinkedPositionManager manager) {
Assert.isNotNull(viewer);
Assert.isNotNull(manager);
fViewer= viewer;
fManager= manager;
fManager.setLinkedPositionListener(this);
initializeHighlightColor(viewer);
}
/**
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
initializeHighlightColor(fViewer);
redrawRegion();
}
private void initializeHighlightColor(ITextViewer viewer) {
if (fFrameColor != null)
fFrameColor.dispose();
Display display= viewer.getTextWidget().getDisplay();
fFrameColor= createColor(fgStore, CompilationUnitEditor.LINKED_POSITION_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
/**
* Sets the final position of the caret when the linked mode is exited
* successfully by leaving the last linked position using TAB.
*/
public void setFinalCaretOffset(int offset) {
fFinalCaretOffset= offset;
}
/**
* Sets a <code>CancelListener</code> which is notified if the linked mode
* is exited unsuccessfully by hitting ESC.
*/
public void setCancelListener(ExitListener listener) {
fExitListener= listener;
}
/*
* @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, int)
*/
public void setCurrentPosition(Position position, int caretOffset) {
if (!fFramePosition.equals(position)) {
redrawRegion();
fFramePosition= position;
}
fCaretOffset= caretOffset;
}
/**
* Enters the linked mode. The linked mode can be left by calling
* <code>exit</code>.
*
* @see exit(boolean)
*/
public void enter() {
// track final caret
IDocument document= fViewer.getDocument();
document.addPositionCategory(CARET_POSITION);
document.addPositionUpdater(fgUpdater);
try {
if (fFinalCaretOffset != -1)
document.addPosition(CARET_POSITION, new Position(fFinalCaretOffset));
} catch (BadLocationException e) {
openErrorDialog(fViewer.getTextWidget().getShell(), e);
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
fViewer.addTextInputListener(this);
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
extension.prependVerifyKeyListener(this);
StyledText text= fViewer.getTextWidget();
text.addVerifyListener(this);
text.addModifyListener(this);
text.addPaintListener(this);
text.showSelection();
fFramePosition= fManager.getFirstPosition();
if (fFramePosition == null)
leave(UNINSTALL | COMMIT | UPDATE_CARET);
fgStore.addPropertyChangeListener(this);
}
/**
* @see LinkedPositionManager.LinkedPositionListener#exit(boolean)
*/
public void exit(boolean success) {
// no UNINSTALL since manager has already uninstalled itself
leave((success ? COMMIT : 0) | UPDATE_CARET);
}
/**
* Returns the cursor selection, after having entered the linked mode.
* <code>enter()</code> must be called prior to a call to this method.
*/
public IRegion getSelectedRegion() {
if (fFramePosition == null)
return new Region(fFinalCaretOffset, 0);
else
return new Region(fFramePosition.getOffset(), fFramePosition.getLength());
}
private void leave(int flags) {
if ((flags & UNINSTALL) != 0)
fManager.uninstall((flags & COMMIT) != 0);
fgStore.removePropertyChangeListener(this);
if (fFrameColor != null) {
fFrameColor.dispose();
fFrameColor= null;
}
StyledText text= fViewer.getTextWidget();
text.removePaintListener(this);
text.removeModifyListener(this);
text.removeVerifyListener(this);
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
extension.removeVerifyKeyListener(this);
fViewer.removeTextInputListener(this);
try {
IRegion region= fViewer.getVisibleRegion();
IDocument document= fViewer.getDocument();
if (((flags & COMMIT) != 0) &&
((flags & DOCUMENT_CHANGED) == 0) &&
((flags & UPDATE_CARET) != 0))
{
Position[] positions= document.getPositions(CARET_POSITION);
if ((positions != null) && (positions.length != 0)) {
int offset= positions[0].getOffset() - region.getOffset();
if ((offset >= 0) && (offset <= region.getLength()))
text.setSelection(offset, offset);
}
}
document.removePositionUpdater(fgUpdater);
document.removePositionCategory(CARET_POSITION);
if (fExitListener != null)
fExitListener.exit(
((flags & COMMIT) != 0) ||
((flags & DOCUMENT_CHANGED) != 0));
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
if ((flags & DOCUMENT_CHANGED) == 0)
text.redraw();
}
private void next() {
redrawRegion();
fFramePosition= fManager.getNextPosition(fFramePosition.getOffset());
if (fFramePosition == null) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
} else {
selectRegion();
redrawRegion();
}
}
private void previous() {
redrawRegion();
Position position= fManager.getPreviousPosition(fFramePosition.getOffset());
if (position == null) {
fViewer.getTextWidget().getDisplay().beep();
} else {
fFramePosition= position;
selectRegion();
redrawRegion();
}
}
/*
* @see VerifyKeyListener#verifyKey(VerifyEvent)
*/
public void verifyKey(VerifyEvent event) {
switch (event.character) {
// [SHIFT-]TAB = hop between edit boxes
case 0x09:
{
Point selection= fViewer.getTextWidget().getSelection();
IRegion region= fViewer.getVisibleRegion();
int offset= selection.x + region.getOffset();
int length= selection.y - selection.x;
// if tab was treated as a document change, would it exceed variable range?
if (!LinkedPositionManager.includes(fFramePosition, offset, length)) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
return;
}
}
if (event.stateMask == SWT.SHIFT)
previous();
else
next();
event.doit= false;
break;
// ENTER
case 0x0D:
leave(UNINSTALL | COMMIT | UPDATE_CARET);
event.doit= false;
break;
// ESC
case 0x1B:
leave(UNINSTALL | COMMIT);
event.doit= false;
break;
}
}
/*
* @see VerifyListener#verifyText(VerifyEvent)
*/
public void verifyText(VerifyEvent event) {
if (!event.doit)
return;
IRegion region= fViewer.getVisibleRegion();
int offset= event.start + region.getOffset();
int length= event.end - event.start;
// allow changes only within linked positions when coming through UI
if (!fManager.anyPositionIncludes(offset, length))
leave(UNINSTALL | COMMIT);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fFramePosition == null)
return;
IRegion region= fViewer.getVisibleRegion();
// #6824
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() - region.getOffset();
int length= fFramePosition.getLength();
StyledText text= fViewer.getTextWidget();
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
gc.setForeground(fFrameColor);
gc.drawLine(x1, y, x2, y);
}
private static Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private static Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
private void redrawRegion() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() - region.getOffset();
int length= fFramePosition.getLength();
fViewer.getTextWidget().redrawRange(offset, length, true);
}
private void selectRegion() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int start= fFramePosition.getOffset() - region.getOffset();
int end= fFramePosition.getLength() + start;
fViewer.getTextWidget().setSelection(start, end);
}
private void updateCaret() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() + fCaretOffset - region.getOffset();
if ((offset >= 0) && (offset <= region.getLength()))
fViewer.getTextWidget().setCaretOffset(offset);
}
/*
* @see ModifyListener#modifyText(ModifyEvent)
*/
public void modifyText(ModifyEvent e) {
// reposition caret after StyledText
redrawRegion();
updateCaret();
}
private static void openErrorDialog(Shell shell, Exception e) {
MessageDialog.openError(shell, LinkedPositionMessages.getString("LinkedPositionUI.error.title"), e.getMessage()); //$NON-NLS-1$
}
/*
* @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
// 5326: leave linked mode on document change
int flags= UNINSTALL | COMMIT | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED);
leave(flags);
}
/*
* @see ITextInputListener#inputDocumentChanged(IDocument, IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
}
private static boolean includes(IRegion region, Position position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
}
|
14,665 |
Bug 14665 Mnemonic collisions on Tag Configuration dialog
|
3 of the buttons on the Tag Configuration Dialog have A as a mnemonic
|
resolved fixed
|
01550b4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T08:35:29Z | 2002-04-25T18:40:00Z |
org.eclipse.jdt.ui/ui
| |
14,665 |
Bug 14665 Mnemonic collisions on Tag Configuration dialog
|
3 of the buttons on the Tag Configuration Dialog have A as a mnemonic
|
resolved fixed
|
01550b4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T08:35:29Z | 2002-04-25T18:40:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/RenameJavaElementAction.java
| |
14,429 |
Bug 14429 Smoke 20020423: replace from local history wrong indentation
|
- load TestCase.java - edit method runTest - save - replace method with latest from local histroy observe: the method is wrong indented IMO the culprit is a change DB did at MemberEdit.
|
resolved fixed
|
f7c1350
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T10:48:02Z | 2002-04-23T16:40:00Z |
org.eclipse.jdt.ui/core
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.