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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25,324 |
Bug 25324 Ability to know when tests are finished [junit]
|
Hi, I'm writing a Cactus Plugin that extends the JUnit Plugin and I need to know when the tests have finished running in the TestRunner. There is a nice ITestRunListener interface for that. My idea was thus to implement this interface and somehow register my listener to the TestRunner (RemoteTestRunnerClient). However: 1/ Currently the RemoteTestRunnerClient implementation only supports one listener 2/ There is no API in TestRunnerViewPart to get access to the TestRunner I am attaching a patch that should provide this facility. However, I need your help to know if this is the right approach or not. Thank you -Vincent
|
resolved fixed
|
f2b66ff
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T11:04:18Z | 2002-10-24T14:33:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/FilterPatternsDialog.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
/**
* A dialog to enter a filter pattern.
*/
public class FilterPatternsDialog extends InputDialog {
static class NonEmptyValidator implements IInputValidator {
public String isValid(String input) {
if (input.length() > 0)
return null;
return JUnitMessages.getString("FilterPatternsDialog.message.notempty"); //$NON-NLS-1$
}
};
/*
* @see InputDialog#InputDialog
*/
public FilterPatternsDialog(Shell parent, String title, String message) {
super(parent, title, message, "", new NonEmptyValidator()); //$NON-NLS-1$
}
/*
* @see InputDialog#createDialogArea(Composite)
*/
protected Control createDialogArea(Composite parent) {
Control result= super.createDialogArea(parent);
getText().setFocus();
return result;
}
}
|
25,324 |
Bug 25324 Ability to know when tests are finished [junit]
|
Hi, I'm writing a Cactus Plugin that extends the JUnit Plugin and I need to know when the tests have finished running in the TestRunner. There is a nice ITestRunListener interface for that. My idea was thus to implement this interface and somehow register my listener to the TestRunner (RemoteTestRunnerClient). However: 1/ Currently the RemoteTestRunnerClient implementation only supports one listener 2/ There is no API in TestRunnerViewPart to get access to the TestRunner I am attaching a patch that should provide this facility. However, I need your help to know if this is the right approach or not. Thank you -Vincent
|
resolved fixed
|
f2b66ff
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T11:04:18Z | 2002-10-24T14:33:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/HierarchyRunView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jdt.internal.junit.runner.ITestRunListener;
/*
* A view that shows the contents of a test suite
* as a tree.
*/
class HierarchyRunView implements ITestRunView, IMenuListener {
/**
* The tree widget
*/
private Tree fTree;
public static final int IS_SUITE= -1;
/**
* Helper used to resurrect test hierarchy
*/
private static class SuiteInfo {
public int fTestCount;
public TreeItem fTreeItem;
public SuiteInfo(TreeItem treeItem, int testCount){
fTreeItem= treeItem;
fTestCount= testCount;
}
}
/**
* Vector of SuiteInfo items
*/
private Vector fSuiteInfos= new Vector();
/**
* Maps test names to TreeItems.
* If there is one treeItem for a test then the
* value of the map corresponds to the item, otherwise
* there is a list of tree items.
*/
private Map fTreeItemMap= new HashMap();
private TestRunnerViewPart fTestRunnerPart;
private boolean fPressed= false;
private final Image fOkIcon= TestRunnerViewPart.createImage("obj16/testok.gif"); //$NON-NLS-1$
private final Image fErrorIcon= TestRunnerViewPart.createImage("obj16/testerr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("obj16/testfail.gif"); //$NON-NLS-1$
private final Image fHierarchyIcon= TestRunnerViewPart.createImage("obj16/testhier.gif"); //$NON-NLS-1$
private final Image fSuiteIcon= TestRunnerViewPart.createImage("obj16/tsuite.gif"); //$NON-NLS-1$
private final Image fSuiteErrorIcon= TestRunnerViewPart.createImage("obj16/tsuiteerror.gif"); //$NON-NLS-1$
private final Image fSuiteFailIcon= TestRunnerViewPart.createImage("obj16/tsuitefail.gif"); //$NON-NLS-1$
private final Image fTestIcon= TestRunnerViewPart.createImage("obj16/test.gif"); //$NON-NLS-1$
public HierarchyRunView(CTabFolder tabFolder, TestRunnerViewPart runner) {
fTestRunnerPart= runner;
CTabItem hierarchyTab= new CTabItem(tabFolder, SWT.NONE);
hierarchyTab.setText(getName());
hierarchyTab.setImage(fHierarchyIcon);
Composite testTreePanel= new Composite(tabFolder, SWT.NONE);
GridLayout gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
testTreePanel.setLayout(gridLayout);
GridData gridData= new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
testTreePanel.setLayoutData(gridData);
hierarchyTab.setControl(testTreePanel);
hierarchyTab.setToolTipText(JUnitMessages.getString("HierarchyRunView.tab.tooltip")); //$NON-NLS-1$
fTree= new Tree(testTreePanel, SWT.V_SCROLL);
gridData= new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fTree.setLayoutData(gridData);
initMenu();
addListeners();
}
void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
fOkIcon.dispose();
fHierarchyIcon.dispose();
fTestIcon.dispose();
fSuiteIcon.dispose();
fSuiteErrorIcon.dispose();
fSuiteFailIcon.dispose();
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTree);
fTree.setMenu(menu);
}
private String getTestLabel() {
TreeItem treeItem= fTree.getSelection()[0];
if(treeItem == null)
return ""; //$NON-NLS-1$
return treeItem.getText();
}
private TestRunInfo getTestInfo() {
TreeItem[] treeItems= fTree.getSelection();
if(treeItems.length == 0)
return null;
return ((TestRunInfo)treeItems[0].getData());
}
public String getClassName() {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return null;
return extractClassName(testInfo.fTestName);
}
public String getTestName() {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return null;
return testInfo.fTestName;
}
private String extractClassName(String testNameString) {
if (testNameString == null)
return null;
int index= testNameString.indexOf('(');
if (index < 0)
return testNameString;
testNameString= testNameString.substring(index + 1);
return testNameString.substring(0, testNameString.indexOf(')'));
}
public String getName() {
return JUnitMessages.getString("HierarchyRunView.tab.title"); //$NON-NLS-1$
}
public void setSelectedTest(String testName) {
TreeItem treeItem= findFirstItem(testName);
if (treeItem != null)
fTree.setSelection(new TreeItem[]{treeItem});
}
public void endTest(String testName) {
TreeItem treeItem= findFirstNotRunItem(testName);
// workaround for bug 8657
if (treeItem == null)
return;
TestRunInfo testInfo= fTestRunnerPart.getTestInfo(testName);
updateItem(treeItem, testInfo);
if (testInfo.fTrace != null)
fTree.showItem(treeItem);
}
private void updateItem(TreeItem treeItem, TestRunInfo testInfo) {
treeItem.setData(testInfo);
if(testInfo.fStatus == ITestRunListener.STATUS_OK) {
treeItem.setImage(fOkIcon);
return;
}
if (testInfo.fStatus == ITestRunListener.STATUS_FAILURE)
treeItem.setImage(fFailureIcon);
else if (testInfo.fStatus == ITestRunListener.STATUS_ERROR)
treeItem.setImage(fErrorIcon);
propagateStatus(treeItem, testInfo.fStatus);
}
void propagateStatus(TreeItem item, int status) {
TreeItem parent= item.getParentItem();
if (parent == null)
return;
Image parentImage= parent.getImage();
if (status == ITestRunListener.STATUS_FAILURE) {
if (parentImage == fSuiteErrorIcon || parentImage == fSuiteFailIcon)
return;
parent.setImage(fSuiteFailIcon);
} else {
if (parentImage == fSuiteErrorIcon)
return;
parent.setImage(fSuiteErrorIcon);
}
propagateStatus(parent, status);
}
public void activate() {
testSelected();
}
public void setFocus() {
fTree.setFocus();
}
public void aboutToStart() {
fTree.removeAll();
fSuiteInfos.removeAllElements();
fTreeItemMap= new HashMap();
}
protected void testSelected() {
fTestRunnerPart.handleTestSelected(getTestName());
}
public void menuAboutToShow(IMenuManager manager) {
if (fTree.getSelectionCount() > 0) {
final TreeItem treeItem= fTree.getSelection()[0];
TestRunInfo testInfo= (TestRunInfo) treeItem.getData();
if (testInfo.fStatus == IS_SUITE) {
String className= getTestLabel();
int index= className.length();
if ((index= className.indexOf('@')) > 0)
className= className.substring(0, index);
manager.add(new OpenTestAction(fTestRunnerPart, className));
} else {
manager.add(new OpenTestAction(fTestRunnerPart, getClassName(), getTestLabel()));
manager.add(new RerunAction(fTestRunnerPart, getClassName(), getTestLabel()));
}
}
}
private void addListeners() {
fTree.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
activate();
}
public void widgetDefaultSelected(SelectionEvent e) {
activate();
}
});
fTree.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
fTree.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
handleDoubleClick(e);
}
public void mouseDown(MouseEvent e) {
fPressed= true;
}
public void mouseUp(MouseEvent e) {
fPressed= false;
}
});
fTree.addMouseMoveListener(new MouseMoveListener() {
public void mouseMove(MouseEvent e) {
if (!(e.getSource() instanceof Tree))
return;
TreeItem[] treeItem= {((Tree) e.getSource()).getItem(new Point(e.x, e.y))};
if (fPressed & (null != treeItem[0])) {
fTree.setSelection(treeItem);
activate();
}
// scroll
if ((e.y < 1) & fPressed) {
try {
TreeItem tItem= treeItem[0].getParentItem();
fTree.setSelection(new TreeItem[] { tItem });
activate();
} catch (Exception ex) {
}
}
}
});
}
void handleDoubleClick(MouseEvent e) {
TestRunInfo testInfo= getTestInfo();
if(testInfo == null)
return;
if ((testInfo.fStatus == IS_SUITE)) {
String className= getTestLabel();
int index= className.length();
if ((index= className.indexOf('@')) > 0)
className= className.substring(0, index);
(new OpenTestAction(fTestRunnerPart, className)).run();
}
else {
(new OpenTestAction(fTestRunnerPart, getClassName(), getTestLabel())).run();
}
}
public void newTreeEntry(String treeEntry) {
int index0= treeEntry.indexOf(',');
int index1= treeEntry.lastIndexOf(',');
String label= treeEntry.substring(0, index0).trim();
TestRunInfo testInfo= new TestRunInfo(label);
//fTestInfo.addElement(testInfo);
int index2;
if((index2= label.indexOf('(')) > 0)
label= label.substring(0, index2);
if((index2= label.indexOf('@')) > 0)
label= label.substring(0, index2);
String isSuite= treeEntry.substring(index0+1, index1);
int testCount= Integer.parseInt(treeEntry.substring(index1+1));
TreeItem treeItem;
while((fSuiteInfos.size() > 0) && (((SuiteInfo) fSuiteInfos.lastElement()).fTestCount == 0)) {
fSuiteInfos.removeElementAt(fSuiteInfos.size()-1);
}
if(fSuiteInfos.size() == 0){
testInfo.fStatus= IS_SUITE;
treeItem= new TreeItem(fTree, SWT.NONE);
treeItem.setImage(fSuiteIcon);
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else if(isSuite.equals("true")) { //$NON-NLS-1$
testInfo.fStatus= IS_SUITE;
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fHierarchyIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else {
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fTestIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
mapTest(testInfo, treeItem);
}
treeItem.setText(label);
treeItem.setData(testInfo);
}
private void mapTest(TestRunInfo info, TreeItem item) {
String test= info.fTestName;
Object o= fTreeItemMap.get(test);
if (o == null) {
fTreeItemMap.put(test, item);
return;
}
if (o instanceof TreeItem) {
List list= new ArrayList();
list.add(o);
list.add(item);
fTreeItemMap.put(test, list);
return;
}
if (o instanceof List) {
((List)o).add(item);
}
}
private TreeItem findFirstNotRunItem(String testName) {
Object o= fTreeItemMap.get(testName);
if (o instanceof TreeItem)
return (TreeItem)o;
if (o instanceof List) {
List l= (List)o;
for (int i= 0; i < l.size(); i++) {
TreeItem item= (TreeItem)l.get(i);
if (item.getImage() == fTestIcon)
return item;
}
return null;
}
return null;
}
private TreeItem findFirstItem(String testName) {
Object o= fTreeItemMap.get(testName);
if (o instanceof TreeItem)
return (TreeItem)o;
if (o instanceof List) {
return (TreeItem)((List)o).get(0);
}
return null;
}
/*
* @see ITestRunView#testStatusChanged(TestRunInfo, int)
*/
public void testStatusChanged(TestRunInfo newInfo) {
Object o= fTreeItemMap.get(newInfo.fTestName);
if (o instanceof TreeItem) {
updateItem((TreeItem)o, newInfo);
return;
}
if (o instanceof List) {
List l= (List)o;
for (int i= 0; i < l.size(); i++)
updateItem((TreeItem)l.get(i), newInfo);
}
}
}
|
25,324 |
Bug 25324 Ability to know when tests are finished [junit]
|
Hi, I'm writing a Cactus Plugin that extends the JUnit Plugin and I need to know when the tests have finished running in the TestRunner. There is a nice ITestRunListener interface for that. My idea was thus to implement this interface and somehow register my listener to the TestRunner (RemoteTestRunnerClient). However: 1/ Currently the RemoteTestRunnerClient implementation only supports one listener 2/ There is no API in TestRunnerViewPart to get access to the TestRunner I am attaching a patch that should provide this facility. However, I need your help to know if this is the right approach or not. Thank you -Vincent
|
resolved fixed
|
f2b66ff
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T11:04:18Z | 2002-10-24T14:33:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/JUnitPlugin.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchListener;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* The plug-in runtime class for the JUnit plug-in.
*/
public class JUnitPlugin extends AbstractUIPlugin implements ILaunchListener {
/**
* The single instance of this plug-in runtime class.
*/
private static JUnitPlugin fgPlugin= null;
public static final String PLUGIN_ID = "org.eclipse.jdt.junit" ; //$NON-NLS-1$
public final static String TEST_SUPERCLASS_NAME= "junit.framework.TestCase"; //$NON-NLS-1$
public final static String TEST_INTERFACE_NAME= "junit.framework.Test"; //$NON-NLS-1$
private static URL fgIconBaseURL;
/**
* Use to track new launches. We need to do this
* so that we only attach a TestRunner once to a launch.
* Once a test runner is connected it is removed from the set.
*/
private AbstractSet fTrackedLaunches= new HashSet(20);
public JUnitPlugin(IPluginDescriptor desc) {
super(desc);
fgPlugin= this;
String pathSuffix= "icons/full/"; //$NON-NLS-1$
try {
fgIconBaseURL= new URL(getDescriptor().getInstallURL(), pathSuffix);
} catch (MalformedURLException e) {
// do nothing
}
}
public static JUnitPlugin getDefault() {
return fgPlugin;
}
public static Shell getActiveWorkbenchShell() {
IWorkbenchWindow workBenchWindow= getActiveWorkbenchWindow();
if (workBenchWindow == null)
return null;
return workBenchWindow.getShell();
}
/**
* Returns the active workbench window
*
* @return the active workbench window
*/
public static IWorkbenchWindow getActiveWorkbenchWindow() {
if (fgPlugin == null)
return null;
IWorkbench workBench= fgPlugin.getWorkbench();
if (workBench == null)
return null;
return workBench.getActiveWorkbenchWindow();
}
public IWorkbenchPage getActivePage() {
return getActiveWorkbenchWindow().getActivePage();
}
public static String getPluginId() {
return getDefault().getDescriptor().getUniqueIdentifier();
}
/*
* @see AbstractUIPlugin#initializeDefaultPreferences
*/
protected void initializeDefaultPreferences(IPreferenceStore store) {
super.initializeDefaultPreferences(store);
JUnitPreferencePage.initializeDefaults(store);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, getPluginId(), IStatus.ERROR, "Error", e)); //$NON-NLS-1$
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static URL makeIconFileURL(String name) throws MalformedURLException {
if (JUnitPlugin.fgIconBaseURL == null)
throw new MalformedURLException();
return new URL(JUnitPlugin.fgIconBaseURL, name);
}
static ImageDescriptor getImageDescriptor(String relativePath) {
try {
return ImageDescriptor.createFromURL(makeIconFileURL(relativePath));
} catch (MalformedURLException e) {
// should not happen
return ImageDescriptor.getMissingImageDescriptor();
}
}
/*
* @see ILaunchListener#launchRemoved(ILaunch)
*/
public void launchRemoved(ILaunch launch) {
fTrackedLaunches.remove(launch);
}
/*
* @see ILaunchListener#launchAdded(ILaunch)
*/
public void launchAdded(ILaunch launch) {
fTrackedLaunches.add(launch);
}
public void connectTestRunner(ILaunch launch, IType launchedType, int port) {
IWorkbench workbench= getWorkbench();
if (workbench == null)
return;
IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page= window.getActivePage();
TestRunnerViewPart testRunner= null;
if (page != null) {
try { // show the result view if it isn't shown yet
testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
// TODO: have force the creation of view part contents
// otherwise the UI will not be updated
if(testRunner == null || !testRunner.isCreated()) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the result view
page.activate(activePart);
}
} catch (PartInitException pie) {
log(pie);
}
}
if (testRunner != null)
testRunner.startTestRunListening(launchedType, port, launch);
}
/*
* @see ILaunchListener#launchChanged(ILaunch)
*/
public void launchChanged(final ILaunch launch) {
if (!fTrackedLaunches.contains(launch))
return;
ILaunchConfiguration config= launch.getLaunchConfiguration();
IType launchedType= null;
int port= -1;
if (config != null) {
// test whether the launch defines the JUnit attributes
String portStr= launch.getAttribute(JUnitBaseLaunchConfiguration.PORT_ATTR);
String typeStr= launch.getAttribute(JUnitBaseLaunchConfiguration.TESTTYPE_ATTR);
if (portStr != null && typeStr != null) {
port= Integer.parseInt(portStr);
IJavaElement element= JavaCore.create(typeStr);
if (element instanceof IType)
launchedType= (IType)element;
}
}
if (launchedType != null) {
fTrackedLaunches.remove(launch);
final int finalPort= port;
final IType finalType= launchedType;
getDisplay().asyncExec(new Runnable() {
public void run() {
connectTestRunner(launch, finalType, finalPort);
}
});
}
}
/*
* @see Plugin#startup()
*/
public void startup() throws CoreException {
super.startup();
ILaunchManager launchManager= DebugPlugin.getDefault().getLaunchManager();
launchManager.addLaunchListener(this);
}
/*
* @see Plugin#shutdown()
*/
public void shutdown() throws CoreException {
super.shutdown();
ILaunchManager launchManager= DebugPlugin.getDefault().getLaunchManager();
launchManager.removeLaunchListener(this);
}
public static Display getDisplay() {
Shell shell= getActiveWorkbenchShell();
if (shell != null) {
return shell.getDisplay();
}
Display display= Display.getCurrent();
if (display == null) {
display= Display.getDefault();
}
return display;
}
/**
* Utility method to create and return a selection dialog that allows
* selection of a specific Java package. Empty packages are not returned.
* If Java Projects are provided, only packages found within those projects
* are included. If no Java projects are provided, all Java projects in the
* workspace are considered.
*/
public static ElementListSelectionDialog createAllPackagesDialog(Shell shell, IJavaProject[] originals, final boolean includeDefaultPackage) throws JavaModelException {
final List packageList= new ArrayList();
if (originals == null) {
IWorkspaceRoot wsroot= ResourcesPlugin.getWorkspace().getRoot();
IJavaModel model= JavaCore.create(wsroot);
originals= model.getJavaProjects();
}
final IJavaProject[] projects= originals;
final JavaModelException[] exception= new JavaModelException[1];
ProgressMonitorDialog monitor= new ProgressMonitorDialog(shell);
IRunnableWithProgress r= new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
Set packageNameSet= new HashSet();
monitor.beginTask(JUnitMessages.getString("JUnitPlugin.searching"), projects.length); //$NON-NLS-1$
for (int i= 0; i < projects.length; i++) {
IPackageFragment[] pkgs= projects[i].getPackageFragments();
for (int j= 0; j < pkgs.length; j++) {
IPackageFragment pkg= pkgs[j];
if (!pkg.hasChildren() && (pkg.getNonJavaResources().length > 0))
continue;
String pkgName= pkg.getElementName();
if (!includeDefaultPackage && pkgName.length() == 0)
continue;
if (packageNameSet.add(pkgName))
packageList.add(pkg);
}
monitor.worked(1);
}
monitor.done();
} catch (JavaModelException jme) {
exception[0]= jme;
}
}
};
try {
monitor.run(false, false, r);
} catch (InvocationTargetException e) {
JUnitPlugin.log(e);
} catch (InterruptedException e) {
JUnitPlugin.log(e);
}
if (exception[0] != null)
throw exception[0];
int flags= JavaElementLabelProvider.SHOW_DEFAULT;
ElementListSelectionDialog dialog= new ElementListSelectionDialog(shell, new JavaElementLabelProvider(flags));
dialog.setIgnoreCase(false);
dialog.setElements(packageList.toArray()); // XXX inefficient
return dialog;
}
}
|
25,324 |
Bug 25324 Ability to know when tests are finished [junit]
|
Hi, I'm writing a Cactus Plugin that extends the JUnit Plugin and I need to know when the tests have finished running in the TestRunner. There is a nice ITestRunListener interface for that. My idea was thus to implement this interface and somehow register my listener to the TestRunner (RemoteTestRunnerClient). However: 1/ Currently the RemoteTestRunnerClient implementation only supports one listener 2/ There is no API in TestRunnerViewPart to get access to the TestRunner I am attaching a patch that should provide this facility. However, I need your help to know if this is the right approach or not. Thank you -Vincent
|
resolved fixed
|
f2b66ff
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T11:04:18Z | 2002-10-24T14:33:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/JUnitPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.junit.util.ExceptionHandler;
import org.eclipse.jdt.internal.junit.util.SWTUtil;
import org.eclipse.jdt.ui.IJavaElementSearchConstants;
import org.eclipse.jdt.ui.ISharedImages;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ContentViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.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.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchViewerSorter;
/**
* Preference page for JUnit settings. Supports to define the failure
* stack filter patterns.
*/
public class JUnitPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String DEFAULT_NEW_FILTER_TEXT= ""; //$NON-NLS-1$
private static final Image IMG_CUNIT= JavaUI.getSharedImages().getImage(ISharedImages.IMG_OBJS_CLASS);
private static final Image IMG_PKG= JavaUI.getSharedImages().getImage(ISharedImages.IMG_OBJS_PACKAGE);
private static String[] fgDefaultFilterPatterns= new String[] { "org.eclipse.jdt.internal.junit.runner.*", //$NON-NLS-1$
"org.eclipse.jdt.internal.junit.ui.*", //$NON-NLS-1$
"junit.framework.TestCase", //$NON-NLS-1$
"junit.framework.TestResult", //$NON-NLS-1$
"junit.framework.TestSuite", //$NON-NLS-1$
"junit.framework.Assert", //$NON-NLS-1$
"java.lang.reflect.Method.invoke" //$NON-NLS-1$
};
// Step filter widgets
private CheckboxTableViewer fFilterViewer;
private Table fFilterTable;
private Button fShowOnErrorCheck;
private Button fAddPackageButton;
private Button fAddTypeButton;
private Button fRemoveFilterButton;
private Button fAddFilterButton;
private Button fEnableAllButton;
private Button fDisableAllButton;
private Text fEditorText;
private String fInvalidEditorText= null;
private TableEditor fTableEditor;
private TableItem fNewTableItem;
private Filter fNewStackFilter;
private Label fTableLabel;
private StackFilterContentProvider fStackFilterContentProvider;
/**
* Model object that represents a single entry in the filter table.
*/
private class Filter {
private String fName;
private boolean fChecked;
public Filter(String name, boolean checked) {
setName(name);
setChecked(checked);
}
public String getName() {
return fName;
}
public void setName(String name) {
fName= name;
}
public boolean isChecked() {
return fChecked;
}
public void setChecked(boolean checked) {
fChecked= checked;
}
public boolean equals(Object o) {
if (!(o instanceof Filter))
return false;
Filter other= (Filter) o;
return (getName().equals(other.getName()));
}
public int hashCode() {
return fName.hashCode();
}
}
/**
* Sorter for the filter table; sorts alphabetically ascending.
*/
private class FilterViewerSorter extends WorkbenchViewerSorter {
public int compare(Viewer viewer, Object e1, Object e2) {
ILabelProvider lprov= (ILabelProvider) ((ContentViewer) viewer).getLabelProvider();
String name1= lprov.getText(e1);
String name2= lprov.getText(e2);
if (name1 == null)
name1= ""; //$NON-NLS-1$
if (name2 == null)
name2= ""; //$NON-NLS-1$
if (name1.length() > 0 && name2.length() > 0) {
char char1= name1.charAt(name1.length() - 1);
char char2= name2.charAt(name2.length() - 1);
if (char1 == '*' && char1 != char2)
return -1;
if (char2 == '*' && char2 != char1)
return 1;
}
return name1.compareTo(name2);
}
}
/**
* Label provider for Filter model objects
*/
private class FilterLabelProvider extends LabelProvider implements ITableLabelProvider {
public String getColumnText(Object object, int column) {
return (column == 0) ? ((Filter) object).getName() : ""; //$NON-NLS-1$
}
public String getText(Object element) {
return ((Filter) element).getName();
}
public Image getColumnImage(Object object, int column) {
String name= ((Filter) object).getName();
if (name.endsWith(".*") || name.equals(JUnitMessages.getString("JUnitMainTab.label.defaultpackage"))) { //$NON-NLS-1$ //$NON-NLS-2$
//package
return IMG_PKG;
} else if ("".equals(name)) { //$NON-NLS-1$
//needed for the in-place editor
return null;
} else if ((Character.isUpperCase(name.charAt(0))) && (name.indexOf('.') < 0)) {
//class in default package
return IMG_CUNIT;
} else {
//fully-qualified class or other filter
final int lastDotIndex= name.lastIndexOf('.');
if ((-1 != lastDotIndex) && ((name.length() - 1) != lastDotIndex) && Character.isUpperCase(name.charAt(lastDotIndex + 1)))
return IMG_CUNIT;
}
//other filter
return null;
}
}
/**
* Content provider for the filter table. Content consists of instances of
* Filter.
*/
private class StackFilterContentProvider implements IStructuredContentProvider {
private List fFilters;
public StackFilterContentProvider() {
List active= createActiveStackFiltersList();
List inactive= createInactiveStackFiltersList();
populateFilters(active, inactive);
}
public void setDefaults() {
fFilterViewer.remove(fFilters.toArray());
List active= createDefaultStackFiltersList();
List inactive= new ArrayList();
populateFilters(active, inactive);
}
protected void populateFilters(List activeList, List inactiveList) {
fFilters= new ArrayList(activeList.size() + inactiveList.size());
populateList(activeList, true);
if (inactiveList.size() != 0)
populateList(inactiveList, false);
}
protected void populateList(List list, boolean checked) {
Iterator iterator= list.iterator();
while (iterator.hasNext()) {
String name= (String) iterator.next();
addFilter(name, checked);
}
}
public Filter addFilter(String name, boolean checked) {
Filter filter= new Filter(name, checked);
if (!fFilters.contains(filter)) {
fFilters.add(filter);
fFilterViewer.add(filter);
fFilterViewer.setChecked(filter, checked);
}
updateActions();
return filter;
}
public void saveFilters() {
List active= new ArrayList(fFilters.size());
List inactive= new ArrayList(fFilters.size());
Iterator iterator= fFilters.iterator();
while (iterator.hasNext()) {
Filter filter= (Filter) iterator.next();
String name= filter.getName();
if (filter.isChecked())
active.add(name);
else
inactive.add(name);
}
String pref= JUnitPreferencePage.serializeList((String[]) active.toArray(new String[active.size()]));
getPreferenceStore().setValue(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST, pref);
pref= JUnitPreferencePage.serializeList((String[]) inactive.toArray(new String[inactive.size()]));
getPreferenceStore().setValue(IJUnitPreferencesConstants.PREF_INACTIVE_FILTERS_LIST, pref);
}
public void removeFilters(Object[] filters) {
for (int i= (filters.length - 1); i >= 0; --i) {
Filter filter= (Filter) filters[i];
fFilters.remove(filter);
}
fFilterViewer.remove(filters);
updateActions();
}
public void toggleFilter(Filter filter) {
boolean newState= !filter.isChecked();
filter.setChecked(newState);
fFilterViewer.setChecked(filter, newState);
}
public Object[] getElements(Object inputElement) {
return fFilters.toArray();
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}
public void dispose() {}
}
public JUnitPreferencePage() {
super();
setPreferenceStore(JUnitPlugin.getDefault().getPreferenceStore());
}
protected Control createContents(Composite parent) {
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.JUNIT_PREFERENCE_PAGE);
Composite composite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
layout.numColumns= 1;
layout.marginHeight= 0;
layout.marginWidth= 0;
composite.setLayout(layout);
GridData data= new GridData();
data.verticalAlignment= GridData.FILL;
data.horizontalAlignment= GridData.FILL;
composite.setLayoutData(data);
createStackFilterPreferences(composite);
return composite;
}
/**
* Create a group to contain the step filter related widgetry
*/
private void createStackFilterPreferences(Composite composite) {
Composite container= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
container.setLayout(layout);
GridData gd= new GridData(GridData.FILL_BOTH);
container.setLayoutData(gd);
createShowCheck(container);
createFilterTable(container);
createStepFilterButtons(container);
}
private void createShowCheck(Composite composite) {
GridData data;
fShowOnErrorCheck= new Button(composite, SWT.CHECK);
fShowOnErrorCheck.setText(JUnitMessages.getString("JUnitPreferencePage.showcheck.label")); //$NON-NLS-1$
data= new GridData();
data.horizontalAlignment= GridData.FILL;
data.horizontalSpan= 2;
fShowOnErrorCheck.setLayoutData(data);
fShowOnErrorCheck.setSelection(getShowOnErrorOnly());
}
private void createFilterTable(Composite container) {
fTableLabel= new Label(container, SWT.NONE);
fTableLabel.setText(JUnitMessages.getString("JUnitPreferencePage.filter.label")); //$NON-NLS-1$
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalSpan= 2;
fTableLabel.setLayoutData(gd);
fFilterTable= new Table(container, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
gd= new GridData(GridData.FILL_HORIZONTAL);
fFilterTable.setLayoutData(gd);
TableLayout tableLayout= new TableLayout();
ColumnLayoutData[] columnLayoutData= new ColumnLayoutData[1];
columnLayoutData[0]= new ColumnWeightData(100);
tableLayout.addColumnData(columnLayoutData[0]);
fFilterTable.setLayout(tableLayout);
new TableColumn(fFilterTable, SWT.NONE);
fFilterViewer= new CheckboxTableViewer(fFilterTable);
fTableEditor= new TableEditor(fFilterTable);
fFilterViewer.setLabelProvider(new FilterLabelProvider());
fFilterViewer.setSorter(new FilterViewerSorter());
fStackFilterContentProvider= new StackFilterContentProvider();
fFilterViewer.setContentProvider(fStackFilterContentProvider);
// input just needs to be non-null
fFilterViewer.setInput(this);
gd= new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fFilterViewer.getTable().setLayoutData(gd);
fFilterViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
Filter filter= (Filter) event.getElement();
fStackFilterContentProvider.toggleFilter(filter);
}
});
fFilterViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection= event.getSelection();
fRemoveFilterButton.setEnabled(!selection.isEmpty());
}
});
}
private void createStepFilterButtons(Composite container) {
Composite buttonContainer= new Composite(container, SWT.NONE);
GridData gd= new GridData(GridData.FILL_VERTICAL);
buttonContainer.setLayoutData(gd);
GridLayout buttonLayout= new GridLayout();
buttonLayout.numColumns= 1;
buttonLayout.marginHeight= 0;
buttonLayout.marginWidth= 0;
buttonContainer.setLayout(buttonLayout);
fAddFilterButton= new Button(buttonContainer, SWT.PUSH);
fAddFilterButton.setText(JUnitMessages.getString("JUnitPreferencePage.addfilterbutton.label")); //$NON-NLS-1$
fAddFilterButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.addfilterbutton.tooltip")); //$NON-NLS-1$
gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
fAddFilterButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fAddFilterButton);
fAddFilterButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
editFilter();
}
});
fAddTypeButton= new Button(buttonContainer, SWT.PUSH);
fAddTypeButton.setText(JUnitMessages.getString("JUnitPreferencePage.addtypebutton.label")); //$NON-NLS-1$
fAddTypeButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.addtypebutton.tooltip")); //$NON-NLS-1$
gd= getButtonGridData(fAddTypeButton);
fAddTypeButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fAddTypeButton);
fAddTypeButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
addType();
}
});
fAddPackageButton= new Button(buttonContainer, SWT.PUSH);
fAddPackageButton.setText(JUnitMessages.getString("JUnitPreferencePage.addpackagebutton.label")); //$NON-NLS-1$
fAddPackageButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.addpackagebutton.tooltip")); //$NON-NLS-1$
gd= getButtonGridData(fAddPackageButton);
fAddPackageButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fAddPackageButton);
fAddPackageButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
addPackage();
}
});
fRemoveFilterButton= new Button(buttonContainer, SWT.PUSH);
fRemoveFilterButton.setText(JUnitMessages.getString("JUnitPreferencePage.removefilterbutton.label")); //$NON-NLS-1$
fRemoveFilterButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.removefilterbutton.tooltip")); //$NON-NLS-1$
gd= getButtonGridData(fRemoveFilterButton);
fRemoveFilterButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fRemoveFilterButton);
fRemoveFilterButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
removeFilters();
}
});
fRemoveFilterButton.setEnabled(false);
fEnableAllButton= new Button(buttonContainer, SWT.PUSH);
fEnableAllButton.setText(JUnitMessages.getString("JUnitPreferencePage.enableallbutton.label")); //$NON-NLS-1$
fEnableAllButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.enableallbutton.tooltip")); //$NON-NLS-1$
gd= getButtonGridData(fEnableAllButton);
fEnableAllButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fEnableAllButton);
fEnableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
checkAllFilters(true);
}
});
fDisableAllButton= new Button(buttonContainer, SWT.PUSH);
fDisableAllButton.setText(JUnitMessages.getString("JUnitPreferencePage.disableallbutton.label")); //$NON-NLS-1$
fDisableAllButton.setToolTipText(JUnitMessages.getString("JUnitPreferencePage.disableallbutton.tooltip")); //$NON-NLS-1$
gd= getButtonGridData(fDisableAllButton);
fDisableAllButton.setLayoutData(gd);
SWTUtil.setButtonDimensionHint(fDisableAllButton);
fDisableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
checkAllFilters(false);
}
});
}
private GridData getButtonGridData(Button button) {
GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
int widthHint= convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
gd.widthHint= Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
gd.heightHint= convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT);
return gd;
}
public void init(IWorkbench workbench) {}
/**
* Create a new filter in the table (with the default 'new filter' value),
* then open up an in-place editor on it.
*/
private void editFilter() {
// if a previous edit is still in progress, finish it
if (fEditorText != null)
validateChangeAndCleanup();
fNewStackFilter= fStackFilterContentProvider.addFilter(DEFAULT_NEW_FILTER_TEXT, true);
fNewTableItem= fFilterTable.getItem(0);
// create & configure Text widget for editor
// Fix for bug 1766. Border behavior on for text fields varies per platform.
// On Motif, you always get a border, on other platforms,
// you don't. Specifying a border on Motif results in the characters
// getting pushed down so that only there very tops are visible. Thus,
// we have to specify different style constants for the different platforms.
int textStyles= SWT.SINGLE | SWT.LEFT;
if (!SWT.getPlatform().equals("motif")) //$NON-NLS-1$
textStyles |= SWT.BORDER;
fEditorText= new Text(fFilterTable, textStyles);
GridData gd= new GridData(GridData.FILL_BOTH);
fEditorText.setLayoutData(gd);
// set the editor
fTableEditor.horizontalAlignment= SWT.LEFT;
fTableEditor.grabHorizontal= true;
fTableEditor.setEditor(fEditorText, fNewTableItem, 0);
// get the editor ready to use
fEditorText.setText(fNewStackFilter.getName());
fEditorText.selectAll();
setEditorListeners(fEditorText);
fEditorText.setFocus();
}
private void setEditorListeners(Text text) {
// CR means commit the changes, ESC means abort and don't commit
text.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
if (event.character == SWT.CR) {
if (fInvalidEditorText != null) {
fEditorText.setText(fInvalidEditorText);
fInvalidEditorText= null;
} else
validateChangeAndCleanup();
} else if (event.character == SWT.ESC) {
removeNewFilter();
cleanupEditor();
}
}
});
// Consider loss of focus on the editor to mean the same as CR
text.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent event) {
if (fInvalidEditorText != null) {
fEditorText.setText(fInvalidEditorText);
fInvalidEditorText= null;
} else
validateChangeAndCleanup();
}
});
// Consume traversal events from the text widget so that CR doesn't
// traverse away to dialog's default button. Without this, hitting
// CR in the text field closes the entire dialog.
text.addListener(SWT.Traverse, new Listener() {
public void handleEvent(Event event) {
event.doit= false;
}
});
}
private void validateChangeAndCleanup() {
String trimmedValue= fEditorText.getText().trim();
// if the new value is blank, remove the filter
if (trimmedValue.length() < 1)
removeNewFilter();
// if it's invalid, beep and leave sitting in the editor
else if (!validateEditorInput(trimmedValue)) {
fInvalidEditorText= trimmedValue;
fEditorText.setText(JUnitMessages.getString("JUnitPreferencePage.invalidstepfilterreturnescape")); //$NON-NLS-1$
getShell().getDisplay().beep();
return;
// otherwise, commit the new value if not a duplicate
} else {
Object[] filters= fStackFilterContentProvider.getElements(null);
for (int i= 0; i < filters.length; i++) {
Filter filter= (Filter) filters[i];
if (filter.getName().equals(trimmedValue)) {
removeNewFilter();
cleanupEditor();
return;
}
}
fNewTableItem.setText(trimmedValue);
fNewStackFilter.setName(trimmedValue);
fFilterViewer.refresh();
}
cleanupEditor();
}
/**
* Cleanup all widgetry & resources used by the in-place editing
*/
private void cleanupEditor() {
if (fEditorText == null)
return;
fNewStackFilter= null;
fNewTableItem= null;
fTableEditor.setEditor(null, null, 0);
fEditorText.dispose();
fEditorText= null;
}
private void removeNewFilter() {
fStackFilterContentProvider.removeFilters(new Object[] { fNewStackFilter });
}
/**
* A valid step filter is simply one that is a valid Java identifier.
* and, as defined in the JDI spec, the regular expressions used for
* step filtering must be limited to exact matches or patterns that
* begin with '*' or end with '*'. Beyond this, a string cannot be validated
* as corresponding to an existing type or package (and this is probably not
* even desirable).
*/
private boolean validateEditorInput(String trimmedValue) {
char firstChar= trimmedValue.charAt(0);
if ((!(Character.isJavaIdentifierStart(firstChar)) || (firstChar == '*')))
return false;
int length= trimmedValue.length();
for (int i= 1; i < length; i++) {
char c= trimmedValue.charAt(i);
if (!Character.isJavaIdentifierPart(c)) {
if (c == '.' && i != (length - 1))
continue;
if (c == '*' && i == (length - 1))
continue;
return false;
}
}
return true;
}
private void addType() {
Shell shell= getShell();
SelectionDialog dialog= null;
try {
dialog=
JavaUI.createTypeDialog(
shell,
new ProgressMonitorDialog(shell),
SearchEngine.createWorkspaceScope(),
IJavaElementSearchConstants.CONSIDER_CLASSES,
false);
} catch (JavaModelException jme) {
String title= JUnitMessages.getString("JUnitPreferencePage.addtypedialog.title"); //$NON-NLS-1$
String message= JUnitMessages.getString("JUnitPreferencePage.addtypedialog.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(jme, shell, title, message);
return;
}
dialog.setTitle(JUnitMessages.getString("JUnitPreferencePage.addtypedialog.title")); //$NON-NLS-1$
dialog.setMessage(JUnitMessages.getString("JUnitPreferencePage.addtypedialog.message")); //$NON-NLS-1$
if (dialog.open() == IDialogConstants.CANCEL_ID)
return;
Object[] types= dialog.getResult();
if (types != null && types.length > 0) {
IType type= (IType) types[0];
fStackFilterContentProvider.addFilter(type.getFullyQualifiedName(), true);
}
}
private void addPackage() {
Shell shell= getShell();
ElementListSelectionDialog dialog= null;
try {
dialog= JUnitPlugin.createAllPackagesDialog(shell, null, true);
} catch (JavaModelException jme) {
String title= JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.title"); //$NON-NLS-1$
String message= JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(jme, shell, title, message);
return;
}
dialog.setTitle(JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.title")); //$NON-NLS-1$
dialog.setMessage(JUnitMessages.getString("JUnitPreferencePage.addpackagedialog.message")); //$NON-NLS-1$
dialog.setMultipleSelection(true);
if (dialog.open() == IDialogConstants.CANCEL_ID)
return;
Object[] packages= dialog.getResult();
if (packages == null)
return;
for (int i= 0; i < packages.length; i++) {
IJavaElement pkg= (IJavaElement) packages[i];
String filter= pkg.getElementName();
if (filter.length() < 1)
filter= JUnitMessages.getString("JUnitMainTab.label.defaultpackage"); //$NON-NLS-1$
else
filter += ".*"; //$NON-NLS-1$
fStackFilterContentProvider.addFilter(filter, true);
}
}
private void removeFilters() {
IStructuredSelection selection= (IStructuredSelection) fFilterViewer.getSelection();
fStackFilterContentProvider.removeFilters(selection.toArray());
}
private void checkAllFilters(boolean check) {
Object[] filters= fStackFilterContentProvider.getElements(null);
for (int i= (filters.length - 1); i >= 0; --i)
((Filter) filters[i]).setChecked(check);
fFilterViewer.setAllChecked(check);
}
public boolean performOk() {
IPreferenceStore store= getPreferenceStore();
store.setValue(IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY, fShowOnErrorCheck.getSelection());
fStackFilterContentProvider.saveFilters();
return true;
}
protected void performDefaults() {
setDefaultValues();
super.performDefaults();
}
private void setDefaultValues() {
fStackFilterContentProvider.setDefaults();
}
/**
* Returns the default list of active stack filters.
*
* @return list
*/
protected List createDefaultStackFiltersList() {
return Arrays.asList(fgDefaultFilterPatterns);
}
/**
* Returns a list of active stack filters.
*
* @return list
*/
protected List createActiveStackFiltersList() {
return Arrays.asList(getFilterPatterns());
}
/**
* Returns a list of active stack filters.
*
* @return list
*/
protected List createInactiveStackFiltersList() {
String[] strings=
JUnitPreferencePage.parseList(getPreferenceStore().getString(IJUnitPreferencesConstants.PREF_INACTIVE_FILTERS_LIST));
return Arrays.asList(strings);
}
protected void updateActions() {
if (fEnableAllButton == null)
return;
boolean enabled= fFilterViewer.getTable().getItemCount() > 0;
fEnableAllButton.setEnabled(enabled);
fDisableAllButton.setEnabled(enabled);
}
public static String[] getFilterPatterns() {
IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore();
return JUnitPreferencePage.parseList(store.getString(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST));
}
public static boolean getFilterStack() {
IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore();
return store.getBoolean(IJUnitPreferencesConstants.DO_FILTER_STACK);
}
public static void setFilterStack(boolean filter) {
IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore();
store.setValue(IJUnitPreferencesConstants.DO_FILTER_STACK, filter);
}
public static void initializeDefaults(IPreferenceStore store) {
store.setDefault(IJUnitPreferencesConstants.DO_FILTER_STACK, true);
store.setDefault(IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY, false);
String list= store.getString(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST);
if ("".equals(list)) { //$NON-NLS-1$
String pref= JUnitPreferencePage.serializeList(fgDefaultFilterPatterns);
store.setValue(IJUnitPreferencesConstants.PREF_ACTIVE_FILTERS_LIST, pref);
}
store.setValue(IJUnitPreferencesConstants.PREF_INACTIVE_FILTERS_LIST, ""); //$NON-NLS-1$
}
public static boolean getShowOnErrorOnly() {
IPreferenceStore store= JUnitPlugin.getDefault().getPreferenceStore();
return store.getBoolean(IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY);
}
/**
* Parses the comma separated string into an array of strings
*
* @return list
*/
private static String[] parseList(String listString) {
List list= new ArrayList(10);
StringTokenizer tokenizer= new StringTokenizer(listString, ","); //$NON-NLS-1$
while (tokenizer.hasMoreTokens())
list.add(tokenizer.nextToken());
return (String[]) list.toArray(new String[list.size()]);
}
/**
* Serializes the array of strings into one comma
* separated string.
*
* @param list array of strings
* @return a single string composed of the given list
*/
private static String serializeList(String[] list) {
if (list == null)
return ""; //$NON-NLS-1$
StringBuffer buffer= new StringBuffer();
for (int i= 0; i < list.length; i++) {
if (i > 0)
buffer.append(',');
buffer.append(list[i]);
}
return buffer.toString();
}
}
|
25,324 |
Bug 25324 Ability to know when tests are finished [junit]
|
Hi, I'm writing a Cactus Plugin that extends the JUnit Plugin and I need to know when the tests have finished running in the TestRunner. There is a nice ITestRunListener interface for that. My idea was thus to implement this interface and somehow register my listener to the TestRunner (RemoteTestRunnerClient). However: 1/ Currently the RemoteTestRunnerClient implementation only supports one listener 2/ There is no API in TestRunnerViewPart to get access to the TestRunner I am attaching a patch that should provide this facility. However, I need your help to know if this is the right approach or not. Thank you -Vincent
|
resolved fixed
|
f2b66ff
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T11:04:18Z | 2002-10-24T14:33:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/RemoteTestRunnerClient.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import org.eclipse.jdt.internal.junit.runner.ITestRunListener;
import org.eclipse.jdt.internal.junit.runner.MessageIds;
/**
* The client side of the RemoteTestRunner. Handles the
* marshalling of th different messages.
*/
public class RemoteTestRunnerClient {
/**
* A listener that is informed about test events.
*/
private ITestRunListener fListener;
/**
* The server socket
*/
private ServerSocket fServerSocket;
private Socket fSocket;
private int fPort= -1;
private PrintWriter fWriter;
private BufferedReader fBufferedReader;
/**
* RemoteTestRunner is sending trace.
*/
private boolean fInReadTrace= false;
/**
* RemoteTestRunner is sending the rerun trace.
*/
private boolean fInReadRerunTrace= false;
/**
* The currently received failed message
*/
private boolean fInFailedMessage= false;
/**
* The failed test that is currently reported from the RemoteTestRunner
*/
private String fFailedTest;
/**
* The failed message that is currently reported from the RemoteTestRunner
*/
private String fFailedMessage;
/**
* The failed trace that is currently reported from the RemoteTestRunner
*/
private String fFailedTrace;
/**
* The failed trace of a reran test
*/
private String fFailedRerunTrace;
/**
* The kind of failure of the test that is currently reported as failed
*/
private int fFailureKind;
private boolean fDebug= false;
/**
* Reads the message stream from the RemoteTestRunner
*/
private class ServerConnection extends Thread {
int fPort;
public ServerConnection(int port) {
super("ServerConnection"); //$NON-NLS-1$
fPort= port;
}
public void run() {
try {
if (fDebug)
System.out.println("Creating server socket "+fPort); //$NON-NLS-1$
fServerSocket= new ServerSocket(fPort);
fSocket= fServerSocket.accept();
fBufferedReader= new BufferedReader(new InputStreamReader(fSocket.getInputStream()));
fWriter= new PrintWriter(fSocket.getOutputStream(), true);
String message;
while(fBufferedReader != null && (message= readMessage(fBufferedReader)) != null)
receiveMessage(message);
} catch (SocketException e) {
fListener.testRunTerminated();
} catch (IOException e) {
System.out.println(e);
// fall through
}
shutDown();
}
}
/**
* Start listening to a test run. Start a server connection that
* the RemoteTestRunner can connect to.
*/
public synchronized void startListening(ITestRunListener listener, int port) {
fListener= listener;
fPort= port;
ServerConnection connection= new ServerConnection(port);
connection.start();
}
/**
* Requests to stop the remote test run.
*/
public synchronized void stopTest() {
if (isRunning()) {
fWriter.println(MessageIds.TEST_STOP);
fWriter.flush();
}
}
/**
* Requests to rerun a test
*/
public synchronized void rerunTest(String className, String testName) {
if (isRunning()) {
fWriter.println(MessageIds.TEST_RERUN+className+" "+testName); //$NON-NLS-1$
fWriter.flush();
}
}
private synchronized void shutDown() {
if (fDebug)
System.out.println("shutdown "+fPort); //$NON-NLS-1$
if (fWriter != null) {
fWriter.close();
fWriter= null;
}
try {
if (fBufferedReader != null) {
fBufferedReader.close();
fBufferedReader= null;
}
} catch(IOException e) {
}
try{
if(fSocket != null) {
fSocket.close();
fSocket= null;
}
} catch(IOException e) {
}
try{
if(fServerSocket != null) {
fServerSocket.close();
fServerSocket= null;
}
} catch(IOException e) {
}
}
public boolean isRunning() {
return fSocket != null;
}
private String readMessage(BufferedReader in) throws IOException {
return in.readLine();
}
private void receiveMessage(String message) {
if (message.startsWith(MessageIds.TRACE_START)) {
fInReadTrace= true;
fFailedTrace= ""; //$NON-NLS-1$
return;
}
if (message.startsWith(MessageIds.TRACE_END)) {
fInReadTrace= false;
fListener.testFailed(fFailureKind, fFailedTest, fFailedTrace);
fFailedTrace= ""; //$NON-NLS-1$
return;
}
if (fInReadTrace) {
fFailedTrace+= message + '\n';
return;
}
if (message.startsWith(MessageIds.RTRACE_START)) {
fInReadRerunTrace= true;
fFailedRerunTrace= ""; //$NON-NLS-1$
return;
}
if (message.startsWith(MessageIds.RTRACE_END)) {
fInReadRerunTrace= false;
return;
}
if (fInReadRerunTrace) {
fFailedRerunTrace+= message + '\n';
return;
}
String arg= message.substring(MessageIds.MSG_HEADER_LENGTH);
if (message.startsWith(MessageIds.TEST_RUN_START)) {
int count= Integer.parseInt(arg);
fListener.testRunStarted(count);
return;
}
if (message.startsWith(MessageIds.TEST_START)) {
fListener.testStarted(arg);
return;
}
if (message.startsWith(MessageIds.TEST_END)) {
fListener.testEnded(arg);
return;
}
if (message.startsWith(MessageIds.TEST_ERROR)) {
fFailedTest= arg;
fFailureKind= ITestRunListener.STATUS_ERROR;
return;
}
if (message.startsWith(MessageIds.TEST_FAILED)) {
fFailedTest= arg;
fFailureKind= ITestRunListener.STATUS_FAILURE;
return;
}
if (message.startsWith(MessageIds.TEST_RUN_END)) {
long elapsedTime= Long.parseLong(arg);
fListener.testRunEnded(elapsedTime);
return;
}
if (message.startsWith(MessageIds.TEST_STOPPED)) {
long elapsedTime= Long.parseLong(arg);
fListener.testRunStopped(elapsedTime);
shutDown();
return;
}
if (message.startsWith(MessageIds.TEST_TREE)) {
fListener.testTreeEntry(arg);
return;
}
if (message.startsWith(MessageIds.TEST_RERAN)) {
// format: className" "testName" "status
// status: FAILURE, ERROR, OK
int c= arg.indexOf(" "); //$NON-NLS-1$
int t= arg.indexOf(" ", c+1); //$NON-NLS-1$
String className= arg.substring(0, c);
String testName= arg.substring(c+1, t);
String status= arg.substring(t+1);
int statusCode= ITestRunListener.STATUS_OK;
if (status.equals("FAILURE")) //$NON-NLS-1$
statusCode= ITestRunListener.STATUS_FAILURE;
else if (status.equals("ERROR")) //$NON-NLS-1$
statusCode= ITestRunListener.STATUS_ERROR;
String trace= ""; //$NON-NLS-1$
if (statusCode != ITestRunListener.STATUS_OK)
trace= fFailedRerunTrace; // assumption a rerun trace was sent before
fListener.testReran(className, testName, statusCode, trace);
}
}
}
|
25,324 |
Bug 25324 Ability to know when tests are finished [junit]
|
Hi, I'm writing a Cactus Plugin that extends the JUnit Plugin and I need to know when the tests have finished running in the TestRunner. There is a nice ITestRunListener interface for that. My idea was thus to implement this interface and somehow register my listener to the TestRunner (RemoteTestRunnerClient). However: 1/ Currently the RemoteTestRunnerClient implementation only supports one listener 2/ There is no API in TestRunnerViewPart to get access to the TestRunner I am attaching a patch that should provide this facility. However, I need your help to know if this is the right approach or not. Thank you -Vincent
|
resolved fixed
|
f2b66ff
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T11:04:18Z | 2002-10-24T14:33:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunnerViewPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.junit.ui;
import java.net.MalformedURLException;
import java.text.NumberFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.*;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
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.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.internal.junit.runner.ITestRunListener;
/**
* A ViewPart that shows the results of a test run.
*/
public class TestRunnerViewPart extends ViewPart implements ITestRunListener, IPropertyChangeListener {
public static final String NAME= "org.eclipse.jdt.junit.ResultView"; //$NON-NLS-1$
/**
* Number of executed tests during a test run
*/
protected int fExecutedTests;
/**
* Number of errors during this test run
*/
protected int fErrors;
/**
* Number of failures during this test run
*/
protected int fFailures;
/**
* Number of tests run
*/
private int fTestCount;
/**
* Map storing TestInfos for each executed test keyed by
* the test name.
*/
private Map fTestInfos = new HashMap();
/**
* The first failure of a test run. Used to reveal the
* first failed tests at the end of a run.
*/
private TestRunInfo fFirstFailure;
private JUnitProgressBar fProgressBar;
private ProgressImages fProgressImages;
private Image fViewImage;
private CounterPanel fCounterPanel;
private boolean fShowOnErrorOnly= false;
/**
* The view that shows the stack trace of a failure
*/
private FailureTraceView fFailureView;
/**
* The collection of ITestRunViews
*/
private Vector fTestRunViews = new Vector();
/**
* The currently active run view
*/
private ITestRunView fActiveRunView;
/**
* Is the UI disposed
*/
private boolean fIsDisposed= false;
/**
* The launched project
*/
private IJavaProject fTestProject;
/**
* The launcher that has started the test
*/
private String fLaunchMode;
private ILaunch fLastLaunch= null;
/**
* The client side of the remote test runner
*/
private RemoteTestRunnerClient fTestRunnerClient;
final Image fStackViewIcon= TestRunnerViewPart.createImage("cview16/stackframe.gif");//$NON-NLS-1$
final Image fTestRunOKIcon= TestRunnerViewPart.createImage("cview16/junitsucc.gif"); //$NON-NLS-1$
final Image fTestRunFailIcon= TestRunnerViewPart.createImage("cview16/juniterr.gif"); //$NON-NLS-1$
final Image fTestRunOKDirtyIcon= TestRunnerViewPart.createImage("cview16/junitsuccq.gif"); //$NON-NLS-1$
final Image fTestRunFailDirtyIcon= TestRunnerViewPart.createImage("cview16/juniterrq.gif"); //$NON-NLS-1$
Image fOriginalViewImage= null;
IElementChangedListener fDirtyListener= null;
private class StopAction extends Action{
public StopAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.stopaction.text"));//$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.stopaction.tooltip"));//$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/stop.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/stop.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/stop.gif")); //$NON-NLS-1$
}
public void run() {
stopTest();
}
}
private class RerunLastAction extends Action{
public RerunLastAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.label")); //$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.tooltip")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/relaunch.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/relaunch.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/relaunch.gif")); //$NON-NLS-1$
}
public void run(){
rerunTestRun();
}
}
/**
* Listen for for modifications to Java elements
*/
private class DirtyListener implements IElementChangedListener {
public void elementChanged(ElementChangedEvent event) {
processDelta(event.getDelta());
}
private boolean processDelta(IJavaElementDelta delta) {
int kind= delta.getKind();
int details= delta.getFlags();
int type= delta.getElement().getElementType();
switch (type) {
// Consider containers for class files.
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.PACKAGE_FRAGMENT:
// If we did some different than changing a child we flush the the undo / redo stack.
if (kind != IJavaElementDelta.CHANGED || details != IJavaElementDelta.F_CHILDREN) {
codeHasChanged();
return false;
}
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit unit= (ICompilationUnit)delta.getElement();
// If we change a working copy we do nothing
if (unit.isWorkingCopy()) {
// Don't examine children of a working copy but keep processing siblings.
return true;
} else {
codeHasChanged();
return false;
}
case IJavaElement.CLASS_FILE:
// Don't examine children of a class file but keep on examining siblings.
return true;
default:
codeHasChanged();
return false;
}
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren == null)
return true;
for (int i= 0; i < affectedChildren.length; i++) {
if (!processDelta(affectedChildren[i]))
return false;
}
return true;
}
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void stopTest() {
if (fTestRunnerClient != null)
fTestRunnerClient.stopTest();
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void rerunTestRun() {
if (fLastLaunch != null && fLastLaunch.getLaunchConfiguration() != null) {
try {
DebugUITools.saveAndBuildBeforeLaunch();
fLastLaunch.getLaunchConfiguration().launch(fLastLaunch.getLaunchMode(), null);
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
}
/*
* @see ITestRunListener#testRunStarted(testCount)
*/
public void testRunStarted(final int testCount){
reset(testCount);
fShowOnErrorOnly= JUnitPreferencePage.getShowOnErrorOnly();
fExecutedTests++;
}
/*
* @see ITestRunListener#testRunEnded
*/
public void testRunEnded(long elapsedTime){
fExecutedTests--;
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.finish", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$
postInfo(msg);
postAsyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
if (fFirstFailure != null) {
fActiveRunView.setSelectedTest(fFirstFailure.fTestName);
handleTestSelected(fFirstFailure.fTestName);
}
updateViewIcon();
if (fDirtyListener == null) {
fDirtyListener= new DirtyListener();
JavaCore.addElementChangedListener(fDirtyListener);
}
}
});
}
private void updateViewIcon() {
if (fErrors+fFailures > 0)
fViewImage= fTestRunFailIcon;
else
fViewImage= fTestRunOKIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
private String elapsedTimeAsString(long runTime) {
return NumberFormat.getInstance().format((double)runTime/1000);
}
/*
* @see ITestRunListener#testRunStopped
*/
public void testRunStopped(final long elapsedTime) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.stopped", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$
postInfo(msg);
postAsyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
resetViewIcon();
}
});
}
private void resetViewIcon() {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
/*
* @see ITestRunListener#testRunTerminated
*/
public void testRunTerminated() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.terminated"); //$NON-NLS-1$
showMessage(msg);
}
private void showMessage(String msg) {
showInformation(msg);
postError(msg);
}
/*
* @see ITestRunListener#testStarted
*/
public void testStarted(String testName) {
// reveal the part when the first test starts
if (!fShowOnErrorOnly && fExecutedTests == 1)
postShowTestResultsView();
postInfo(JUnitMessages.getFormattedString("TestRunnerViewPart.message.started", testName)); //$NON-NLS-1$
TestRunInfo testInfo= getTestInfo(testName);
if (testInfo == null)
fTestInfos.put(testName, new TestRunInfo(testName));
}
/*
* @see ITestRunListener#testEnded
*/
public void testEnded(String testName){
postEndTest(testName);
fExecutedTests++;
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testName, String trace){
TestRunInfo testInfo= getTestInfo(testName);
if (testInfo == null) {
testInfo= new TestRunInfo(testName);
fTestInfos.put(testName, testInfo);
}
testInfo.fTrace= trace;
testInfo.fStatus= status;
if (status == ITestRunListener.STATUS_ERROR)
fErrors++;
else
fFailures++;
if (fFirstFailure == null)
fFirstFailure= testInfo;
// show the view on the first error only
if (fShowOnErrorOnly && (fErrors + fFailures == 1))
postShowTestResultsView();
}
/*
* @see ITestRunListener#testReran
*/
public void testReran(String className, String testName, int status, String trace) {
if (status == ITestRunListener.STATUS_ERROR) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.error", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else if (status == ITestRunListener.STATUS_FAILURE) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.failure", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.success", new String[]{testName, className}); //$NON-NLS-1$
postInfo(msg);
}
String test= testName+"("+className+")"; //$NON-NLS-1$ //$NON-NLS-2$
TestRunInfo info= getTestInfo(test);
updateTest(info, status);
if (info.fTrace == null || !info.fTrace.equals(trace)) {
info.fTrace= trace;
showFailure(info.fTrace);
}
}
private void updateTest(TestRunInfo info, final int status) {
if (status == info.fStatus)
return;
if (info.fStatus == ITestRunListener.STATUS_OK) {
if (status == ITestRunListener.STATUS_FAILURE)
fFailures++;
else if (status == ITestRunListener.STATUS_ERROR)
fErrors++;
} else if (info.fStatus == ITestRunListener.STATUS_ERROR) {
if (status == ITestRunListener.STATUS_OK)
fErrors--;
else if (status == ITestRunListener.STATUS_FAILURE) {
fErrors--;
fFailures++;
}
} else if (info.fStatus == ITestRunListener.STATUS_FAILURE) {
if (status == ITestRunListener.STATUS_OK)
fFailures--;
else if (status == ITestRunListener.STATUS_ERROR) {
fFailures--;
fErrors++;
}
}
info.fStatus= status;
final TestRunInfo finalInfo= info;
postAsyncRunnable(new Runnable() {
public void run() {
refreshCounters();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.testStatusChanged(finalInfo);
}
}
});
}
/*
* @see ITestRunListener#testTreeEntry
*/
public void testTreeEntry(final String treeEntry){
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.newTreeEntry(treeEntry);
}
}
});
}
public void startTestRunListening(IJavaElement type, int port, ILaunch launch) {
fTestProject= type.getJavaProject();
fLaunchMode= launch.getLaunchMode();
aboutToLaunch();
if (fTestRunnerClient != null) {
stopTest();
}
fTestRunnerClient= new RemoteTestRunnerClient();
fTestRunnerClient.startListening(this, port);
fLastLaunch= launch;
String title= JUnitMessages.getFormattedString("TestRunnerViewPart.title", type.getElementName()); //$NON-NLS-1$
setTitle(title);
if (type instanceof IType)
setTitleToolTip(((IType)type).getFullyQualifiedName());
else
setTitleToolTip(type.getElementName());
}
private void aboutToLaunch() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.launching"); //$NON-NLS-1$
showInformation(msg);
postInfo(msg);
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
public void rerunTest(String className, String testName) {
DebugUITools.saveAndBuildBeforeLaunch();
if (fTestRunnerClient != null && fTestRunnerClient.isRunning() && ILaunchManager.DEBUG_MODE.equals(fLaunchMode))
fTestRunnerClient.rerunTest(className, testName);
else if (fLastLaunch != null) {
// run the selected test using the previous launch configuration
ILaunchConfiguration launchConfiguration= fLastLaunch.getLaunchConfiguration();
if (launchConfiguration != null) {
try {
ILaunchConfigurationWorkingCopy tmp= launchConfiguration.copy("Rerun "+testName); //$NON-NLS-1$
tmp.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName);
tmp.launch(fLastLaunch.getLaunchMode(), null);
return;
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
MessageDialog.openInformation(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.cannotrerun.title"), //$NON-NLS-1$
JUnitMessages.getString("TestRunnerViewPart.cannotrerurn.message") //$NON-NLS-1$
);
}
}
public synchronized void dispose(){
fIsDisposed= true;
stopTest();
if (fProgressImages != null)
fProgressImages.dispose();
JUnitPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
fTestRunOKIcon.dispose();
fTestRunFailIcon.dispose();
fStackViewIcon.dispose();
fTestRunOKDirtyIcon.dispose();
fTestRunFailDirtyIcon.dispose();
}
private void start(final int total) {
resetProgressBar(total);
fCounterPanel.setTotal(total);
fCounterPanel.setRunValue(0);
}
private void resetProgressBar(final int total) {
fProgressBar.reset();
fProgressBar.setMaximum(total);
}
private void postSyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void postAsyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void aboutToStart() {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed()) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.aboutToStart();
}
}
}
});
}
private void postEndTest(final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
handleEndTest();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.endTest(testName);
}
}
});
}
private void handleEndTest() {
refreshCounters();
fProgressBar.step(fFailures+fErrors);
if (fShowOnErrorOnly) {
Image progress= fProgressImages.getImage(fExecutedTests, fTestCount, fErrors, fFailures);
if (progress != fViewImage) {
fViewImage= progress;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
private void refreshCounters() {
fCounterPanel.setErrorValue(fErrors);
fCounterPanel.setFailureValue(fFailures);
fCounterPanel.setRunValue(fExecutedTests);
}
protected void postShowTestResultsView() {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
showTestResultsView();
}
});
}
public void showTestResultsView() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IWorkbenchPage page= window.getActivePage();
TestRunnerViewPart testRunner= null;
if (page != null) {
try { // show the result view
testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
if(testRunner == null) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the console
page.activate(activePart);
} else {
page.bringToTop(testRunner);
}
} catch (PartInitException pie) {
JUnitPlugin.log(pie);
}
}
}
protected void postInfo(final String message) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setErrorMessage(null);
getStatusLine().setMessage(message);
}
});
}
protected void postError(final String message) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(message);
}
});
}
protected void showInformation(final String info){
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.setInformation(info);
}
});
}
private CTabFolder createTestRunViews(Composite parent) {
CTabFolder tabFolder= new CTabFolder(parent, SWT.TOP);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL));
ITestRunView failureRunView= new FailureRunView(tabFolder, this);
ITestRunView testHierarchyRunView= new HierarchyRunView(tabFolder, this);
fTestRunViews.addElement(failureRunView);
fTestRunViews.addElement(testHierarchyRunView);
tabFolder.setSelection(0);
fActiveRunView= (ITestRunView)fTestRunViews.firstElement();
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
testViewChanged(event);
}
});
return tabFolder;
}
private void testViewChanged(SelectionEvent event) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
if (((CTabFolder) event.widget).getSelection().getText() == v.getName()){
v.setSelectedTest(fActiveRunView.getTestName());
fActiveRunView= v;
fActiveRunView.activate();
}
}
}
private SashForm createSashForm(Composite parent) {
SashForm sashForm= new SashForm(parent, SWT.VERTICAL);
ViewForm top= new ViewForm(sashForm, SWT.NONE);
CTabFolder tabFolder= createTestRunViews(top);
tabFolder.setLayoutData(new TabFolderLayout());
top.setContent(tabFolder);
ViewForm bottom= new ViewForm(sashForm, SWT.NONE);
ToolBar failureToolBar= new ToolBar(bottom, SWT.FLAT | SWT.WRAP);
bottom.setTopCenter(failureToolBar);
fFailureView= new FailureTraceView(bottom, this);
bottom.setContent(fFailureView.getComposite());
CLabel label= new CLabel(bottom, SWT.NONE);
label.setText(JUnitMessages.getString("TestRunnerViewPart.label.failure")); //$NON-NLS-1$
label.setImage(fStackViewIcon);
bottom.setTopLeft(label);
// fill the failure trace viewer toolbar
ToolBarManager failureToolBarmanager= new ToolBarManager(failureToolBar);
failureToolBarmanager.add(new EnableStackFilterAction(fFailureView));
failureToolBarmanager.update(true);
sashForm.setWeights(new int[]{50, 50});
return sashForm;
}
private void reset(final int testCount) {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
fCounterPanel.reset();
fFailureView.clear();
fProgressBar.reset();
clearStatus();
start(testCount);
}
});
fExecutedTests= 0;
fFailures= 0;
fErrors= 0;
fTestCount= testCount;
aboutToStart();
fTestInfos.clear();
fFirstFailure= null;
}
private void clearStatus() {
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(null);
}
public void setFocus() {
if (fActiveRunView != null)
fActiveRunView.setFocus();
}
public void createPartControl(Composite parent) {
GridLayout gridLayout= new GridLayout();
gridLayout.marginWidth= 0;
parent.setLayout(gridLayout);
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
toolBar.add(new StopAction());
toolBar.add(new RerunLastAction());
actionBars.updateActionBars();
Composite counterPanel= createProgressCountPanel(parent);
counterPanel.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
SashForm sashForm= createSashForm(parent);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
actionBars.setGlobalActionHandler(
IWorkbenchActionConstants.COPY,
new CopyTraceAction(fFailureView));
JUnitPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fOriginalViewImage= getTitleImage();
fProgressImages= new ProgressImages();
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.RESULTS_VIEW);
}
private IStatusLineManager getStatusLine() {
// we want to show messages globally hence we
// have to go throgh the active part
IViewSite site= getViewSite();
IWorkbenchPage page= site.getPage();
IWorkbenchPart activePart= page.getActivePart();
if (activePart instanceof IViewPart) {
IViewPart activeViewPart= (IViewPart)activePart;
IViewSite activeViewSite= activeViewPart.getViewSite();
return activeViewSite.getActionBars().getStatusLineManager();
}
if (activePart instanceof IEditorPart) {
IEditorPart activeEditorPart= (IEditorPart)activePart;
IEditorActionBarContributor contributor= activeEditorPart.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor)
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
// no active part
return getViewSite().getActionBars().getStatusLineManager();
}
private Composite createProgressCountPanel(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
fProgressBar = new JUnitProgressBar(composite);
fProgressBar.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
fCounterPanel = new CounterPanel(composite);
fCounterPanel.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
return composite;
}
public TestRunInfo getTestInfo(String testName) {
if (testName == null)
return null;
return (TestRunInfo) fTestInfos.get(testName);
}
public void handleTestSelected(String testName) {
TestRunInfo testInfo= getTestInfo(testName);
if (testInfo == null) {
showFailure(""); //$NON-NLS-1$
} else {
showFailure(testInfo.fTrace);
}
}
private void showFailure(final String failure) {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.showFailure(failure);
}
});
}
public IJavaProject getLaunchedProject() {
return fTestProject;
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
private boolean isDisposed() {
return fIsDisposed || fCounterPanel.isDisposed();
}
private Display getDisplay() {
return getViewSite().getShell().getDisplay();
}
/**
* @see IWorkbenchPart#getTitleImage()
*/
public Image getTitleImage() {
if (fOriginalViewImage == null)
fOriginalViewImage= super.getTitleImage();
if (fViewImage == null)
return super.getTitleImage();
return fViewImage;
}
public void propertyChange(PropertyChangeEvent event) {
if (isDisposed())
return;
if (IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY.equals(event.getProperty())) {
if (!JUnitPreferencePage.getShowOnErrorOnly()) {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
void codeHasChanged() {
postAsyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
if (fDirtyListener != null) {
JavaCore.removeElementChangedListener(fDirtyListener);
fDirtyListener= null;
}
if (fViewImage == fTestRunOKIcon)
fViewImage= fTestRunOKDirtyIcon;
else if (fViewImage == fTestRunFailIcon)
fViewImage= fTestRunFailDirtyIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
});
}
boolean isCreated() {
return fCounterPanel != null;
}
}
|
25,324 |
Bug 25324 Ability to know when tests are finished [junit]
|
Hi, I'm writing a Cactus Plugin that extends the JUnit Plugin and I need to know when the tests have finished running in the TestRunner. There is a nice ITestRunListener interface for that. My idea was thus to implement this interface and somehow register my listener to the TestRunner (RemoteTestRunnerClient). However: 1/ Currently the RemoteTestRunnerClient implementation only supports one listener 2/ There is no API in TestRunnerViewPart to get access to the TestRunner I am attaching a patch that should provide this facility. However, I need your help to know if this is the right approach or not. Thank you -Vincent
|
resolved fixed
|
f2b66ff
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T11:04:18Z | 2002-10-24T14:33:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/ITestRunListener.java
| |
31,075 |
Bug 31075 Code Templates are not preserved
|
the new code templates are a great feature. The problem is when you close eclipse and start it up again they seem to be reset to the defaults.
|
resolved fixed
|
938fd9a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T14:43:10Z | 2003-02-06T11:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeTemplateBlock.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
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.SourceViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.corext.template.Template;
import org.eclipse.jdt.internal.corext.template.TemplateSet;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
/**
*/
public class CodeTemplateBlock {
private class CodeTemplateAdapter implements ITreeListAdapter, IDialogFieldListener {
private final Object[] NO_CHILDREN= new Object[0];
private CodeTemplates fTemplates;
public CodeTemplateAdapter(CodeTemplates templates) {
fTemplates= templates;
}
public void customButtonPressed(TreeListDialogField field, int index) {
doButtonPressed(index, field.getSelectedElements());
}
public void selectionChanged(TreeListDialogField field) {
List selected= field.getSelectedElements();
field.enableButton(IDX_EDIT, canEdit(selected));
field.enableButton(IDX_EXPORT, !selected.isEmpty());
updateSourceViewerInput(selected);
}
public void doubleClicked(TreeListDialogField field) {
List selected= field.getSelectedElements();
if (canEdit(selected)) {
doButtonPressed(IDX_EDIT, selected);
}
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element == COMMENT_NODE || element == CODE_NODE) {
return getTemplateOfCategory(element == COMMENT_NODE);
}
return NO_CHILDREN;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof Template) {
Template template= (Template) element;
if (template.getName().endsWith(CodeTemplates.COMMENT_SUFFIX)) {
return COMMENT_NODE;
}
return CODE_NODE;
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return (element == COMMENT_NODE || element == CODE_NODE);
}
public void dialogFieldChanged(DialogField field) {
}
}
private static class CodeTemplateLabelProvider extends LabelProvider {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
*/
public Image getImage(Object element) {
if (element == COMMENT_NODE) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG);
}
if (element == CODE_NODE) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPCONT);
}
Template template = (Template) element;
String name= template.getName();
if (CodeTemplates.CATCHBLOCK.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
} else if (CodeTemplates.METHODSTUB.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_MISC_DEFAULT);
} else if (CodeTemplates.CONSTRUCTORSTUB.equals(name)) {
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE));
} else if (CodeTemplates.NEWTYPE.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CUNIT);
} else if (CodeTemplates.TYPECOMMENT.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS);
} else if (CodeTemplates.METHODCOMMENT.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
} else if (CodeTemplates.OVERRIDECOMMENT.equals(name)) {
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PROTECTED, JavaElementImageDescriptor.OVERRIDES, JavaElementImageProvider.SMALL_SIZE));
} else if (CodeTemplates.CONSTRUCTORCOMMENT.equals(name)) {
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE));
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
*/
public String getText(Object element) {
if (element == COMMENT_NODE || element == CODE_NODE) {
return (String) element;
}
Template template = (Template) element;
String name= template.getName();
if (CodeTemplates.CATCHBLOCK.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.catchblock.label"); //$NON-NLS-1$
} else if (CodeTemplates.METHODSTUB.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.methodstub.label"); //$NON-NLS-1$
} else if (CodeTemplates.CONSTRUCTORSTUB.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.constructorstub.label"); //$NON-NLS-1$
} else if (CodeTemplates.NEWTYPE.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.newtype.label"); //$NON-NLS-1$
} else if (CodeTemplates.TYPECOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.typecomment.label"); //$NON-NLS-1$
} else if (CodeTemplates.METHODCOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.methodcomment.label"); //$NON-NLS-1$
} else if (CodeTemplates.OVERRIDECOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.overridecomment.label"); //$NON-NLS-1$
} else if (CodeTemplates.CONSTRUCTORCOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.constructorcomment.label"); //$NON-NLS-1$
}
return template.getDescription();
}
}
private final static int IDX_EDIT= 0;
private final static int IDX_IMPORT= 2;
private final static int IDX_EXPORT= 3;
private final static int IDX_EXPORTALL= 4;
private final static Object COMMENT_NODE= PreferencesMessages.getString("CodeTemplateBlock.templates.comment.node"); //$NON-NLS-1$
private final static Object CODE_NODE= PreferencesMessages.getString("CodeTemplateBlock.templates.code.node"); //$NON-NLS-1$
private static final String PREF_JAVADOC_STUBS= PreferenceConstants.CODEGEN__JAVADOC_STUBS;
private TreeListDialogField fCodeTemplateTree;
private SelectionButtonDialogField fCreateJavaDocComments;
protected CodeTemplates fTemplates;
private PixelConverter fPixelConverter;
private SourceViewer fPatternViewer;
private Control fSWTWidget;
public CodeTemplateBlock() {
fTemplates= CodeTemplates.getInstance();
CodeTemplateAdapter adapter= new CodeTemplateAdapter(fTemplates);
String[] buttonLabels= new String[] {
/* IDX_EDIT*/ PreferencesMessages.getString("CodeTemplateBlock.templates.edit.button"), //$NON-NLS-1$
/* */ null,
/* IDX_IMPORT */ PreferencesMessages.getString("CodeTemplateBlock.templates.import.button"), //$NON-NLS-1$
/* IDX_EXPORT */ PreferencesMessages.getString("CodeTemplateBlock.templates.export.button"), //$NON-NLS-1$
/* IDX_EXPORTALL */ PreferencesMessages.getString("CodeTemplateBlock.templates.exportall.button") //$NON-NLS-1$
};
fCodeTemplateTree= new TreeListDialogField(adapter, buttonLabels, new CodeTemplateLabelProvider());
fCodeTemplateTree.setDialogFieldListener(adapter);
fCodeTemplateTree.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.templates.label")); //$NON-NLS-1$
fCodeTemplateTree.enableButton(IDX_EXPORT, false);
fCodeTemplateTree.enableButton(IDX_EDIT, false);
fCodeTemplateTree.addElement(COMMENT_NODE);
fCodeTemplateTree.addElement(CODE_NODE);
fCreateJavaDocComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateJavaDocComments.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.createcomment.label")); //$NON-NLS-1$
fCreateJavaDocComments.setSelection(PreferenceConstants.getPreferenceStore().getBoolean(PREF_JAVADOC_STUBS));
fCodeTemplateTree.selectFirstElement();
}
protected Control createContents(Composite parent) {
fPixelConverter= new PixelConverter(parent);
fSWTWidget= parent;
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
//layout.marginHeight= 0;
//layout.marginWidth= 0;
layout.numColumns= 2;
composite.setLayout(layout);
fCreateJavaDocComments.doFillIntoGrid(composite, 2);
fCodeTemplateTree.doFillIntoGrid(composite, 3);
LayoutUtil.setHorizontalSpan(fCodeTemplateTree.getLabelControl(null), 2);
LayoutUtil.setHorizontalGrabbing(fCodeTemplateTree.getTreeControl(null));
fPatternViewer= createViewer(composite, 2);
return composite;
}
private Shell getShell() {
if (fSWTWidget != null) {
return fSWTWidget.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private SourceViewer createViewer(Composite parent, int nColumns) {
Label label= new Label(parent, SWT.NONE);
label.setText(PreferencesMessages.getString("CodeTemplateBlock.preview")); //$NON-NLS-1$
GridData data= new GridData();
data.horizontalSpan= nColumns;
label.setLayoutData(data);
SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
IDocument document= new Document();
IDocumentPartitioner partitioner= tools.createDocumentPartitioner();
document.setDocumentPartitioner(partitioner);
partitioner.connect(document);
viewer.configure(new JavaSourceViewerConfiguration(tools, null));
viewer.setEditable(false);
viewer.setDocument(document);
viewer.getTextWidget().setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
viewer.getTextWidget().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
doKeyInSourcePressed();
}
});
Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
viewer.getTextWidget().setFont(font);
Control control= viewer.getControl();
data= new GridData(GridData.FILL_BOTH);
data.horizontalSpan= nColumns;
data.heightHint= fPixelConverter.convertHeightInCharsToPixels(5);
control.setLayoutData(data);
return viewer;
}
protected Template[] getTemplateOfCategory(boolean isComment) {
ArrayList res= new ArrayList();
Template[] templates= fTemplates.getTemplates();
for (int i= 0; i < templates.length; i++) {
Template curr= templates[i];
if (isComment == curr.getName().endsWith(CodeTemplates.COMMENT_SUFFIX)) {
res.add(curr);
}
}
return (Template[]) res.toArray(new Template[res.size()]);
}
protected static boolean canEdit(List selected) {
return selected.size() == 1 && (selected.get(0) instanceof Template);
}
protected void updateSourceViewerInput(List selection) {
if (fPatternViewer == null || fPatternViewer.getTextWidget().isDisposed()) {
return;
}
if (selection.size() == 1 && selection.get(0) instanceof Template) {
Template template= (Template) selection.get(0);
fPatternViewer.getDocument().set(template.getPattern());
} else {
fPatternViewer.getDocument().set(""); //$NON-NLS-1$
}
}
protected void doKeyInSourcePressed() {
List selected= fCodeTemplateTree.getSelectedElements();
if (canEdit(selected)) {
doButtonPressed(IDX_EDIT, selected);
}
}
protected void doButtonPressed(int buttonIndex, List selected) {
if (buttonIndex == IDX_EDIT) {
edit((Template) selected.get(0));
} else if (buttonIndex == IDX_EXPORT) {
export(selected);
} else if (buttonIndex == IDX_EXPORTALL) {
exportAll();
} else {
import_();
}
}
private void edit(Template template) {
Template newTemplate= new Template(template);
EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true, false, new String[0]);
if (dialog.open() == EditTemplateDialog.OK) {
// changed
template.setDescription(newTemplate.getDescription());
template.setPattern(newTemplate.getPattern());
fCodeTemplateTree.refresh(template);
fCodeTemplateTree.selectElements(new StructuredSelection(template));
}
}
private void import_() {
FileDialog dialog= new FileDialog(getShell());
dialog.setText(PreferencesMessages.getString("CodeTemplateBlock.import.title")); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {PreferencesMessages.getString("CodeTemplateBlock.import.extension")}); //$NON-NLS-1$
String path= dialog.open();
if (path != null) {
try {
fTemplates.addFromFile(new File(path), false);
} catch (CoreException e) {
openReadErrorDialog(e);
}
fCodeTemplateTree.refresh();
}
}
private void exportAll() {
export(fTemplates);
}
private void export(List selected) {
TemplateSet templateSet= new TemplateSet(fTemplates.getTemplateTag());
for (int i= 0; i < selected.size(); i++) {
Object curr= selected.get(i);
if (curr instanceof Template) {
addToTemplateSet(templateSet, (Template) curr);
} else {
Template[] templates= getTemplateOfCategory(curr == COMMENT_NODE);
for (int k= 0; k < templates.length; k++) {
addToTemplateSet(templateSet, templates[k]);
}
}
}
export(templateSet);
}
private void addToTemplateSet(TemplateSet set, Template template) {
if (set.getFirstTemplate(template.getName()) == null) {
set.add(template);
}
}
private void export(TemplateSet templateSet) {
FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
dialog.setText(PreferencesMessages.getFormattedString("CodeTemplateBlock.export.title", String.valueOf(templateSet.getTemplates().length))); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {PreferencesMessages.getString("CodeTemplateBlock.export.extension")}); //$NON-NLS-1$
dialog.setFileName(PreferencesMessages.getString("CodeTemplateBlock.export.filename")); //$NON-NLS-1$
String path= dialog.open();
if (path == null)
return;
File file= new File(path);
if (!file.exists() || confirmOverwrite(file)) {
try {
templateSet.saveToFile(file);
} catch (CoreException e) {
JavaPlugin.log(e);
openWriteErrorDialog(e);
}
}
}
private boolean confirmOverwrite(File file) {
return MessageDialog.openQuestion(getShell(),
PreferencesMessages.getString("CodeTemplateBlock.export.exists.title"), //$NON-NLS-1$
PreferencesMessages.getFormattedString("CodeTemplateBlock.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$
}
public void performDefaults() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fCreateJavaDocComments.setSelection(prefs.getDefaultBoolean(PREF_JAVADOC_STUBS));
try {
fTemplates.restoreDefaults();
} catch (CoreException e) {
JavaPlugin.log(e);
openReadErrorDialog(e);
}
// refresh
fCodeTemplateTree.refresh();
}
public boolean performOk(boolean enabled) {
IPreferenceStore prefs= PreferenceConstants.getPreferenceStore();
prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected());
JavaPlugin.getDefault().savePluginPreferences();
return true;
}
public void performCancel() {
try {
fTemplates.reset();
} catch (CoreException e) {
openReadErrorDialog(e);
}
}
private void openReadErrorDialog(CoreException e) {
String title= PreferencesMessages.getString("CodeTemplateBlock.error.read.title"); //$NON-NLS-1$
String message= PreferencesMessages.getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
private void openWriteErrorDialog(CoreException e) {
String title= PreferencesMessages.getString("CodeTemplateBlock.error.write.title"); //$NON-NLS-1$
String message= PreferencesMessages.getString("CodeTemplateBlock.error.write.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
}
|
31,078 |
Bug 31078 Context menu for types includes Add Bookmark
|
1) select a class in the outline or package explorer -> Add Bookmark appears in the context menu We should remove this action
|
resolved fixed
|
702a584
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T15:26:43Z | 2003-02-06T11:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/GenerateActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.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.util.Assert;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.texteditor.ConvertLineDelimitersAction;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.AddBookmarkAction;
import org.eclipse.jdt.internal.ui.javaeditor.AddImportOnSelectionAction;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.AddTaskAction;
import org.eclipse.jdt.ui.IContextMenuConstants;
/**
* Action group that adds the source and generate actions to a part's context
* menu and installs handlers for the corresponding global menu actions.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class GenerateActionGroup extends ActionGroup {
private CompilationUnitEditor fEditor;
private IWorkbenchSite fSite;
private String fGroupName= IContextMenuConstants.GROUP_SOURCE;
private List fRegisteredSelectionListeners;
private AddImportOnSelectionAction fAddImport;
private OverrideMethodsAction fOverrideMethods;
private AddGetterSetterAction fAddGetterSetter;
private AddDelegateMethodsAction fAddDelegateMethods;
private AddUnimplementedConstructorsAction fAddUnimplementedConstructors;
private AddJavaDocStubAction fAddJavaDocStub;
private AddBookmarkAction fAddBookmark;
private AddTaskAction fAddTaskAction;
private ExternalizeStringsAction fExternalizeStrings;
private FindStringsToExternalizeAction fFindStringsToExternalize;
private SurroundWithTryCatchAction fSurroundWithTryCatch;
private AddToClasspathAction fAddToClasspathAction;
private RemoveFromClasspathAction fRemoveFromClasspathAction;
private OrganizeImportsAction fOrganizeImports;
private SortMembersAction fSortMembers;
private ConvertLineDelimitersAction fConvertToWindows;
private ConvertLineDelimitersAction fConvertToUNIX;
private ConvertLineDelimitersAction fConvertToMac;
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public GenerateActionGroup(CompilationUnitEditor editor, String groupName) {
fSite= editor.getSite();
fEditor= editor;
fGroupName= groupName;
ISelectionProvider provider= fSite.getSelectionProvider();
ISelection selection= provider.getSelection();
fAddImport= new AddImportOnSelectionAction(editor);
fAddImport.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_IMPORT);
fAddImport.update();
editor.setAction("AddImport", fAddImport); //$NON-NLS-1$
fOrganizeImports= new OrganizeImportsAction(editor);
fOrganizeImports.setActionDefinitionId(IJavaEditorActionDefinitionIds.ORGANIZE_IMPORTS);
editor.setAction("OrganizeImports", fOrganizeImports); //$NON-NLS-1$
fSortMembers= new SortMembersAction(editor);
fSortMembers.setActionDefinitionId(IJavaEditorActionDefinitionIds.SORT_MEMBERS);
editor.setAction("SortMembers", fSortMembers); //$NON-NLS-1$
fOverrideMethods= new OverrideMethodsAction(editor);
fOverrideMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.OVERRIDE_METHODS);
editor.setAction("OverrideMethods", fOverrideMethods); //$NON-NLS-1$
fAddGetterSetter= new AddGetterSetterAction(editor);
fAddGetterSetter.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_GETTER_SETTER);
editor.setAction("AddGetterSetter", fAddGetterSetter); //$NON-NLS-1$
fAddDelegateMethods= new AddDelegateMethodsAction(editor);
fAddDelegateMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_DELEGATE_METHODS);
editor.setAction("AddDelegateMethods", fAddDelegateMethods); //$NON-NLS-1$
fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(editor);
fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS);
editor.setAction("AddUnimplementedConstructors", fAddUnimplementedConstructors); //$NON-NLS-1$
fAddJavaDocStub= new AddJavaDocStubAction(editor);
fSurroundWithTryCatch= new SurroundWithTryCatchAction(editor);
fSurroundWithTryCatch.setActionDefinitionId(IJavaEditorActionDefinitionIds.SURROUND_WITH_TRY_CATCH);
fSurroundWithTryCatch.update(selection);
provider.addSelectionChangedListener(fSurroundWithTryCatch);
editor.setAction("SurroundWithTryCatch", fSurroundWithTryCatch); //$NON-NLS-1$
fExternalizeStrings= new ExternalizeStringsAction(editor);
fExternalizeStrings.setActionDefinitionId(IJavaEditorActionDefinitionIds.EXTERNALIZE_STRINGS);
editor.setAction("ExternalizeStrings", fExternalizeStrings); //$NON-NLS-1$
fConvertToWindows= new ConvertLineDelimitersAction(editor, "\r\n"); //$NON-NLS-1$
fConvertToWindows.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_WINDOWS);
editor.setAction("ConvertLineDelimitersToWindows", fConvertToWindows); //$NON-NLS-1$
fConvertToUNIX= new ConvertLineDelimitersAction(editor, "\n"); //$NON-NLS-1$
fConvertToUNIX.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_UNIX);
editor.setAction("ConvertLineDelimitersToUNIX", fConvertToUNIX); //$NON-NLS-1$
fConvertToMac= new ConvertLineDelimitersAction(editor, "\r"); //$NON-NLS-1$
fConvertToMac.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONVERT_LINE_DELIMITERS_TO_MAC);
editor.setAction("ConvertLineDelimitersToMac", fConvertToMac); //$NON-NLS-1$
}
/**
* Creates a new <code>GenerateActionGroup</code>. The group
* requires that the selection provided by the page's selection provider
* is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param page the page that owns this action group
*/
public GenerateActionGroup(Page page) {
this(page.getSite());
}
/**
* Creates a new <code>GenerateActionGroup</code>. The group
* requires that the selection provided by the part's selection provider
* is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param part the view part that owns this action group
*/
public GenerateActionGroup(IViewPart part) {
this(part.getSite());
}
private GenerateActionGroup(IWorkbenchSite site) {
fSite= site;
ISelectionProvider provider= fSite.getSelectionProvider();
ISelection selection= provider.getSelection();
fOverrideMethods= new OverrideMethodsAction(site);
fAddGetterSetter= new AddGetterSetterAction(site);
fAddDelegateMethods= new AddDelegateMethodsAction(site);
fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(site);
fAddJavaDocStub= new AddJavaDocStubAction(site);
fAddBookmark= new AddBookmarkAction(site.getShell());
fAddToClasspathAction= new AddToClasspathAction(site);
fRemoveFromClasspathAction= new RemoveFromClasspathAction(site);
fAddTaskAction= new AddTaskAction(site);
fExternalizeStrings= new ExternalizeStringsAction(site);
fFindStringsToExternalize= new FindStringsToExternalizeAction(site);
fOrganizeImports= new OrganizeImportsAction(site);
fSortMembers= new SortMembersAction(site);
fOverrideMethods.update(selection);
fAddGetterSetter.update(selection);
fAddDelegateMethods.update(selection);
fAddUnimplementedConstructors.update(selection);
fAddJavaDocStub.update(selection);
fExternalizeStrings.update(selection);
fFindStringsToExternalize.update(selection);
fAddTaskAction.update(selection);
fOrganizeImports.update(selection);
fSortMembers.update(selection);
if (selection instanceof IStructuredSelection) {
IStructuredSelection ss= (IStructuredSelection)selection;
fAddBookmark.selectionChanged(ss);
} else {
fAddBookmark.setEnabled(false);
}
registerSelectionListener(provider, fOverrideMethods);
registerSelectionListener(provider, fAddGetterSetter);
registerSelectionListener(provider, fAddDelegateMethods);
registerSelectionListener(provider, fAddUnimplementedConstructors);
registerSelectionListener(provider, fAddJavaDocStub);
registerSelectionListener(provider, fAddBookmark);
registerSelectionListener(provider, fAddToClasspathAction);
registerSelectionListener(provider, fRemoveFromClasspathAction);
registerSelectionListener(provider, fExternalizeStrings);
registerSelectionListener(provider, fFindStringsToExternalize);
registerSelectionListener(provider, fOrganizeImports);
registerSelectionListener(provider, fSortMembers);
registerSelectionListener(provider, fAddTaskAction);
}
private void registerSelectionListener(ISelectionProvider provider, ISelectionChangedListener listener) {
if (fRegisteredSelectionListeners == null)
fRegisteredSelectionListeners= new ArrayList(20);
provider.addSelectionChangedListener(listener);
fRegisteredSelectionListeners.add(listener);
}
/*
* The state of the editor owning this action group has changed.
* This method does nothing if the group's owner isn't an
* editor.
*/
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
public void editorStateChanged() {
Assert.isTrue(isEditorOwner());
// http://dev.eclipse.org/bugs/show_bug.cgi?id=17709
fConvertToMac.update();
fConvertToUNIX.update();
fConvertToWindows.update();
}
/* (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);
if (isEditorOwner()) {
IMenuManager subMenu= createEditorSubMenu(menu);
if (subMenu != null)
menu.appendToGroup(fGroupName, subMenu);
} else {
appendToGroup(menu, fOrganizeImports);
appendToGroup(menu, fOverrideMethods);
appendToGroup(menu, fAddGetterSetter);
appendToGroup(menu, fAddDelegateMethods);
appendToGroup(menu, fAddUnimplementedConstructors);
appendToGroup(menu, fAddJavaDocStub);
appendToGroup(menu, fSortMembers);
appendToGroup(menu, fAddBookmark);
appendToGroup(menu, fAddToClasspathAction);
appendToGroup(menu, fRemoveFromClasspathAction);
}
}
private IMenuManager createEditorSubMenu(IMenuManager mainMenu) {
IMenuManager result= new MenuManager(ActionMessages.getString("SourceMenu.label")); //$NON-NLS-1$
int added= 0;
added+= addEditorAction(result, "Comment"); //$NON-NLS-1$
added+= addEditorAction(result, "Uncomment"); //$NON-NLS-1$
result.add(new Separator());
added+= addAction(result, fOrganizeImports);
added+= addAction(result, fAddImport);
result.add(new Separator());
added+= addAction(result, fOverrideMethods);
added+= addAction(result, fAddGetterSetter);
added+= addAction(result, fAddDelegateMethods);
added+= addAction(result, fAddUnimplementedConstructors);
added+= addAction(result, fAddJavaDocStub);
added+= addAction(result, fSortMembers);
added+= addAction(result, fAddBookmark);
result.add(new Separator());
added+= addAction(result, fSurroundWithTryCatch);
added+= addAction(result, fExternalizeStrings);
if (added == 0)
result= null;
return result;
}
/* (non-Javadoc)
* Method declared in ActionGroup
*/
public void dispose() {
if (fRegisteredSelectionListeners != null) {
ISelectionProvider provider= fSite.getSelectionProvider();
for (Iterator iter= fRegisteredSelectionListeners.iterator(); iter.hasNext();) {
ISelectionChangedListener listener= (ISelectionChangedListener) iter.next();
provider.removeSelectionChangedListener(listener);
}
}
fEditor= null;
super.dispose();
}
private void setGlobalActionHandlers(IActionBars actionBar) {
actionBar.setGlobalActionHandler(JdtActionConstants.ADD_IMPORT, fAddImport);
actionBar.setGlobalActionHandler(JdtActionConstants.SURROUND_WITH_TRY_CATCH, fSurroundWithTryCatch);
actionBar.setGlobalActionHandler(JdtActionConstants.OVERRIDE_METHODS, fOverrideMethods);
actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_GETTER_SETTER, fAddGetterSetter);
actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_DELEGATE_METHODS, fAddDelegateMethods);
actionBar.setGlobalActionHandler(JdtActionConstants.ADD_CONSTRUCTOR_FROM_SUPERCLASS, fAddUnimplementedConstructors);
actionBar.setGlobalActionHandler(JdtActionConstants.ADD_JAVA_DOC_COMMENT, fAddJavaDocStub);
actionBar.setGlobalActionHandler(JdtActionConstants.EXTERNALIZE_STRINGS, fExternalizeStrings);
actionBar.setGlobalActionHandler(JdtActionConstants.FIND_STRINGS_TO_EXTERNALIZE, fFindStringsToExternalize);
actionBar.setGlobalActionHandler(JdtActionConstants.ORGANIZE_IMPORTS, fOrganizeImports);
actionBar.setGlobalActionHandler(JdtActionConstants.SORT_MEMBERS, fSortMembers);
actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_WINDOWS, fConvertToWindows);
actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_UNIX, fConvertToUNIX);
actionBar.setGlobalActionHandler(JdtActionConstants.CONVERT_LINE_DELIMITERS_TO_MAC, fConvertToMac);
if (!isEditorOwner()) {
// editor provides its own implementation of these actions.
actionBar.setGlobalActionHandler(IWorkbenchActionConstants.BOOKMARK, fAddBookmark);
actionBar.setGlobalActionHandler(IWorkbenchActionConstants.ADD_TASK, fAddTaskAction);
}
}
private int appendToGroup(IMenuManager menu, IAction action) {
if (action != null && action.isEnabled()) {
menu.appendToGroup(fGroupName, action);
return 1;
}
return 0;
}
private int addAction(IMenuManager menu, IAction action) {
if (action != null && action.isEnabled()) {
menu.add(action);
return 1;
}
return 0;
}
private int addEditorAction(IMenuManager menu, String actionID) {
if (fEditor == null)
return 0;
IAction action= fEditor.getAction(actionID);
if (action == null)
return 0;
if (action instanceof IUpdate)
((IUpdate)action).update();
if (action.isEnabled()) {
menu.add(action);
return 1;
}
return 0;
}
private boolean isEditorOwner() {
return fEditor != null;
}
}
|
31,091 |
Bug 31091 14 times - Unneccessary error dialog from Outline View
|
I20030205 1) Open a java file that is not on the classpath (in SWT we have many of these because the code for other platforms is not included in the current classpath). For example, get org.eclipse.swt from CVS and copy .classpath_carbon to .classpath. Now open org.eclipse.swt/Eclipse SWT/gtk/org/eclipse/swt/widgets/Display.java. 2) Click on a method in the Outline view. 14 times a dialog pops up with title "Operation can not be performed" and message "The resource is not on the build path of a project.". After the last dialog is closed, the Java editor scrolls to the requested method.
|
resolved fixed
|
452db81
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T15:52:36Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/FindAction.java
| |
31,096 |
Bug 31096 NPE creating Packages wizard
|
20030206 I just got an NPE creating a new package wizard. It has to be the first thing you do in an empty workspace for it to happen - if you have loaded anything into your workbench or opened another wizard I can't replicate it. STEPS 1) Select New -Other 2) Select Java-> package. 3) Try it again - no problem. !SESSION Feb 06, 2003 11:00:22.296 -------------------------------------------- - java.version=1.4.1-rc java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US Command-line arguments: -dev bin -feature org.eclipse.platform -data D:\R21 \0206\eclipse\runtime-workspace -os win32 -ws win32 -arch x86 -nl en_US - configuration file:D:/R21/0206/eclipse/workspace/.metadata/.plugins/org.eclipse.pde.core/D__R 21_0206_eclipse_runtime-workspace/platform.cfg -install file:D:/R21/0206/eclipse/ !ENTRY org.eclipse.jface 4 2 Feb 06, 2003 11:00:22.312 !MESSAGE Problems occurred when invoking code from plug- in: "org.eclipse.jface". !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.ui.wizards.NewPackageWizardPage.init (NewPackageWizardPage.java:106) at org.eclipse.jdt.internal.ui.wizards.NewPackageCreationWizard.addPages (NewPackageCreationWizard.java:33) at org.eclipse.jface.wizard.WizardSelectionPage.getNextPage (WizardSelectionPage.java:99) at org.eclipse.ui.internal.dialogs.NewWizardSelectionPage.advanceToNextPage (NewWizardSelectionPage.java:39) at org.eclipse.ui.internal.dialogs.NewWizardNewPage.doubleClick (NewWizardNewPage.java:145) at org.eclipse.jface.viewers.StructuredViewer$1.run (StructuredViewer.java:372) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:867) at org.eclipse.core.runtime.Platform.run(Platform.java:413) at org.eclipse.jface.viewers.StructuredViewer.fireDoubleClick (StructuredViewer.java:370) at org.eclipse.jface.viewers.StructuredViewer.handleDoubleSelect (StructuredViewer.java:586) at org.eclipse.jface.viewers.StructuredViewer$4.widgetDefaultSelected (StructuredViewer.java:679) at org.eclipse.jface.util.OpenStrategy.fireDefaultSelectionEvent (OpenStrategy.java:181) at org.eclipse.jface.util.OpenStrategy.access$0(OpenStrategy.java:178) at org.eclipse.jface.util.OpenStrategy$1.handleEvent (OpenStrategy.java:225) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.ui.actions.NewWizardAction.run(NewWizardAction.java:122) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:398) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:392) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
f1d1000
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T16:26:56Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewPackageWizardPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
/**
* Wizard page to create a new package.
*
* <p>
* Note: This class is not intended to be subclassed. To implement a different kind of
* a new package wizard page, extend <code>NewContainerWizardPage</code>.
* </p>
*
* @since 2.0
*/
public class NewPackageWizardPage extends NewContainerWizardPage {
private static final String PAGE_NAME= "NewPackageWizardPage"; //$NON-NLS-1$
private static final String PACKAGE= "NewPackageWizardPage.package"; //$NON-NLS-1$
private StringDialogField fPackageDialogField;
/*
* Status of last validation of the package field
*/
private IStatus fPackageStatus;
private IPackageFragment fCreatedPackageFragment;
/**
* Creates a new <code>NewPackageWizardPage</code>
*/
public NewPackageWizardPage() {
super(PAGE_NAME);
setTitle(NewWizardMessages.getString("NewPackageWizardPage.title")); //$NON-NLS-1$
setDescription(NewWizardMessages.getString("NewPackageWizardPage.description")); //$NON-NLS-1$
fCreatedPackageFragment= null;
PackageFieldAdapter adapter= new PackageFieldAdapter();
fPackageDialogField= new StringDialogField();
fPackageDialogField.setDialogFieldListener(adapter);
fPackageDialogField.setLabelText(NewWizardMessages.getString("NewPackageWizardPage.package.label")); //$NON-NLS-1$
fPackageStatus= new StatusInfo();
}
// -------- Initialization ---------
/**
* The wizard owning this page is responsible for calling this method with the
* current selection. The selection is used to initialize the fields of the wizard
* page.
*
* @param selection used to initialize the fields
*/
public void init(IStructuredSelection selection) {
IJavaElement jelem= getInitialJavaElement(selection);
initContainerPage(jelem);
String pName= ""; //$NON-NLS-1$
if (jelem.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
IPackageFragment pf= (IPackageFragment)jelem;
if (!pf.isDefaultPackage())
pName= jelem.getElementName();
}
setPackageText(pName, true); //$NON-NLS-1$
updateStatus(new IStatus[] { fContainerStatus, fPackageStatus });
}
// -------- UI Creation ---------
/*
* @see WizardPage#createControl
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NONE);
int nColumns= 3;
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
layout.numColumns= 3;
composite.setLayout(layout);
Label label= new Label(composite, SWT.WRAP);
label.setText(NewWizardMessages.getString("NewPackageWizardPage.info")); //$NON-NLS-1$
GridData gd= new GridData();
gd.widthHint= convertWidthInCharsToPixels(80);
gd.horizontalSpan= 3;
label.setLayoutData(gd);
createContainerControls(composite, nColumns);
createPackageControls(composite, nColumns);
setControl(composite);
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.NEW_PACKAGE_WIZARD_PAGE);
}
/**
* @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
*/
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
setFocus();
}
}
/**
* Sets the focus to the package name input field.
*/
protected void setFocus() {
fPackageDialogField.setFocus();
}
private void createPackageControls(Composite composite, int nColumns) {
fPackageDialogField.doFillIntoGrid(composite, nColumns - 1);
LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth());
LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null));
DialogField.createEmptySpace(composite);
}
// -------- PackageFieldAdapter --------
private class PackageFieldAdapter implements IDialogFieldListener {
// --------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
fPackageStatus= packageChanged();
// tell all others
handleFieldChanged(PACKAGE);
}
}
// -------- update message ----------------
/*
* @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName == CONTAINER) {
fPackageStatus= packageChanged();
}
// do status line update
updateStatus(new IStatus[] { fContainerStatus, fPackageStatus });
}
// ----------- validation ----------
/**
* Verifies the input for the package field.
*/
private IStatus packageChanged() {
StatusInfo status= new StatusInfo();
String packName= getPackageText();
if (packName.length() > 0) {
IStatus val= JavaConventions.validatePackageName(packName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewPackageWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewPackageWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$
}
} else {
status.setError(NewWizardMessages.getString("NewPackageWizardPage.error.EnterName")); //$NON-NLS-1$
return status;
}
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root != null) {
IPackageFragment pack= root.getPackageFragment(packName);
try {
IPath rootPath= root.getPath();
IPath outputPath= root.getJavaProject().getOutputLocation();
if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
// if the bin folder is inside of our root, dont allow to name a package
// like the bin folder
IPath packagePath= pack.getPath();
if (outputPath.isPrefixOf(packagePath)) {
status.setError(NewWizardMessages.getString("NewPackageWizardPage.error.IsOutputFolder")); //$NON-NLS-1$
return status;
}
}
if (pack.exists()) {
if (pack.containsJavaResources() || !pack.hasSubpackages()) {
status.setError(NewWizardMessages.getString("NewPackageWizardPage.error.PackageExists")); //$NON-NLS-1$
} else {
status.setWarning(NewWizardMessages.getString("NewPackageWizardPage.warning.PackageNotShown")); //$NON-NLS-1$
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return status;
}
/**
* Returns the content of the package input field.
*
* @return the content of the package input field
*/
public String getPackageText() {
return fPackageDialogField.getText();
}
/**
* Sets the content of the package input field to the given value.
*
* @param str the new package input field text
* @param canBeModified if <code>true</code> the package input
* field can be modified; otherwise it is read-only.
*/
public void setPackageText(String str, boolean canBeModified) {
fPackageDialogField.setText(str);
fPackageDialogField.setEnabled(canBeModified);
}
// ---- creation ----------------
/**
* Returns a runnable that creates a package using the current settings.
*
* @return the runnable that creates the new package
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
createPackage(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
/**
* Returns the created package fragment. This method only returns a valid value
* after <code>getRunnable</code> or <code>createPackage</code> have been
* executed.
*
* @return the created package fragment
*/
public IPackageFragment getNewPackageFragment() {
return fCreatedPackageFragment;
}
/**
* Creates the new package using the entered field values.
*
* @param monitor a progress monitor to report progress. The progress
* monitor must not be <code>null</code>
* @since 2.1
*/
public void createPackage(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
IPackageFragmentRoot root= getPackageFragmentRoot();
String packName= getPackageText();
fCreatedPackageFragment= root.createPackageFragment(packName, true, monitor);
}
}
|
31,001 |
Bug 31001 Filterdialog shows clipped items
|
1) In the package explorer drop down the view menu 2) select filters 3) the filter dialog shows up Notice that the initial size of the table clips the last entry and this looks ugly. The initial size of the table should be a multiple of the item height. There is support to do this.
|
resolved fixed
|
6450262
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-06T16:29:44Z | 2003-02-05T18:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/CustomFiltersDialog.java
| |
30,143 |
Bug 30143 [performance] leverage IResourceProxyVisitor
|
The new IResourceProxyVisitor results in signficant speed-ups when processing the resource trees as long as you do not need the full path of the resource. The AmountOfWorkCalculator is a candidate for leveraging the new IResourceProxyVisitor. Please investigate.
|
resolved fixed
|
dc57223
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-07T16:01:21Z | 2003-01-24T09:20:00Z |
org.eclipse.jdt.ui/core
| |
30,143 |
Bug 30143 [performance] leverage IResourceProxyVisitor
|
The new IResourceProxyVisitor results in signficant speed-ups when processing the resource trees as long as you do not need the full path of the resource. The AmountOfWorkCalculator is a candidate for leveraging the new IResourceProxyVisitor. Please investigate.
|
resolved fixed
|
dc57223
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-07T16:01:21Z | 2003-01-24T09:20:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/util/QualifiedNameFinder.java
| |
28,277 |
Bug 28277 Double-clicking in the Types view refreshes decorators
|
In build I20021210, with CVS decorators turned on, in the Java browing perspective, if I double click on a class in the Types view, the decorators in the view undergo a visible refresh (i.e. they go away and then reappear).
|
resolved fixed
|
2d92fbe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-07T17:32:59Z | 2002-12-13T17:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingContentProvider.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
class JavaBrowsingContentProvider extends StandardJavaElementContentProvider implements IElementChangedListener {
private StructuredViewer fViewer;
private Object fInput;
private JavaBrowsingPart fBrowsingPart;
public JavaBrowsingContentProvider(boolean provideMembers, JavaBrowsingPart browsingPart) {
super(provideMembers, reconcileJavaViews());
fBrowsingPart= browsingPart;
fViewer= fBrowsingPart.getViewer();
JavaCore.addElementChangedListener(this);
}
private static boolean reconcileJavaViews() {
return PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
}
public Object[] getChildren(Object element) {
if (!exists(element))
return NO_CHILDREN;
try {
if (element instanceof Collection) {
Collection elements= (Collection)element;
if (elements.isEmpty())
return NO_CHILDREN;
Object[] result= new Object[0];
Iterator iter= ((Collection)element).iterator();
while (iter.hasNext()) {
Object[] children= getChildren(iter.next());
if (children != NO_CHILDREN)
result= concatenate(result, children);
}
return result;
}
if (element instanceof IPackageFragment)
return getPackageContents((IPackageFragment)element);
if (fProvideMembers && element instanceof IType)
return getChildren((IType)element);
if (fProvideMembers && element instanceof ISourceReference && element instanceof IParent)
return removeImportAndPackageDeclarations(super.getChildren(element));
if (element instanceof IJavaProject)
return getPackageFragmentRoots((IJavaProject)element);
return super.getChildren(element);
} catch (JavaModelException e) {
return NO_CHILDREN;
}
}
private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException {
ISourceReference[] sourceRefs;
if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
sourceRefs= fragment.getCompilationUnits();
if (getProvideWorkingCopy()) {
for (int i= 0; i < sourceRefs.length; i++) {
IWorkingCopy wc= EditorUtility.getWorkingCopy((ICompilationUnit)sourceRefs[i]);
if (wc != null)
sourceRefs[i]= (ICompilationUnit)wc;
}
}
}
else {
IClassFile[] classFiles= fragment.getClassFiles();
List topLevelClassFile= new ArrayList();
for (int i= 0; i < classFiles.length; i++) {
IType type= classFiles[i].getType();
if (type != null && type.getDeclaringType() == null && !type.isAnonymous() && !type.isLocal())
topLevelClassFile.add(classFiles[i]);
}
sourceRefs= (ISourceReference[])topLevelClassFile.toArray(new ISourceReference[topLevelClassFile.size()]);
}
Object[] result= new Object[0];
for (int i= 0; i < sourceRefs.length; i++)
result= concatenate(result, removeImportAndPackageDeclarations(getChildren(sourceRefs[i])));
return concatenate(result, fragment.getNonJavaResources());
}
private Object[] removeImportAndPackageDeclarations(Object[] members) {
ArrayList tempResult= new ArrayList(members.length);
for (int i= 0; i < members.length; i++)
if (!(members[i] instanceof IImportContainer) && !(members[i] instanceof IPackageDeclaration))
tempResult.add(members[i]);
return tempResult.toArray();
}
private Object[] getChildren(IType type) throws JavaModelException{
IParent parent;
if (type.isBinary())
parent= type.getClassFile();
else {
parent= type.getCompilationUnit();
if (getProvideWorkingCopy()) {
IWorkingCopy wc= EditorUtility.getWorkingCopy((ICompilationUnit)parent);
if (wc != null) {
parent= (IParent)wc;
IMember wcType= EditorUtility.getWorkingCopy(type);
if (wcType != null)
type= (IType)wcType;
}
}
}
if (type.getDeclaringType() != null)
return type.getChildren();
// Add import declarations
IJavaElement[] members= parent.getChildren();
ArrayList tempResult= new ArrayList(members.length);
for (int i= 0; i < members.length; i++)
if ((members[i] instanceof IImportContainer))
tempResult.add(members[i]);
tempResult.addAll(Arrays.asList(type.getChildren()));
return tempResult.toArray();
}
protected Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException {
if (!project.getProject().isOpen())
return NO_CHILDREN;
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
List list= new ArrayList(roots.length);
// filter out package fragments that correspond to projects and
// replace them with the package fragments directly
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= (IPackageFragmentRoot)roots[i];
if (!root.isExternal()) {
Object[] children= root.getChildren();
for (int k= 0; k < children.length; k++)
list.add(children[k]);
}
else if (hasChildren(root)) {
list.add(root);
}
}
return concatenate(list.toArray(), project.getNonJavaResources());
}
// ---------------- Element change handling
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
super.inputChanged(viewer, oldInput, newInput);
if (newInput instanceof Collection) {
// Get a template object from the collection
Collection col= (Collection)newInput;
if (!col.isEmpty())
newInput= col.iterator().next();
else
newInput= null;
}
fInput= newInput;
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void dispose() {
super.dispose();
JavaCore.removeElementChangedListener(this);
}
/* (non-Javadoc)
* Method declared on IElementChangedListener.
*/
public void elementChanged(final ElementChangedEvent event) {
try {
processDelta(event.getDelta());
} catch(JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
/**
* Processes a delta recursively. When more than two children are affected the
* tree is fully refreshed starting at this node. The delta is processed in the
* current thread but the viewer updates are posted to the UI thread.
*/
protected void processDelta(IJavaElementDelta delta) throws JavaModelException {
int kind= delta.getKind();
int flags= delta.getFlags();
IJavaElement element= delta.getElement();
if (!getProvideWorkingCopy() && element instanceof IWorkingCopy && ((IWorkingCopy)element).isWorkingCopy())
return;
if (element != null && element.getElementType() == IJavaElement.COMPILATION_UNIT && !isOnClassPath((ICompilationUnit)element))
return;
// handle open and closing of a solution or project
if (((flags & IJavaElementDelta.F_CLOSED) != 0) || ((flags & IJavaElementDelta.F_OPENED) != 0)) {
postRefresh(element);
return;
}
if (kind == IJavaElementDelta.REMOVED) {
Object parent= internalGetParent(element);
if (fBrowsingPart.isValidElement(element)) {
if (element instanceof IClassFile) {
postRemove(((IClassFile)element).getType());
} else if (element instanceof ICompilationUnit && !((ICompilationUnit)element).isWorkingCopy()) {
postRefresh(null);
} else if (element instanceof ICompilationUnit && ((ICompilationUnit)element).isWorkingCopy()) {
if (getProvideWorkingCopy())
postRefresh(null);
} else if (parent instanceof ICompilationUnit && getProvideWorkingCopy() && !((ICompilationUnit)parent).isWorkingCopy()) {
if (element instanceof IWorkingCopy && ((IWorkingCopy)element).isWorkingCopy()) {
// working copy removed from system - refresh
postRefresh(null);
}
} else if (element instanceof IWorkingCopy && ((IWorkingCopy)element).isWorkingCopy() && parent != null && parent.equals(fInput))
// closed editor - removing working copy
postRefresh(null);
else
postRemove(element);
}
if (fBrowsingPart.isAncestorOf(element, fInput)) {
if (element instanceof IWorkingCopy && ((IWorkingCopy)element).isWorkingCopy()) {
postAdjustInputAndSetSelection(((IWorkingCopy)element).getOriginal((IJavaElement)fInput));
} else
postAdjustInputAndSetSelection(null);
}
if (fInput != null && fInput.equals(element))
postRefresh(null);
if (parent instanceof IPackageFragment && fBrowsingPart.isValidElement(parent)) {
// refresh if package gets empty (might be filtered)
if (isPackageFragmentEmpty((IPackageFragment)parent) && fViewer.testFindItem(parent) != null)
postRefresh(null);
}
return;
}
if (kind == IJavaElementDelta.ADDED && delta.getMovedFromElement() != null && element instanceof ICompilationUnit)
return;
if (kind == IJavaElementDelta.ADDED) {
if (fBrowsingPart.isValidElement(element)) {
Object parent= internalGetParent(element);
if (element instanceof IClassFile) {
postAdd(parent, ((IClassFile)element).getType());
} else if (element instanceof ICompilationUnit && !((ICompilationUnit)element).isWorkingCopy()) {
postAdd(parent, ((ICompilationUnit)element).getTypes());
} else if (parent instanceof ICompilationUnit && getProvideWorkingCopy() && !((ICompilationUnit)parent).isWorkingCopy()) {
// do nothing
} else if (element instanceof IWorkingCopy && ((IWorkingCopy)element).isWorkingCopy()) {
// new working copy comes to live
postRefresh(null);
} else
postAdd(parent, element);
} else if (fInput == null) {
IJavaElement newInput= fBrowsingPart.findInputForJavaElement(element);
if (newInput != null)
postAdjustInputAndSetSelection(element);
} else if (element instanceof IType && fBrowsingPart.isValidInput(element)) {
IJavaElement cu1= element.getAncestor(IJavaElement.COMPILATION_UNIT);
IJavaElement cu2= ((IJavaElement)fInput).getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu1 != null && cu2 != null && cu1.equals(cu2))
postAdjustInputAndSetSelection(element);
}
return;
}
if (kind == IJavaElementDelta.CHANGED) {
if (fBrowsingPart.isValidElement(element)) {
postRefresh(element);
}
}
if (isClassPathChange(delta))
// throw the towel and do a full refresh
postRefresh(null);
if ((flags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0 && fInput instanceof IJavaElement) {
IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)element;
IJavaElement inputsParent= ((IJavaElement)fInput).getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
if (pkgRoot.equals(inputsParent))
postRefresh(null);
}
// the source attachment of a JAR has changed
if (element instanceof IPackageFragmentRoot && (((flags & IJavaElementDelta.F_SOURCEATTACHED) != 0 || ((flags & IJavaElementDelta.F_SOURCEDETACHED)) != 0)))
postUpdateIcon(element);
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren.length > 1) {
// a package fragment might become non empty refresh from the parent
if (element instanceof IPackageFragment) {
IJavaElement parent= (IJavaElement)internalGetParent(element);
// avoid posting a refresh to an unvisible parent
if (element.equals(fInput)) {
postRefresh(element);
} else {
postRefresh(parent);
}
}
// more than one child changed, refresh from here downwards
if (element instanceof IPackageFragmentRoot && fBrowsingPart.isValidElement(element)) {
postRefresh(skipProjectPackageFragmentRoot((IPackageFragmentRoot)element));
return;
}
}
for (int i= 0; i < affectedChildren.length; i++) {
processDelta(affectedChildren[i]);
}
}
private boolean isOnClassPath(ICompilationUnit element) throws JavaModelException {
IJavaProject project= element.getJavaProject();
if (project == null || !project.exists())
return false;
return project.isOnClasspath(element);
}
/**
* Updates the package icon
*/
private void postUpdateIcon(final IJavaElement element) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.update(element, new String[]{IBasicPropertyConstants.P_IMAGE});
}
});
}
private void postRefresh(final Object root) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.setRedraw(false);
fViewer.refresh(root);
ctrl.setRedraw(true);
}
}
});
}
private void postAdd(final Object parent, final Object element) {
postAdd(parent, new Object[] {element});
}
private void postAdd(final Object parent, final Object[] elements) {
if (elements == null || elements.length <= 0)
return;
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.setRedraw(false);
Object[] newElements= getNewElements(elements);
if (fViewer instanceof AbstractTreeViewer) {
if (fViewer.testFindItem(parent) == null) {
Object root= ((AbstractTreeViewer)fViewer).getInput();
if (root != null)
((AbstractTreeViewer)fViewer).add(root, newElements);
}
else
((AbstractTreeViewer)fViewer).add(parent, newElements);
}
else if (fViewer instanceof ListViewer)
((ListViewer)fViewer).add(newElements);
else if (fViewer instanceof TableViewer)
((TableViewer)fViewer).add(newElements);
if (fViewer.testFindItem(elements[0]) != null)
fBrowsingPart.adjustInputAndSetSelection((IJavaElement)elements[0]);
ctrl.setRedraw(true);
}
}
});
}
private Object[] getNewElements(Object[] elements) {
int elementsLength= elements.length;
ArrayList result= new ArrayList(elementsLength);
for (int i= 0; i < elementsLength; i++) {
Object element= elements[i];
if (fViewer.testFindItem(element) == null)
result.add(element);
}
return result.toArray();
}
private void postRemove(final Object element) {
postRemove(new Object[] {element});
}
private void postRemove(final Object[] elements) {
if (elements.length <= 0)
return;
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.setRedraw(false);
if (fViewer instanceof AbstractTreeViewer)
((AbstractTreeViewer)fViewer).remove(elements);
else if (fViewer instanceof ListViewer)
((ListViewer)fViewer).remove(elements);
else if (fViewer instanceof TableViewer)
((TableViewer)fViewer).remove(elements);
ctrl.setRedraw(true);
}
}
});
}
private void postAdjustInputAndSetSelection(final Object element) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.setRedraw(false);
fBrowsingPart.adjustInputAndSetSelection((IJavaElement)element);
ctrl.setRedraw(true);
}
}
});
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
fBrowsingPart.setProcessSelectionEvents(false);
try {
Display currentDisplay= Display.getCurrent();
if (currentDisplay != null && currentDisplay.equals(ctrl.getDisplay()))
ctrl.getDisplay().syncExec(r);
else
ctrl.getDisplay().asyncExec(r);
} finally {
fBrowsingPart.setProcessSelectionEvents(true);
}
}
}
/**
* Returns the parent for the element.
* <p>
* Note: This method will return a working copy if the
* parent is a working copy. The super class implementation
* returns the original element instead.
* </p>
*/
protected Object internalGetParent(Object element) {
if (element instanceof IJavaProject) {
return ((IJavaProject)element).getJavaModel();
}
// try to map resources to the containing package fragment
if (element instanceof IResource) {
IResource parent= ((IResource)element).getParent();
Object jParent= JavaCore.create(parent);
if (jParent != null)
return jParent;
return parent;
}
// for package fragments that are contained in a project package fragment
// we have to skip the package fragment root as the parent.
if (element instanceof IPackageFragment) {
IPackageFragmentRoot parent= (IPackageFragmentRoot)((IPackageFragment)element).getParent();
return skipProjectPackageFragmentRoot(parent);
}
if (element instanceof IJavaElement)
return ((IJavaElement)element).getParent();
return null;
}
}
|
31,295 |
Bug 31295 javadoc export exception in the log
|
20030206 i missed it whet it happened because there was no dialog Java Model Exception: Java Model Status [org.eclipse.core.resources.win32 does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException (JavaElement.java:482) at org.eclipse.jdt.internal.core.JavaModelManager.getPerProjectInfoCheckExistence (JavaModelManager.java:943) at org.eclipse.jdt.internal.core.JavaProject.getResolvedClasspath (JavaProject.java:1351) at org.eclipse.jdt.internal.core.JavaProject.getResolvedClasspath (JavaProject.java:1336) at org.eclipse.jdt.internal.core.JavaProject.generateInfos (JavaProject.java:881) at org.eclipse.jdt.internal.core.Openable.buildStructure (Openable.java:71) at org.eclipse.jdt.internal.core.Openable.openWhenClosed (Openable.java:394) at org.eclipse.jdt.internal.core.JavaProject.openWhenClosed (JavaProject.java:1780) at org.eclipse.jdt.internal.core.JavaElement.openHierarchy (JavaElement.java:503) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:296) at org.eclipse.jdt.internal.core.JavaElement.getChildren (JavaElement.java:252) at org.eclipse.jdt.internal.core.JavaProject.getPackageFragmentRoots (JavaProject.java:1187) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.getValidProject (JavadocOptionsManager.java:1103) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.getProjects (JavadocOptionsManager.java:1047) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.getValidSelectio n(JavadocOptionsManager.java:1018) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.loadDefaults (JavadocOptionsManager.java:339) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.loadStore (JavadocOptionsManager.java:249) at org.eclipse.jdt.internal.ui.javadocexport.JavadocOptionsManager.<init> (JavadocOptionsManager.java:181) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.init (JavadocWizard.java:420) at org.eclipse.jdt.internal.ui.actions.GenerateJavadocAction.run (GenerateJavadocAction.java:45) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:250) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:202) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:398) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:392) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
92daeb7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-07T17:35:02Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocOptionsManager.java
|
/*
* Copyright (c) 2002 IBM Corp. All rights reserved.
* This file is made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*/
package org.eclipse.jdt.internal.ui.javadocexport;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IFile;
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.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
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.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.ExecutionArguments;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.preferences.JavadocPreferencePage;
public class JavadocOptionsManager {
private IWorkspaceRoot fRoot;
//consider making a List
private List fProjects;
private IFile fXmlfile;
private StatusInfo fWizardStatus;
private List fSourceElements;
private List fSelectedElements;
private String fAccess;
private String fDocletpath;
private String fDocletname;
private boolean fFromStandard;
private String fStylesheet;
private String fAdditionalParams;
private String fOverview;
private String fTitle;
private String fJDocCommand;
private IPath[] fSourcepath;
private IPath[] fClasspath;
private boolean fNotree;
private boolean fNoindex;
private boolean fSplitindex;
private boolean fNonavbar;
private boolean fNodeprecated;
private boolean fNoDeprecatedlist;
private boolean fAuthor;
private boolean fVersion;
private boolean fUse;
private boolean fOpenInBrowser;
//list of hrefs in string format
private Map fLinks;
//add-on for multi-project version
private String fDestination;
private String fDependencies;
private String fAntpath;
public final String PRIVATE= "private"; //$NON-NLS-1$
public final String PROTECTED= "protected"; //$NON-NLS-1$
public final String PACKAGE= "package"; //$NON-NLS-1$
public final String PUBLIC= "public"; //$NON-NLS-1$
public final String USE= "use"; //$NON-NLS-1$
public final String NOTREE= "notree"; //$NON-NLS-1$
public final String NOINDEX= "noindex"; //$NON-NLS-1$
public final String NONAVBAR= "nonavbar"; //$NON-NLS-1$
public final String NODEPRECATED= "nodeprecated"; //$NON-NLS-1$
public final String NODEPRECATEDLIST= "nodeprecatedlist"; //$NON-NLS-1$
public final String VERSION= "version"; //$NON-NLS-1$
public final String AUTHOR= "author"; //$NON-NLS-1$
public final String SPLITINDEX= "splitindex"; //$NON-NLS-1$
public final String STYLESHEETFILE= "stylesheetfile"; //$NON-NLS-1$
public final String OVERVIEW= "overview"; //$NON-NLS-1$
public final String DOCLETNAME= "docletname"; //$NON-NLS-1$
public final String DOCLETPATH= "docletpath"; //$NON-NLS-1$
public final String SOURCEPATH= "sourcepath"; //$NON-NLS-1$
public final String CLASSPATH= "classpath"; //$NON-NLS-1$
public final String DESTINATION= "destdir"; //$NON-NLS-1$
public final String OPENINBROWSER= "openinbrowser"; //$NON-NLS-1$
public final String VISIBILITY= "access"; //$NON-NLS-1$
public final String PACKAGENAMES= "packagenames"; //$NON-NLS-1$
public final String SOURCEFILES= "sourcefiles"; //$NON-NLS-1$
public final String EXTRAOPTIONS= "additionalparam"; //$NON-NLS-1$
public final String JAVADOCCOMMAND= "javadoccommand"; //$NON-NLS-1$
public final String TITLE= "doctitle"; //$NON-NLS-1$
public final String HREF= "href"; //$NON-NLS-1$
public final String NAME= "name"; //$NON-NLS-1$
public final String PATH= "path"; //$NON-NLS-1$
private final String FROMSTANDARD= "fromStandard"; //$NON-NLS-1$
private final String ANTPATH= "antpath"; //$NON-NLS-1$
/**
* @param xmlJavadocFile The ant file to take initl values from or null, if not started from an ant file.
* @param setting Dialog settings for the Javadoc exporter.
*/
public JavadocOptionsManager(IFile xmlJavadocFile, IDialogSettings settings, ISelection currSelection) {
Element element;
this.fRoot= ResourcesPlugin.getWorkspace().getRoot();
fJDocCommand= JavadocPreferencePage.getJavaDocCommand();
this.fXmlfile= xmlJavadocFile;
this.fWizardStatus= new StatusInfo();
this.fLinks= new HashMap();
fProjects= new ArrayList();
if (xmlJavadocFile != null) {
try {
JavadocReader reader= new JavadocReader(xmlJavadocFile.getContents());
element= reader.readXML();
IJavaProject p= reader.getProject();
if (element == null || p == null) {
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectCE.warning")); //$NON-NLS-1$
loadStore(settings, currSelection);
} else {
fProjects.add(p);
loadStore(element, settings);
}
} catch (CoreException e) {
JavaPlugin.log(e);
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectCE.warning")); //$NON-NLS-1$
loadStore(settings, currSelection);
} catch (IOException e) {
JavaPlugin.log(e);
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectIOE.warning")); //$NON-NLS-1$
loadStore(settings, currSelection);
} catch (SAXException e) {
fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectSAXE.warning")); //$NON-NLS-1$
loadStore(settings, currSelection);
}
} else
loadStore(settings, currSelection);
}
private void loadStore(IDialogSettings settings, ISelection sel) {
if (settings != null) {
//getValidSelection will also find the project
fSelectedElements= getValidSelection(sel);
fAccess= settings.get(VISIBILITY);
if (fAccess == null)
fAccess= PROTECTED;
//this is defaulted to false.
fFromStandard= settings.getBoolean(FROMSTANDARD);
//doclet is loaded even if the standard doclet is being used
fDocletpath= settings.get(DOCLETPATH);
fDocletname= settings.get(DOCLETNAME);
if (fDocletpath == null || fDocletname == null) {
fFromStandard= true;
fDocletpath= ""; //$NON-NLS-1$
fDocletname= ""; //$NON-NLS-1$
}
//load a default antpath
fAntpath= settings.get(ANTPATH);
if (fAntpath == null)
fAntpath= ""; //$NON-NLS-1$
//$NON-NLS-1$
//load a default antpath
fDestination= settings.get(DESTINATION);
if (fDestination == null)
fDestination= ""; //$NON-NLS-1$
//$NON-NLS-1$
fTitle= settings.get(TITLE);
if (fTitle == null)
fTitle= ""; //$NON-NLS-1$
fStylesheet= settings.get(STYLESHEETFILE);
if (fStylesheet == null)
fStylesheet= ""; //$NON-NLS-1$
fAdditionalParams= settings.get(EXTRAOPTIONS);
if (fAdditionalParams == null)
fAdditionalParams= ""; //$NON-NLS-1$
fOverview= settings.get(OVERVIEW);
if (fOverview == null)
fOverview= ""; //$NON-NLS-1$
fUse= loadbutton(settings.get(USE));
fAuthor= loadbutton(settings.get(AUTHOR));
fVersion= loadbutton(settings.get(VERSION));
fNodeprecated= loadbutton(settings.get(NODEPRECATED));
fNoDeprecatedlist= loadbutton(settings.get(NODEPRECATEDLIST));
fNonavbar= loadbutton(settings.get(NONAVBAR));
fNoindex= loadbutton(settings.get(NOINDEX));
fNotree= loadbutton(settings.get(NOTREE));
fSplitindex= loadbutton(settings.get(SPLITINDEX));
fOpenInBrowser= loadbutton(settings.get(OPENINBROWSER));
//get the set of project specific data
loadLinksFromDialogSettings(settings);
} else
loadDefaults(sel);
}
private String getDefaultAntPath(IJavaProject project) {
if (project != null) {
IPath path= project.getProject().getLocation();
if (path != null)
return path.append("javadoc.xml").toOSString(); //$NON-NLS-1$
}
return ""; //$NON-NLS-1$
}
private String getDefaultDestination(IJavaProject project) {
if (project != null) {
URL url= JavaUI.getProjectJavadocLocation(project);
//uses default if source is has http protocol
if (url == null || !url.getProtocol().equals("file")) { //$NON-NLS-1$
IPath path= project.getProject().getLocation();
if (path != null)
return path.append("doc").toOSString(); //$NON-NLS-1$
} else {
//must do this to remove leading "/"
return (new File(url.getFile())).getPath();
}
}
return ""; //$NON-NLS-1$
}
/**
* Method creates a list of data structes that contain
* The destination, antfile location and the list of library/project references for every
* project in the workspace.Defaults are created for new project.
*/
private void loadLinksFromDialogSettings(IDialogSettings settings) {
//sets data for projects if stored in the dialog settings
if (settings != null) {
IDialogSettings links= settings.getSection("projects"); //$NON-NLS-1$
if (links != null) {
IDialogSettings[] projs= links.getSections();
for (int i= 0; i < projs.length; i++) {
IDialogSettings iDialogSettings= projs[i];
String projectName= iDialogSettings.getName();
IProject project= fRoot.getProject(projectName);
//make sure project has not been removed
if (project.exists()) {
IJavaProject javaProject= JavaCore.create(project);
if (!fLinks.containsKey(javaProject)) {
String hrefs= iDialogSettings.get(HREF);
if (hrefs == null) {
hrefs= ""; //$NON-NLS-1$
}
String destdir= iDialogSettings.get(DESTINATION);
if (destdir == null || destdir.length() == 0) {
destdir= getDefaultDestination(javaProject);
}
String antpath= iDialogSettings.get(ANTPATH);
if (antpath == null || antpath.length() == 0) {
antpath= getDefaultAntPath(javaProject);
}
ProjectData data= new ProjectData(javaProject);
data.setDestination(destdir);
data.setAntpath(antpath);
data.setlinks(hrefs);
if (!fLinks.containsValue(javaProject))
fLinks.put(javaProject, data);
}
}
}
}
}
//finds projects in the workspace that have been added since the
//last time the wizard was run
IProject[] projects= fRoot.getProjects();
for (int i= 0; i < projects.length; i++) {
IProject iProject= projects[i];
IJavaProject javaProject= JavaCore.create(iProject);
if (!fLinks.containsKey(javaProject)) {
ProjectData data= new ProjectData(javaProject);
data.setDestination(getDefaultDestination(javaProject));
data.setAntpath(getDefaultAntPath(javaProject));
data.setlinks(""); //$NON-NLS-1$
fLinks.put(javaProject, data);
}
}
}
//loads defaults for wizard (nothing is stored)
private void loadDefaults(ISelection sel) {
fSelectedElements= getValidSelection(sel);
fAccess= PUBLIC;
fDocletname= ""; //$NON-NLS-1$
fDocletpath= ""; //$NON-NLS-1$
fTitle= ""; //$NON-NLS-1$
fStylesheet= ""; //$NON-NLS-1$
fAdditionalParams= ""; //$NON-NLS-1$
fOverview= ""; //$NON-NLS-1$
fAntpath= ""; //$NON-NLS-1$
fDestination= ""; //$NON-NLS-1$
fUse= true;
fAuthor= true;
fVersion= true;
fNodeprecated= false;
fNoDeprecatedlist= false;
fNonavbar= false;
fNoindex= false;
fNotree= false;
fSplitindex= true;
fOpenInBrowser= false;
//by default it is empty all project map to the empty string
fFromStandard= true;
loadLinksFromDialogSettings(null);
}
private void loadStore(Element element, IDialogSettings settings) {
fAccess= element.getAttribute(VISIBILITY);
if (!(fAccess.length() > 0))
fAccess= PROTECTED;
//Since the selected packages are stored we must locate the project
String destination= element.getAttribute(DESTINATION);
fDestination= destination;
fFromStandard= true;
fDocletname= ""; //$NON-NLS-1$
fDocletpath= ""; //$NON-NLS-1$
if (destination.equals("")) { //$NON-NLS-1$
NodeList list= element.getChildNodes();
for (int i= 0; i < list.getLength(); i++) {
Node child= list.item(i);
if (child.getNodeName().equals("doclet")) { //$NON-NLS-1$
fDocletpath= ((Element) child).getAttribute(PATH);
fDocletname= ((Element) child).getAttribute(NAME);
if (!(fDocletpath.equals("") && !fDocletname.equals(""))) { //$NON-NLS-1$ //$NON-NLS-2$
fFromStandard= false;
} else {
fDocletname= ""; //$NON-NLS-1$
fDocletpath= ""; //$NON-NLS-1$
}
break;
}
}
}
//find all the links stored in the ant script
boolean firstTime= true;
StringBuffer buf= new StringBuffer();
NodeList children= element.getChildNodes();
for (int i= 0; i < children.getLength(); i++) {
Node child= children.item(i);
if (child.getNodeName().equals("link")) { //$NON-NLS-1$
String href= ((Element) child).getAttribute(HREF);
if (firstTime)
firstTime= false;
else
buf.append(';');
buf.append(href);
}
}
//associate all those links with each project selected
for (Iterator iter= fProjects.iterator(); iter.hasNext();) {
IJavaProject iJavaProject= (IJavaProject) iter.next();
ProjectData data= new ProjectData(iJavaProject);
IPath path= fXmlfile.getLocation();
if (path != null)
data.setAntpath(path.toOSString());
else
data.setAntpath(""); //$NON-NLS-1$
data.setlinks(buf.toString());
data.setDestination(destination);
fLinks.put(iJavaProject, data);
}
//get tree elements
setSelectedElementsFromAnt(element, (IJavaProject) fProjects.get(0));
IPath p= fXmlfile.getLocation();
if (p != null)
fAntpath= p.toOSString();
else
fAntpath= ""; //$NON-NLS-1$
fStylesheet= element.getAttribute(STYLESHEETFILE);
fTitle= element.getAttribute(TITLE);
fAdditionalParams= element.getAttribute(EXTRAOPTIONS);
fOverview= element.getAttribute(OVERVIEW);
fUse= loadbutton(element.getAttribute(USE));
fAuthor= loadbutton(element.getAttribute(AUTHOR));
fVersion= loadbutton(element.getAttribute(VERSION));
fNodeprecated= loadbutton(element.getAttribute(NODEPRECATED));
fNoDeprecatedlist= loadbutton(element.getAttribute(NODEPRECATEDLIST));
fNonavbar= loadbutton(element.getAttribute(NONAVBAR));
fNoindex= loadbutton(element.getAttribute(NOINDEX));
fNotree= loadbutton(element.getAttribute(NOTREE));
fSplitindex= loadbutton(element.getAttribute(SPLITINDEX));
}
/*
* Method creates an absolute path to the project. If the path is already
* absolute it returns the path. If it encounters any difficulties in
* creating the absolute path, the method returns null.
*
* @param pathStr
* @return IPath
*/
private IPath makeAbsolutePathFromRelative(String pathStr) {
IPath path= new Path(pathStr);
if (!path.isAbsolute()) {
if (fXmlfile == null) {
return null;
}
IPath basePath= fXmlfile.getParent().getLocation(); // relative to the ant file location
if (basePath == null) {
return null;
}
return basePath.append(pathStr);
}
return path;
}
private void setSelectedElementsFromAnt(Element element, IJavaProject iJavaProject) {
fSelectedElements= new ArrayList();
//get all the packages in side the project
String name;
String packagenames= element.getAttribute(PACKAGENAMES);
if (packagenames != null) {
StringTokenizer tokenizer= new StringTokenizer(packagenames, ","); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
name= tokenizer.nextToken().trim();
IJavaElement el;
try {
el= JavaModelUtil.findTypeContainer(iJavaProject, name);
} catch (JavaModelException e) {
JavaPlugin.log(e);
continue;
}
if ((el != null) && (el instanceof IPackageFragment)) {
fSelectedElements.add(el);
}
}
}
//get all CompilationUnites in side the project
String sourcefiles= element.getAttribute(SOURCEFILES);
if (sourcefiles != null) {
StringTokenizer tokenizer= new StringTokenizer(sourcefiles, ","); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
name= tokenizer.nextToken().trim();
if (name.endsWith(".java")) { //$NON-NLS-1$
IPath path= makeAbsolutePathFromRelative(name);
//if unable to create an absolute path the the resource skip it
if (path == null)
continue;
IFile[] files= fRoot.findFilesForLocation(path);
for (int i= 0; i < files.length; i++) {
IFile curr= files[i];
if (curr.getProject().equals(iJavaProject.getProject())) {
IJavaElement el= JavaCore.createCompilationUnitFrom(curr);
if (el != null) {
fSelectedElements.add(el);
}
}
}
}
}
}
}
//it is possible that the package list is empty
public StatusInfo getWizardStatus() {
return fWizardStatus;
}
public IJavaElement[] getSelectedElements() {
return (IJavaElement[]) fSelectedElements.toArray(new IJavaElement[fSelectedElements.size()]);
}
public IJavaElement[] getSourceElements() {
return (IJavaElement[]) fSourceElements.toArray(new IJavaElement[fSourceElements.size()]);
}
public String getAccess() {
return fAccess;
}
public String getGeneralAntpath() {
return fAntpath;
}
public String getSpecificAntpath(IJavaProject project) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
return data.getAntPath();
else
return ""; //$NON-NLS-1$
}
public boolean fromStandard() {
return fFromStandard;
}
//for now if multiple projects are selected the destination
//feild will be empty,
public String getDestination(IJavaProject project) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
return data.getDestination();
else
return ""; //$NON-NLS-1$
}
public String getDestination() {
return fDestination;
}
public String getDocletPath() {
return fDocletpath;
}
public String getDocletName() {
return fDocletname;
}
public String getStyleSheet() {
return fStylesheet;
}
public String getOverview() {
return fOverview;
}
public String getAdditionalParams() {
return fAdditionalParams;
}
public IPath[] getClasspath() {
return fClasspath;
}
public IPath[] getSourcepath() {
return fSourcepath;
}
public IWorkspaceRoot getRoot() {
return fRoot;
}
// public IJavaProject[] getJavaProjects() {
// return (IJavaProject[]) fProjects.toArray(new IJavaProject[fProjects.size()]);
// }
//Use only this one later
public List getJavaProjects() {
return fProjects;
}
public String getTitle() {
return fTitle;
}
public String getLinks(IJavaProject project) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
return data.getlinks();
else
return ""; //$NON-NLS-1$
}
public String getDependencies() {
return fDependencies;
}
public Map getLinkMap() {
return fLinks;
}
public boolean doOpenInBrowser() {
return fOpenInBrowser;
}
public boolean getBoolean(String flag) {
if (flag.equals(AUTHOR))
return fAuthor;
else if (flag.equals(VERSION))
return fVersion;
else if (flag.equals(USE))
return fUse;
else if (flag.equals(NODEPRECATED))
return fNodeprecated;
else if (flag.equals(NODEPRECATEDLIST))
return fNoDeprecatedlist;
else if (flag.equals(NOINDEX))
return fNoindex;
else if (flag.equals(NOTREE))
return fNotree;
else if (flag.equals(SPLITINDEX))
return fSplitindex;
else if (flag.equals(NONAVBAR))
return fNonavbar;
else
return false;
}
private boolean loadbutton(String value) {
if (value == null || value.equals("")) //$NON-NLS-1$
return false;
else {
if (value.equals("true")) //$NON-NLS-1$
return true;
else
return false;
}
}
private String flatPathList(IPath[] paths) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < paths.length; i++) {
if (i > 0) {
buf.append(File.pathSeparatorChar);
}
buf.append(paths[i].toOSString());
}
return buf.toString();
}
public String[] createArgumentArray() throws CoreException {
if (fProjects.isEmpty()) {
return new String[0];
}
List args= new ArrayList();
args.add(fJDocCommand);
if (fFromStandard) {
args.add("-d"); //$NON-NLS-1$
args.add(fDestination);
} else {
if (!fAdditionalParams.equals("")) { //$NON-NLS-1$
ExecutionArguments tokens= new ExecutionArguments("", fAdditionalParams); //$NON-NLS-1$
String[] argsArray= tokens.getProgramArgumentsArray();
for (int i= 0; i < argsArray.length; i++) {
args.add(argsArray[i]);
}
}
args.add("-doclet"); //$NON-NLS-1$
args.add(fDocletname);
args.add("-docletpath"); //$NON-NLS-1$
args.add(fDocletpath);
}
args.add("-sourcepath"); //$NON-NLS-1$
args.add(flatPathList(fSourcepath));
args.add("-classpath"); //$NON-NLS-1$
args.add(flatPathList(fClasspath));
args.add("-" + fAccess); //$NON-NLS-1$
if (fFromStandard) {
if (fUse)
args.add("-use"); //$NON-NLS-1$
if (fVersion)
args.add("-version"); //$NON-NLS-1$
if (fAuthor)
args.add("-author"); //$NON-NLS-1$
if (fNonavbar)
args.add("-nonavbar"); //$NON-NLS-1$
if (fNoindex)
args.add("-noindex"); //$NON-NLS-1$
if (fNotree)
args.add("-notree"); //$NON-NLS-1$
if (fNodeprecated)
args.add("-nodeprecated"); //$NON-NLS-1$
if (fNoDeprecatedlist)
args.add("-nodeprecatedlist"); //$NON-NLS-1$
if (fSplitindex)
args.add("-splitindex"); //$NON-NLS-1$
if (!fTitle.equals("")) { //$NON-NLS-1$
args.add("-doctitle"); //$NON-NLS-1$
args.add(fTitle);
}
if (!fStylesheet.equals("")) { //$NON-NLS-1$
args.add("-stylesheetfile"); //$NON-NLS-1$
args.add(fStylesheet);
}
if (!fAdditionalParams.equals("")) { //$NON-NLS-1$
ExecutionArguments tokens= new ExecutionArguments("", fAdditionalParams); //$NON-NLS-1$
String[] argsArray= tokens.getProgramArgumentsArray();
for (int i= 0; i < argsArray.length; i++) {
args.add(argsArray[i]);
}
}
String hrefs= (String) fDependencies;
StringTokenizer tokenizer= new StringTokenizer(hrefs, ";"); //$NON-NLS-1$
while (tokenizer.hasMoreElements()) {
String href= (String) tokenizer.nextElement();
args.add("-link"); //$NON-NLS-1$
args.add(href);
}
} //end standard options
if (!fOverview.equals("")) { //$NON-NLS-1$
args.add("-overview"); //$NON-NLS-1$
args.add(fOverview);
}
for (int i= 0; i < fSourceElements.size(); i++) {
IJavaElement curr= (IJavaElement) fSourceElements.get(i);
if (curr instanceof IPackageFragment) {
args.add(curr.getElementName());
} else if (curr instanceof ICompilationUnit) {
IPath p= curr.getResource().getLocation();
if (p != null)
args.add(p.toOSString());
}
}
String[] res= (String[]) args.toArray(new String[args.size()]);
return res;
}
public void createXML() {
FileOutputStream objectStreamOutput= null;
//@change
//for now only writting ant files for single project selection
String antpath= fAntpath;
try {
if (!antpath.equals("")) { //$NON-NLS-1$
File file= new File(antpath);
IPath antPath= new Path(antpath);
IPath antDir= antPath.removeLastSegments(1);
IPath basePath= null;
Assert.isTrue(fProjects.size() == 1);
IJavaProject jproject= (IJavaProject) fProjects.get(0);
IWorkspaceRoot root= jproject.getProject().getWorkspace().getRoot();
if (root.findFilesForLocation(antPath).length > 0) {
basePath= antDir; // only do relative path if ant file is stored in the workspace
}
antDir.toFile().mkdirs();
objectStreamOutput= new FileOutputStream(file);
JavadocWriter writer= new JavadocWriter(objectStreamOutput, basePath, jproject);
writer.writeXML(this);
}
} catch (IOException e) {
JavaPlugin.log(e);
} catch (CoreException e) {
JavaPlugin.log(e);
} finally {
if (objectStreamOutput != null) {
try {
objectStreamOutput.close();
} catch (IOException e) {
}
}
}
}
public IDialogSettings createDialogSettings() {
IDialogSettings settings= new DialogSettings("javadoc"); //$NON-NLS-1$
settings.put(FROMSTANDARD, fFromStandard);
settings.put(DOCLETNAME, fDocletname);
settings.put(DOCLETPATH, fDocletpath);
settings.put(VISIBILITY, fAccess);
settings.put(USE, fUse);
settings.put(AUTHOR, fAuthor);
settings.put(VERSION, fVersion);
settings.put(NODEPRECATED, fNodeprecated);
settings.put(NODEPRECATEDLIST, fNoDeprecatedlist);
settings.put(SPLITINDEX, fSplitindex);
settings.put(NOINDEX, fNoindex);
settings.put(NOTREE, fNotree);
settings.put(NONAVBAR, fNonavbar);
settings.put(OPENINBROWSER, fOpenInBrowser);
if (!fAntpath.equals("")) //$NON-NLS-1$
settings.put(ANTPATH, fAntpath);
if (!fDestination.equals("")) //$NON-NLS-1$
settings.put(DESTINATION, fDestination);
if (!fAdditionalParams.equals("")) //$NON-NLS-1$
settings.put(EXTRAOPTIONS, fAdditionalParams);
if (!fOverview.equals("")) //$NON-NLS-1$
settings.put(OVERVIEW, fOverview);
if (!fStylesheet.equals("")) //$NON-NLS-1$
settings.put(STYLESHEETFILE, fStylesheet);
if (!fTitle.equals("")) //$NON-NLS-1$
settings.put(TITLE, fTitle);
IDialogSettings links= new DialogSettings("projects"); //$NON-NLS-1$
//Write all project information to DialogSettings.
Set keys= fLinks.keySet();
for (Iterator iter= keys.iterator(); iter.hasNext();) {
IJavaProject iJavaProject= (IJavaProject) iter.next();
IDialogSettings proj= new DialogSettings(iJavaProject.getElementName());
if (!keys.contains(iJavaProject)) {
proj.put(HREF, ""); //$NON-NLS-1$
proj.put(DESTINATION, ""); //$NON-NLS-1$
proj.put(ANTPATH, ""); //$NON-NLS-1$
} else {
ProjectData data= (ProjectData) fLinks.get(iJavaProject);
proj.put(HREF, data.getlinks());
proj.put(DESTINATION, data.getDestination());
proj.put(ANTPATH, data.getAntPath());
}
links.addSection(proj);
}
settings.addSection(links);
return settings;
}
public void setAccess(String access) {
this.fAccess= access;
}
public void setDestination(IJavaProject project, String destination) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
data.setDestination(destination);
}
public void setDestination(String destination) {
fDestination= destination;
}
public void setDocletPath(String docletpath) {
this.fDocletpath= docletpath;
}
public void setDocletName(String docletname) {
this.fDocletname= docletname;
}
public void setStyleSheet(String stylesheet) {
this.fStylesheet= stylesheet;
}
public void setOverview(String overview) {
this.fOverview= overview;
}
public void setAdditionalParams(String params) {
fAdditionalParams= params;
}
public void setSpecificAntpath(IJavaProject project, String antpath) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
data.setAntpath(antpath);
}
public void setGeneralAntpath(String antpath) {
this.fAntpath= antpath;
}
public void setClasspath(IPath[] classpath) {
this.fClasspath= classpath;
}
public void setSourcepath(IPath[] sourcepath) {
this.fSourcepath= sourcepath;
}
public void setSourceElements(IJavaElement[] elements) {
this.fSourceElements= new ArrayList(Arrays.asList(elements));
}
public void setRoot(IWorkspaceRoot root) {
this.fRoot= root;
}
public void setProjects(IJavaProject[] projects, boolean clear) {
if (clear)
fProjects.clear();
for (int i= 0; i < projects.length; i++) {
IJavaProject iJavaProject= projects[i];
if (!fProjects.contains(iJavaProject))
this.fProjects.add(iJavaProject);
}
}
public void setFromStandard(boolean fromStandard) {
this.fFromStandard= fromStandard;
}
public void setTitle(String title) {
this.fTitle= title;
}
public void setDependencies(String dependencies) {
fDependencies= dependencies;
}
public void setLinks(IJavaProject project, String hrefs) {
ProjectData data= (ProjectData) fLinks.get(project);
if (data != null)
data.setlinks(hrefs);
}
public void setOpenInBrowser(boolean openInBrowser) {
this.fOpenInBrowser= openInBrowser;
}
public void setBoolean(String flag, boolean value) {
if (flag.equals(AUTHOR))
this.fAuthor= value;
else if (flag.equals(USE))
this.fUse= value;
else if (flag.equals(VERSION))
this.fVersion= value;
else if (flag.equals(NODEPRECATED))
this.fNodeprecated= value;
else if (flag.equals(NODEPRECATEDLIST))
this.fNoDeprecatedlist= value;
else if (flag.equals(NOINDEX))
this.fNoindex= value;
else if (flag.equals(NOTREE))
this.fNotree= value;
else if (flag.equals(SPLITINDEX))
this.fSplitindex= value;
else if (flag.equals(NONAVBAR))
this.fNonavbar= value;
}
private List getValidSelection(ISelection currentSelection) {
ArrayList res= new ArrayList();
if (currentSelection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection= (IStructuredSelection) currentSelection;
if (structuredSelection.isEmpty()) {
currentSelection= JavaPlugin.getActiveWorkbenchWindow().getSelectionService().getSelection();
if (currentSelection instanceof IStructuredSelection)
structuredSelection= (IStructuredSelection) currentSelection;
}
Iterator iter= structuredSelection.iterator();
//this method will also find the project for default
//destination and ant generation paths
getProjects(res, iter);
}
return res;
}
private void getProjects(List selectedElements, Iterator iter) {
while (iter.hasNext()) {
Object selectedElement= iter.next();
IJavaElement elem= getSelectableJavaElement(selectedElement);
if (elem != null) {
IJavaProject jproj= elem.getJavaProject();
if (jproj != null) {
//adding the project of the selected element in the list
//now we can select and generate javadoc for two
//methods in different projects
if (!fProjects.contains(jproj))
fProjects.add(jproj);
selectedElements.add(elem);
}
}
}
//if no projects selected add a default
if (fProjects.isEmpty()) {
Object[] roots= fRoot.getProjects();
for (int i= 0; i < roots.length; i++) {
IProject p= (IProject) roots[i];
IJavaProject iJavaProject= JavaCore.create(p);
if (getValidProject(iJavaProject)) {
fProjects.add(iJavaProject);
break;
}
}
}
}
private IJavaElement getSelectableJavaElement(Object obj) {
IJavaElement je= null;
try {
if (obj instanceof IAdaptable) {
je= (IJavaElement) ((IAdaptable) obj).getAdapter(IJavaElement.class);
}
if (je == null) {
return null;
}
switch (je.getElementType()) {
case IJavaElement.JAVA_MODEL :
case IJavaElement.JAVA_PROJECT :
case IJavaElement.CLASS_FILE :
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT :
if (containsCompilationUnits((IPackageFragmentRoot) je)) {
return je;
}
break;
case IJavaElement.PACKAGE_FRAGMENT :
if (containsCompilationUnits((IPackageFragment) je)) {
return je;
}
break;
default :
ICompilationUnit cu= (ICompilationUnit) je.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
if (cu.isWorkingCopy()) {
cu= (ICompilationUnit) cu.getOriginalElement();
}
return cu;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
IJavaProject project= je.getJavaProject();
if (getValidProject(project))
return project;
else
return null;
}
private boolean getValidProject(IJavaProject project) {
if (project != null) {
try {
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
if (containsCompilationUnits(roots[i])) {
return true;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return false;
}
private boolean containsCompilationUnits(IPackageFragmentRoot root) throws JavaModelException {
if (root.getKind() != IPackageFragmentRoot.K_SOURCE) {
return false;
}
IJavaElement[] elements= root.getChildren();
for (int i= 0; i < elements.length; i++) {
if (elements[i] instanceof IPackageFragment) {
IPackageFragment fragment= (IPackageFragment) elements[i];
if (containsCompilationUnits(fragment)) {
return true;
}
}
}
return false;
}
private boolean containsCompilationUnits(IPackageFragment pack) throws JavaModelException {
return pack.getCompilationUnits().length > 0;
}
private class ProjectData {
private IJavaProject dataProject;
private String dataHrefs;
private String dataDestdir;
private String dataAntPath;
ProjectData(IJavaProject project) {
dataProject= project;
}
public void setlinks(String hrefs) {
if (hrefs == null)
dataHrefs= ""; //$NON-NLS-1$
else
dataHrefs= hrefs;
}
public void setDestination(String destination) {
if (destination == null)
dataDestdir= ""; //$NON-NLS-1$
else
dataDestdir= destination;
}
public void setAntpath(String antpath) {
if (antpath == null)
dataAntPath= ""; //$NON-NLS-1$
else
dataAntPath= antpath;
}
public String getlinks() {
return dataHrefs;
}
public String getDestination() {
return dataDestdir;
}
public String getAntPath() {
return dataAntPath;
}
}
}
|
31,289 |
Bug 31289 StringIndexOutOfBoundsException is ASTRewrite
|
20030206 1. select CUCorrectionProposal.createCompilationUnitChange pull up java.lang.reflect.InvocationTargetException: java.lang.StringIndexOutOfBoundsException: String index out of range: 122 at java.lang.String.substring(String.java(Compiled Code)) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.doTextInsert (ASTRewriteAnalyzer.java:681) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.rewriteList (ASTRewriteAnalyzer.java:531) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.rewriteParagraphList (ASTRewriteAnalyzer.java:355) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.visit (ASTRewriteAnalyzer.java:887) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:154) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.visitList (ASTRewriteAnalyzer.java(Compiled Code)) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.visitList (ASTRewriteAnalyzer.java(Compiled Code)) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.rewriteParagraphList (ASTRewriteAnalyzer.java:350) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.visit (ASTRewriteAnalyzer.java:806) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:155) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java(Compiled Code)) at org.eclipse.jdt.internal.corext.dom.ASTRewrite.rewriteNode (ASTRewrite.java:120) at org.eclipse.jdt.internal.corext.refactoring.structure.PullUpRefactoring.fillWith RewriteEdits(PullUpRefactoring.java:1573) at org.eclipse.jdt.internal.corext.refactoring.structure.PullUpRefactoring.createCh angeManager(PullUpRefactoring.java:1171) at org.eclipse.jdt.internal.corext.refactoring.structure.PullUpRefactoring.checkInp ut(PullUpRefactoring.java:688) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:716) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactorin g(PerformRefactoringUtil.java:43) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:366) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.PullUpInputPage2.performFinish (PullUpInputPage2.java:373) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:429) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog.finishPressed (RefactoringWizardDialog.java:73) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:308) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:417) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (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:541) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:59) at org.eclipse.jdt.ui.actions.PullUpAction.startRefactoring (PullUpAction.java:177) at org.eclipse.jdt.ui.actions.PullUpAction.run(PullUpAction.java:100) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:191) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (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.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.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:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
2d36dbe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-07T18:46:10Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,289 |
Bug 31289 StringIndexOutOfBoundsException is ASTRewrite
|
20030206 1. select CUCorrectionProposal.createCompilationUnitChange pull up java.lang.reflect.InvocationTargetException: java.lang.StringIndexOutOfBoundsException: String index out of range: 122 at java.lang.String.substring(String.java(Compiled Code)) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.doTextInsert (ASTRewriteAnalyzer.java:681) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.rewriteList (ASTRewriteAnalyzer.java:531) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.rewriteParagraphList (ASTRewriteAnalyzer.java:355) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.visit (ASTRewriteAnalyzer.java:887) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:154) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.visitList (ASTRewriteAnalyzer.java(Compiled Code)) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.visitList (ASTRewriteAnalyzer.java(Compiled Code)) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.rewriteParagraphList (ASTRewriteAnalyzer.java:350) at org.eclipse.jdt.internal.corext.dom.ASTRewriteAnalyzer.visit (ASTRewriteAnalyzer.java:806) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:155) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java(Compiled Code)) at org.eclipse.jdt.internal.corext.dom.ASTRewrite.rewriteNode (ASTRewrite.java:120) at org.eclipse.jdt.internal.corext.refactoring.structure.PullUpRefactoring.fillWith RewriteEdits(PullUpRefactoring.java:1573) at org.eclipse.jdt.internal.corext.refactoring.structure.PullUpRefactoring.createCh angeManager(PullUpRefactoring.java:1171) at org.eclipse.jdt.internal.corext.refactoring.structure.PullUpRefactoring.checkInp ut(PullUpRefactoring.java:688) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:716) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactorin g(PerformRefactoringUtil.java:43) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:366) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.PullUpInputPage2.performFinish (PullUpInputPage2.java:373) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:429) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog.finishPressed (RefactoringWizardDialog.java:73) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:308) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:417) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (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:541) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:59) at org.eclipse.jdt.ui.actions.PullUpAction.startRefactoring (PullUpAction.java:177) at org.eclipse.jdt.ui.actions.PullUpAction.run(PullUpAction.java:100) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:191) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (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.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.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:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
2d36dbe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-07T18:46:10Z | 2003-02-07T15:00:00Z |
extension/org/eclipse/jdt/internal/corext/dom/ASTWithExistingFlattener.java
| |
31,300 |
Bug 31300 RepositoryProvider.isShared has problems with closed projects [API]
|
build i0206 (1700), win2k, j9sc20030205 In the Packages View, when I select to filter out projects which are non- shared, I get the following warnings in my log file. Note that all these are all the closed projects in my workspace and they are all shared. !ENTRY org.eclipse.core.resources 4 372 Feb 07, 2003 09:45:50.574 !MESSAGE Resource /org.eclipse.core.tests.resources.saveparticipant is not open. !ENTRY org.eclipse.core.resources 4 372 Feb 07, 2003 09:45:50.604 !MESSAGE Resource /org.eclipse.core.tests.resources.saveparticipant1 is not open . !ENTRY org.eclipse.core.resources 4 372 Feb 07, 2003 09:45:50.614 !MESSAGE Resource /org.eclipse.core.tests.resources.saveparticipant2 is not open . !ENTRY org.eclipse.core.resources 4 372 Feb 07, 2003 09:45:50.644 !MESSAGE Resource /org.eclipse.core.tests.resources.saveparticipant3 is not open . !ENTRY org.eclipse.core.resources 4 372 Feb 07, 2003 09:45:50.674 !MESSAGE Resource /org.eclipse.core.tools.wizards is not open. !ENTRY org.eclipse.core.resources 4 372 Feb 07, 2003 09:45:50.694 !MESSAGE Resource /org.eclipse.platform.doc.isv is not open. !ENTRY org.eclipse.core.resources 4 372 Feb 07, 2003 09:45:50.734 !MESSAGE Resource /org.eclipse.platform.doc.user is not open. !ENTRY org.eclipse.core.resources 4 372 Feb 07, 2003 09:45:50.774 !MESSAGE Resource /org.eclipse.webdav.tests is not open. !ENTRY org.eclipse.core.resources 4 372 Feb 07, 2003 09:45:50.934 !MESSAGE Resource /org.eclipse.core.tests.resources.saveparticipant is not open.
|
resolved fixed
|
b7ff326
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T10:09:25Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/NonSharedProjectFilter.java
| |
31,244 |
Bug 31244 Renaming linked source folder copies content
|
I20030206 - Create project with "linked src folder" - rename folder Observe: you loose the link and the content gets copied. I would expect simply renaming the link.
|
verified fixed
|
4c131fd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T10:20:02Z | 2003-02-07T12:13:20Z |
org.eclipse.jdt.ui/core
| |
31,244 |
Bug 31244 Renaming linked source folder copies content
|
I20030206 - Create project with "linked src folder" - rename folder Observe: you loose the link and the content gets copied. I would expect simply renaming the link.
|
verified fixed
|
4c131fd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T10:20:02Z | 2003-02-07T12:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/RenameResourceChange.java
| |
31,244 |
Bug 31244 Renaming linked source folder copies content
|
I20030206 - Create project with "linked src folder" - rename folder Observe: you loose the link and the content gets copied. I would expect simply renaming the link.
|
verified fixed
|
4c131fd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T10:20:02Z | 2003-02-07T12:13:20Z |
org.eclipse.jdt.ui/core
| |
31,244 |
Bug 31244 Renaming linked source folder copies content
|
I20030206 - Create project with "linked src folder" - rename folder Observe: you loose the link and the content gets copied. I would expect simply renaming the link.
|
verified fixed
|
4c131fd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T10:20:02Z | 2003-02-07T12:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/RenameSourceFolderChange.java
| |
28,479 |
Bug 28479 logical packages not recognized as Java by Search [browsing]
|
1) Select a logical package 2) open the search dialog ->it defaults to the File search, I would have expected that it defaults to the Java search
|
verified fixed
|
ec7b2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T11:40:21Z | 2002-12-17T10:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
import org.eclipse.jdt.internal.ui.javaeditor.ClassFileDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemMarkerManager;
/**
* Represents the java plugin. It provides a series of convenience methods such as
* access to the workbench, keeps track of elements shared by all editors and viewers
* of the plugin such as document providers and find-replace-dialogs.
*/
public class JavaPlugin extends AbstractUIPlugin {
// TODO: Evaluate if we should move these ID's to JavaUI
/**
* The id of the best match hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_BESTMATCH_HOVER= "org.eclipse.jdt.ui.BestMatchHover"; //$NON-NLS-1$
/**
* The id of the source code hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_SOURCE_HOVER= "org.eclipse.jdt.ui.JavaSourceHover"; //$NON-NLS-1$
/**
* The id of the javadoc hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_JAVADOC_HOVER= "org.eclipse.jdt.ui.JavadocHover"; //$NON-NLS-1$
/**
* The id of the problem hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_PROBLEM_HOVER= "org.eclipse.jdt.ui.ProblemHover"; //$NON-NLS-1$
private static JavaPlugin fgJavaPlugin;
private CompilationUnitDocumentProvider fCompilationUnitDocumentProvider;
private ClassFileDocumentProvider fClassFileDocumentProvider;
private JavaTextTools fJavaTextTools;
private ProblemMarkerManager fProblemMarkerManager;
private ImageDescriptorRegistry fImageDescriptorRegistry;
private JavaElementAdapterFactory fJavaElementAdapterFactory;
private MarkerAdapterFactory fMarkerAdapterFactory;
private EditorInputAdapterFactory fEditorInputAdapterFactory;
private ResourceAdapterFactory fResourceAdapterFactory;
private MembersOrderPreferenceCache fMembersOrderPreferenceCache;
private IPropertyChangeListener fFontPropertyChangeListener;
private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;
public static JavaPlugin getDefault() {
return fgJavaPlugin;
}
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
public static IWorkbenchPage getActivePage() {
return getDefault().internalGetActivePage();
}
public static IWorkbenchWindow getActiveWorkbenchWindow() {
return getDefault().getWorkbench().getActiveWorkbenchWindow();
}
public static Shell getActiveWorkbenchShell() {
return getActiveWorkbenchWindow().getShell();
}
/**
* Returns an array of all editors that have an unsaved content. If the identical content is
* presented in more than one editor, only one of those editor parts is part of the result.
*
* @return an array of all dirty editor parts.
*/
public static IEditorPart[] getDirtyEditors() {
Set inputs= new HashSet();
List result= new ArrayList(0);
IWorkbench workbench= getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int i= 0; i < windows.length; i++) {
IWorkbenchPage[] pages= windows[i].getPages();
for (int x= 0; x < pages.length; x++) {
IEditorPart[] editors= pages[x].getDirtyEditors();
for (int z= 0; z < editors.length; z++) {
IEditorPart ep= editors[z];
IEditorInput input= ep.getEditorInput();
if (!inputs.contains(input)) {
inputs.add(input);
result.add(ep);
}
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
}
/**
* Returns an array of all instanciated editors.
*/
public static IEditorPart[] getInstanciatedEditors() {
List result= new ArrayList(0);
IWorkbench workbench= getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int windowIndex= 0; windowIndex < windows.length; windowIndex++) {
IWorkbenchPage[] pages= windows[windowIndex].getPages();
for (int pageIndex= 0; pageIndex < pages.length; pageIndex++) {
IEditorReference[] references= pages[pageIndex].getEditorReferences();
for (int refIndex= 0; refIndex < references.length; refIndex++) {
IEditorPart editor= references[refIndex].getEditor(false);
if (editor != null)
result.add(editor);
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
} public static String getPluginId() {
return getDefault().getDescriptor().getUniqueIdentifier();
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static void logErrorMessage(String message) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null));
}
public static void logErrorStatus(String message, IStatus status) {
if (status == null) {
logErrorMessage(message);
return;
}
MultiStatus multi= new MultiStatus(getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null);
multi.add(status);
log(multi);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$
}
public static boolean isDebug() {
return getDefault().isDebugging();
}
/* package */ static IPath getInstallLocation() {
return new Path(getDefault().getDescriptor().getInstallURL().getFile());
}
public static ImageDescriptorRegistry getImageDescriptorRegistry() {
return getDefault().internalGetImageDescriptorRegistry();
}
public JavaPlugin(IPluginDescriptor descriptor) {
super(descriptor);
fgJavaPlugin= this;
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void startup() throws CoreException {
super.startup();
registerAdapters();
/*
* Backward compatibility: set the Java editor font in this plug-in's
* preference store to let older versions access it. Since 2.1 the
* Java editor font is managed by the workbench font preference page.
*/
PreferenceConverter.setValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT).getFontData());
fFontPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty()))
PreferenceConverter.setValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT).getFontData());
}
};
JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
}
/* (non - Javadoc)
* Method declared in AbstractUIPlugin
*/
protected ImageRegistry createImageRegistry() {
return JavaPluginImages.getImageRegistry();
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void shutdown() throws CoreException {
if (fImageDescriptorRegistry != null)
fImageDescriptorRegistry.dispose();
unregisterAdapters();
super.shutdown();
if (fCompilationUnitDocumentProvider != null) {
fCompilationUnitDocumentProvider.shutdown();
fCompilationUnitDocumentProvider= null;
}
if (fJavaTextTools != null) {
fJavaTextTools.dispose();
fJavaTextTools= null;
}
JavaDocLocations.shutdownJavadocLocations();
JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
}
private IWorkbenchPage internalGetActivePage() {
IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow();
if (window == null)
return null;
return getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
public synchronized CompilationUnitDocumentProvider getCompilationUnitDocumentProvider() {
if (fCompilationUnitDocumentProvider == null)
fCompilationUnitDocumentProvider= new CompilationUnitDocumentProvider();
return fCompilationUnitDocumentProvider;
}
public synchronized ClassFileDocumentProvider getClassFileDocumentProvider() {
if (fClassFileDocumentProvider == null)
fClassFileDocumentProvider= new ClassFileDocumentProvider();
return fClassFileDocumentProvider;
}
public synchronized IWorkingCopyManager getWorkingCopyManager() {
return getCompilationUnitDocumentProvider();
}
public synchronized ProblemMarkerManager getProblemMarkerManager() {
if (fProblemMarkerManager == null)
fProblemMarkerManager= new ProblemMarkerManager();
return fProblemMarkerManager;
}
public synchronized JavaTextTools getJavaTextTools() {
if (fJavaTextTools == null)
fJavaTextTools= new JavaTextTools(getPreferenceStore(), JavaCore.getPlugin().getPluginPreferences());
return fJavaTextTools;
}
public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() {
if (fMembersOrderPreferenceCache == null)
fMembersOrderPreferenceCache= new MembersOrderPreferenceCache();
return fMembersOrderPreferenceCache;
}
/**
* Returns all Java editor text hovers contributed to the workbench.
*
* @return an array of JavaEditorTextHoverDescriptor
* @since 2.1
*/
public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() {
if (fJavaEditorTextHoverDescriptors == null)
fJavaEditorTextHoverDescriptors= JavaEditorTextHoverDescriptor.getContributedHovers();
return fJavaEditorTextHoverDescriptors;
}
/**
* Resets the Java editor text hovers contributed to the workbench.
* <p>
* This will force a rebuild of the descriptors the next time
* a client asks for them.
* </p>
*
* @return an array of JavaEditorTextHoverDescriptor
* @since 2.1
*/
public void resetJavaEditorTextHoverDescriptors() {
fJavaEditorTextHoverDescriptors= null;
}
/**
* Creates the Java plugin standard groups in a context menu.
*/
public static void createStandardGroups(IMenuManager menu) {
if (!menu.isEmpty())
return;
menu.add(new Separator(IContextMenuConstants.GROUP_NEW));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO));
menu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW));
menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE));
menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
menu.add(new Separator(IContextMenuConstants.GROUP_BUILD));
menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP));
menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES));
}
/**
* @see AbstractUIPlugin#initializeDefaultPreferences
*/
protected void initializeDefaultPreferences(IPreferenceStore store) {
super.initializeDefaultPreferences(store);
PreferenceConstants.initializeDefaultValues(store);
}
private synchronized ImageDescriptorRegistry internalGetImageDescriptorRegistry() {
if (fImageDescriptorRegistry == null)
fImageDescriptorRegistry= new ImageDescriptorRegistry();
return fImageDescriptorRegistry;
}
private void registerAdapters() {
fJavaElementAdapterFactory= new JavaElementAdapterFactory();
fMarkerAdapterFactory= new MarkerAdapterFactory();
fEditorInputAdapterFactory= new EditorInputAdapterFactory();
fResourceAdapterFactory= new ResourceAdapterFactory();
IAdapterManager manager= Platform.getAdapterManager();
manager.registerAdapters(fJavaElementAdapterFactory, IJavaElement.class);
manager.registerAdapters(fMarkerAdapterFactory, IMarker.class);
manager.registerAdapters(fEditorInputAdapterFactory, IEditorInput.class);
manager.registerAdapters(fResourceAdapterFactory, IResource.class);
}
private void unregisterAdapters() {
IAdapterManager manager= Platform.getAdapterManager();
manager.unregisterAdapters(fJavaElementAdapterFactory);
manager.unregisterAdapters(fMarkerAdapterFactory);
manager.unregisterAdapters(fEditorInputAdapterFactory);
manager.unregisterAdapters(fResourceAdapterFactory);
}
}
|
28,479 |
Bug 28479 logical packages not recognized as Java by Search [browsing]
|
1) Select a logical package 2) open the search dialog ->it defaults to the File search, I would have expected that it defaults to the Java search
|
verified fixed
|
ec7b2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T11:40:21Z | 2002-12-17T10:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/LogicalPackageAdapterFactory.java
| |
28,479 |
Bug 28479 logical packages not recognized as Java by Search [browsing]
|
1) Select a logical package 2) open the search dialog ->it defaults to the File search, I would have expected that it defaults to the Java search
|
verified fixed
|
ec7b2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T11:40:21Z | 2002-12-17T10:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/LogicalPackage.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.browsing;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
/**
* Contains a list of package fragments with the same name
* but residing in different source folders of a unique Java project.
*/
public class LogicalPackage {
private Set fPackages;
private String fName;
private IJavaProject fJavaProject;
public LogicalPackage(IPackageFragment fragment){
Assert.isNotNull(fragment);
fPackages= new HashSet();
fJavaProject= fragment.getJavaProject();
Assert.isNotNull(fJavaProject);
add(fragment);
fName= fragment.getElementName();
}
public IJavaProject getJavaProject(){
return fJavaProject;
}
public IPackageFragment[] getFragments(){
return (IPackageFragment[]) fPackages.toArray(new IPackageFragment[fPackages.size()]);
}
public void add(IPackageFragment fragment){
Assert.isTrue(fragment != null && fJavaProject.equals(fragment.getJavaProject()));
fPackages.add(fragment);
}
public void remove(IPackageFragment fragment){
fPackages.remove(fragment);
}
public boolean contains(IPackageFragment fragment){
return fPackages.contains(fragment);
}
public String getElementName(){
return fName;
}
public int size(){
return fPackages.size();
}
/**
* Returns true if the given fragment has the same name and
* resides inside the same project as the other fragments in
* the LogicalPackage.
*
* @param fragment
* @return boolean
*/
public boolean belongs(IPackageFragment fragment) {
if(fragment==null)
return false;
if(fJavaProject.equals(fragment.getJavaProject())){
return fName.equals(fragment.getElementName());
}
return false;
}
public boolean equals(Object o){
if (!(o instanceof LogicalPackage))
return false;
LogicalPackage lp= (LogicalPackage)o;
if (!fJavaProject.equals(lp.getJavaProject()))
return false;
IPackageFragment[] fragments= lp.getFragments();
if (fragments.length != getFragments().length)
return false;
//this works because a LogicalPackage cannot contain the same IPackageFragment twice
for (int i= 0; i < fragments.length; i++) {
IPackageFragment fragment= fragments[i];
if(!fPackages.contains(fragment))
return false;
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
IPackageFragment[] fragments= getFragments();
return fJavaProject.hashCode() + getHash(fragments, fragments.length-1);
}
private int getHash(IPackageFragment[] fragments, int index) {
if (index <= 0)
return fragments[0].hashCode() * 17;
else return fragments[index].hashCode() * 17 + getHash(fragments, index-1);
}
}
|
28,479 |
Bug 28479 logical packages not recognized as Java by Search [browsing]
|
1) Select a logical package 2) open the search dialog ->it defaults to the File search, I would have expected that it defaults to the Java search
|
verified fixed
|
ec7b2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T11:40:21Z | 2002-12-17T10:13:20Z |
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.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 static class SearchPatternData {
int searchFor;
int limitTo;
String pattern;
boolean isCaseSensitive;
IJavaElement javaElement;
int scope;
IWorkingSet[] workingSets;
public SearchPatternData(int s, int l, boolean i, String p, IJavaElement element) {
this(s, l, p, i, element, ISearchPageContainer.WORKSPACE_SCOPE, null);
}
public SearchPatternData(int s, int l, String p, boolean i, IJavaElement element, int scope, IWorkingSet[] workingSets) {
searchFor= s;
limitTo= l;
pattern= p;
isCaseSensitive= i;
javaElement= element;
this.scope= scope;
this.workingSets= workingSets;
}
}
//---- Action Handling ------------------------------------------------
public boolean performAction() {
SearchUI.activateSearchResultView();
SearchPatternData data= getPatternData();
IWorkspace workspace= JavaPlugin.getWorkspace();
// Setup search scope
IJavaSearchScope scope= null;
String scopeDescription= ""; //$NON-NLS-1$
switch (getContainer().getSelectedScope()) {
case ISearchPageContainer.WORKSPACE_SCOPE:
scopeDescription= SearchMessages.getString("WorkspaceScope"); //$NON-NLS-1$
scope= SearchEngine.createWorkspaceScope();
break;
case ISearchPageContainer.SELECTION_SCOPE:
scopeDescription= SearchMessages.getString("SelectionScope"); //$NON-NLS-1$
scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(fStructuredSelection);
break;
case ISearchPageContainer.WORKING_SET_SCOPE:
IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets();
// should not happen - just to be sure
if (workingSets == null || workingSets.length < 1)
return false;
scopeDescription= SearchMessages.getFormattedString("WorkingSetScope", SearchUtil.toString(workingSets)); //$NON-NLS-1$
scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getContainer().getSelectedWorkingSets());
SearchUtil.updateLRUWorkingSets(getContainer().getSelectedWorkingSets());
}
JavaSearchResultCollector collector= new JavaSearchResultCollector();
JavaSearchOperation op= null;
if (data.javaElement != null && getPattern().equals(fInitialData.pattern)) {
op= new JavaSearchOperation(workspace, data.javaElement, data.limitTo, scope, scopeDescription, collector);
if (data.limitTo == IJavaSearchConstants.REFERENCES)
SearchUtil.warnIfBinaryConstant(data.javaElement, getShell());
} else {
data.javaElement= null;
op= new JavaSearchOperation(workspace, data.pattern, data.isCaseSensitive, data.searchFor, data.limitTo, scope, scopeDescription, collector);
}
Shell shell= getControl().getShell();
try {
getContainer().getRunnableContext().run(true, true, op);
} catch (InvocationTargetException ex) {
ExceptionHandler.handle(ex, shell, SearchMessages.getString("Search.Error.search.title"), SearchMessages.getString("Search.Error.search.message")); //$NON-NLS-2$ //$NON-NLS-1$
return false;
} catch (InterruptedException ex) {
return false;
}
return true;
}
private int getLimitTo() {
for (int i= 0; i < fLimitTo.length; i++) {
if (fLimitTo[i].getSelection())
return i;
}
return -1;
}
private void setLimitTo(int searchFor) {
fLimitTo[DECLARATIONS].setEnabled(true);
fLimitTo[IMPLEMENTORS].setEnabled(false);
fLimitTo[REFERENCES].setEnabled(true);
fLimitTo[ALL_OCCURRENCES].setEnabled(true);
fLimitTo[READ_ACCESSES].setEnabled(false);
fLimitTo[WRITE_ACCESSES].setEnabled(false);
if (!(searchFor == TYPE || searchFor == INTERFACE) && fLimitTo[IMPLEMENTORS].getSelection()) {
fLimitTo[IMPLEMENTORS].setSelection(false);
fLimitTo[REFERENCES].setSelection(true);
}
if (!(searchFor == FIELD) && (getLimitTo() == READ_ACCESSES || getLimitTo() == WRITE_ACCESSES)) {
fLimitTo[getLimitTo()].setSelection(false);
fLimitTo[REFERENCES].setSelection(true);
}
switch (searchFor) {
case TYPE:
case INTERFACE:
fLimitTo[IMPLEMENTORS].setEnabled(true);
break;
case FIELD:
fLimitTo[READ_ACCESSES].setEnabled(true);
fLimitTo[WRITE_ACCESSES].setEnabled(true);
break;
default :
break;
}
}
private String[] getPreviousSearchPatterns() {
// Search results are not persistent
int patternCount= fgPreviousSearchPatterns.size();
String [] patterns= new String[patternCount];
for (int i= 0; i < patternCount; i++)
patterns[i]= ((SearchPatternData) fgPreviousSearchPatterns.get(patternCount - 1 - i)).pattern;
return patterns;
}
private int getSearchFor() {
for (int i= 0; i < fSearchFor.length; i++) {
if (fSearchFor[i].getSelection())
return i;
}
Assert.isTrue(false, "shouldNeverHappen"); //$NON-NLS-1$
return -1;
}
private String getPattern() {
return fPattern.getText();
}
/**
* Return search pattern data and update previous searches.
* An existing entry will be updated.
*/
private SearchPatternData getPatternData() {
String pattern= getPattern();
SearchPatternData match= null;
int i= 0;
int size= fgPreviousSearchPatterns.size();
while (match == null && i < size) {
match= (SearchPatternData) fgPreviousSearchPatterns.get(i);
i++;
if (!pattern.equals(match.pattern))
match= null;
};
if (match == null) {
match= new SearchPatternData(
getSearchFor(),
getLimitTo(),
pattern,
fCaseSensitive.getSelection(),
fJavaElement,
getContainer().getSelectedScope(),
getContainer().getSelectedWorkingSets());
fgPreviousSearchPatterns.add(match);
}
else {
match.searchFor= getSearchFor();
match.limitTo= getLimitTo();
match.isCaseSensitive= fCaseSensitive.getSelection();
match.javaElement= fJavaElement;
match.scope= getContainer().getSelectedScope();
match.workingSets= getContainer().getSelectedWorkingSets();
};
return match;
}
/*
* Implements method from IDialogPage
*/
public void setVisible(boolean visible) {
if (visible && fPattern != null) {
if (fFirstTime) {
fFirstTime= false;
// Set item and text here to prevent page from resizing
fPattern.setItems(getPreviousSearchPatterns());
initSelections();
}
fPattern.setFocus();
getContainer().setPerformActionEnabled(fPattern.getText().length() > 0);
}
super.setVisible(visible);
}
public boolean isValid() {
return true;
}
//---- Widget creation ------------------------------------------------
/**
* Creates the page's content.
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
readConfiguration();
GridData gd;
Composite result= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout(2, false);
layout.horizontalSpacing= 10;
result.setLayout(layout);
result.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
RowLayouter layouter= new RowLayouter(layout.numColumns);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.verticalAlignment= GridData.VERTICAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_FILL;
layouter.setDefaultGridData(gd, 0);
layouter.setDefaultGridData(gd, 1);
layouter.setDefaultSpan();
layouter.perform(createExpression(result));
layouter.perform(createSearchFor(result), createLimitTo(result), -1);
SelectionAdapter javaElementInitializer= new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
if (getSearchFor() == fInitialData.searchFor)
fJavaElement= fInitialData.javaElement;
else
fJavaElement= null;
setLimitTo(getSearchFor());
updateCaseSensitiveCheckbox();
}
};
fSearchFor[TYPE].addSelectionListener(javaElementInitializer);
fSearchFor[METHOD].addSelectionListener(javaElementInitializer);
fSearchFor[FIELD].addSelectionListener(javaElementInitializer);
fSearchFor[CONSTRUCTOR].addSelectionListener(javaElementInitializer);
fSearchFor[PACKAGE].addSelectionListener(javaElementInitializer);
setControl(result);
WorkbenchHelp.setHelp(result, IJavaHelpContextIds.JAVA_SEARCH_PAGE);
}
private Control createExpression(Composite parent) {
Composite result= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout(2, false);
result.setLayout(layout);
GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan= 2;
gd.horizontalIndent= 0;
result.setLayoutData(gd);
// Pattern text + info
Label label= new Label(result, SWT.LEFT);
label.setText(SearchMessages.getString("SearchPage.expression.label")); //$NON-NLS-1$
gd= new GridData(GridData.BEGINNING);
gd.horizontalSpan= 2;
// gd.horizontalIndent= -gd.horizontalIndent;
label.setLayoutData(gd);
// Pattern combo
fPattern= new Combo(result, SWT.SINGLE | SWT.BORDER);
fPattern.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handlePatternSelected();
}
});
fPattern.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
getContainer().setPerformActionEnabled(getPattern().length() > 0);
updateCaseSensitiveCheckbox();
}
});
gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
gd.horizontalIndent= -gd.horizontalIndent;
fPattern.setLayoutData(gd);
// Ignore case checkbox
fCaseSensitive= new Button(result, SWT.CHECK);
fCaseSensitive.setText(SearchMessages.getString("SearchPage.expression.caseSensitive")); //$NON-NLS-1$
gd= new GridData();
fCaseSensitive.setLayoutData(gd);
fCaseSensitive.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fIsCaseSensitive= fCaseSensitive.getSelection();
writeConfiguration();
}
});
return result;
}
private void updateCaseSensitiveCheckbox() {
if (fInitialData != null && getPattern().equals(fInitialData.pattern) && fJavaElement != null) {
fCaseSensitive.setEnabled(false);
fCaseSensitive.setSelection(true);
}
else {
fCaseSensitive.setEnabled(true);
fCaseSensitive.setSelection(fIsCaseSensitive);
}
}
private void handlePatternSelected() {
if (fPattern.getSelectionIndex() < 0)
return;
int index= fgPreviousSearchPatterns.size() - 1 - fPattern.getSelectionIndex();
fInitialData= (SearchPatternData) fgPreviousSearchPatterns.get(index);
for (int i= 0; i < fSearchFor.length; i++)
fSearchFor[i].setSelection(false);
for (int i= 0; i < fLimitTo.length; i++)
fLimitTo[i].setSelection(false);
fSearchFor[fInitialData.searchFor].setSelection(true);
setLimitTo(fInitialData.searchFor);
fLimitTo[fInitialData.limitTo].setSelection(true);
fPattern.setText(fInitialData.pattern);
fIsCaseSensitive= fInitialData.isCaseSensitive;
fJavaElement= fInitialData.javaElement;
fCaseSensitive.setEnabled(fJavaElement == null);
fCaseSensitive.setSelection(fInitialData.isCaseSensitive);
if (fInitialData.workingSets != null)
getContainer().setSelectedWorkingSets(fInitialData.workingSets);
else
getContainer().setSelectedScope(fInitialData.scope);
}
private Control createSearchFor(Composite parent) {
Group result= new Group(parent, SWT.NONE);
result.setText(SearchMessages.getString("SearchPage.searchFor.label")); //$NON-NLS-1$
GridLayout layout= new GridLayout();
layout.numColumns= 3;
result.setLayout(layout);
fSearchFor= new Button[fSearchForText.length];
for (int i= 0; i < fSearchForText.length; i++) {
Button button= new Button(result, SWT.RADIO);
button.setText(fSearchForText[i]);
fSearchFor[i]= button;
}
// Fill with dummy radio buttons
Button filler= new Button(result, SWT.RADIO);
filler.setVisible(false);
filler= new Button(result, SWT.RADIO);
filler.setVisible(false);
return result;
}
private Control createLimitTo(Composite parent) {
Group result= new Group(parent, SWT.NONE);
result.setText(SearchMessages.getString("SearchPage.limitTo.label")); //$NON-NLS-1$
GridLayout layout= new GridLayout();
layout.numColumns= 2;
result.setLayout(layout);
fLimitTo= new Button[fLimitToText.length];
for (int i= 0; i < fLimitToText.length; i++) {
Button button= new Button(result, SWT.RADIO);
button.setText(fLimitToText[i]);
fLimitTo[i]= button;
}
return result;
}
private void initSelections() {
fStructuredSelection= asStructuredSelection();
fInitialData= tryStructuredSelection(fStructuredSelection);
if (fInitialData == null)
fInitialData= trySimpleTextSelection(getContainer().getSelection());
if (fInitialData == null)
fInitialData= getDefaultInitValues();
fJavaElement= fInitialData.javaElement;
fCaseSensitive.setSelection(fInitialData.isCaseSensitive);
fCaseSensitive.setEnabled(fInitialData.javaElement == null);
fSearchFor[fInitialData.searchFor].setSelection(true);
setLimitTo(fInitialData.searchFor);
fLimitTo[fInitialData.limitTo].setSelection(true);
fPattern.setText(fInitialData.pattern);
}
private SearchPatternData tryStructuredSelection(IStructuredSelection selection) {
if (selection == null || selection.size() > 1)
return null;
Object o= selection.getFirstElement();
if (o instanceof IJavaElement) {
return determineInitValuesFrom((IJavaElement)o);
} else if (o instanceof ISearchResultViewEntry) {
IJavaElement element= SearchUtil.getJavaElement(((ISearchResultViewEntry)o).getSelectedMarker());
return determineInitValuesFrom(element);
} else if (o instanceof IAdaptable) {
IJavaElement element= (IJavaElement)((IAdaptable)o).getAdapter(IJavaElement.class);
if (element != null) {
return determineInitValuesFrom(element);
} else {
IWorkbenchAdapter adapter= (IWorkbenchAdapter)((IAdaptable)o).getAdapter(IWorkbenchAdapter.class);
if (adapter != null)
return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, adapter.getLabel(o), null);
}
}
return null;
}
private 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, true, pattern, element);
return null;
}
private SearchPatternData trySimpleTextSelection(ISelection selection) {
SearchPatternData result= null;
if (selection instanceof ITextSelection) {
BufferedReader reader= new BufferedReader(new StringReader(((ITextSelection)selection).getText()));
String text;
try {
text= reader.readLine();
if (text == null)
text= ""; //$NON-NLS-1$
} catch (IOException ex) {
text= ""; //$NON-NLS-1$
}
result= new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, text, null);
}
return result;
}
private SearchPatternData getDefaultInitValues() {
return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, "", null); //$NON-NLS-1$
}
/*
* Implements method from ISearchPage
*/
public void setContainer(ISearchPageContainer container) {
fContainer= container;
}
/**
* Returns the search page's container.
*/
private ISearchPageContainer getContainer() {
return fContainer;
}
/**
* Returns the structured selection from the selection.
*/
private IStructuredSelection asStructuredSelection() {
IWorkbenchWindow wbWindow= PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (wbWindow != null) {
IWorkbenchPage page= wbWindow.getActivePage();
if (page != null) {
IWorkbenchPart part= page.getActivePart();
if (part != null)
try {
return SelectionConverter.getStructuredSelection(part);
} catch (JavaModelException ex) {
}
}
}
return StructuredSelection.EMPTY;
}
//--------------- Configuration handling --------------
/**
* Returns the page settings for this Java search page.
*
* @return the page settings to be used
*/
private IDialogSettings getDialogSettings() {
IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings();
fDialogSettings= settings.getSection(PAGE_NAME);
if (fDialogSettings == null)
fDialogSettings= settings.addNewSection(PAGE_NAME);
return fDialogSettings;
}
/**
* Initializes itself from the stored page settings.
*/
private void readConfiguration() {
IDialogSettings s= getDialogSettings();
fIsCaseSensitive= s.getBoolean(STORE_CASE_SENSITIVE);
}
/**
* Stores it current configuration in the dialog store.
*/
private void writeConfiguration() {
IDialogSettings s= getDialogSettings();
s.put(STORE_CASE_SENSITIVE, fIsCaseSensitive);
}
}
|
28,479 |
Bug 28479 logical packages not recognized as Java by Search [browsing]
|
1) Select a logical package 2) open the search dialog ->it defaults to the File search, I would have expected that it defaults to the Java search
|
verified fixed
|
ec7b2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T11:40:21Z | 2002-12-17T10:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchPageScoreComputer.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.search;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.search.ui.ISearchPageScoreComputer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class JavaSearchPageScoreComputer implements ISearchPageScoreComputer {
public int computeScore(String id, Object element) {
if (!JavaSearchPage.EXTENSION_POINT_ID.equals(id))
// Can't decide
return ISearchPageScoreComputer.UNKNOWN;
if (element instanceof IJavaElement || element instanceof IClassFileEditorInput)
return 90;
if (element instanceof IMarker) {
Object handleId= null;
try {
handleId= ((IMarker)element).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$
// handleId is null
}
if (handleId != null)
return 90;
}
return ISearchPageScoreComputer.LOWEST;
}
}
|
28,479 |
Bug 28479 logical packages not recognized as Java by Search [browsing]
|
1) Select a logical package 2) open the search dialog ->it defaults to the File search, I would have expected that it defaults to the Java search
|
verified fixed
|
ec7b2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T11:40:21Z | 2002-12-17T10:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchScopeFactory.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.search;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.IWorkingSetSelectionDialog;
import org.eclipse.search.ui.ISearchResultViewEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.ui.JavaPlugin;
public class JavaSearchScopeFactory {
private static JavaSearchScopeFactory fgInstance;
private static IJavaSearchScope EMPTY_SCOPE= SearchEngine.createJavaSearchScope(new IJavaElement[] {});
private JavaSearchScopeFactory() {
}
public static JavaSearchScopeFactory getInstance() {
if (fgInstance == null)
fgInstance= new JavaSearchScopeFactory();
return fgInstance;
}
public IWorkingSet[] queryWorkingSets() throws JavaModelException {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
if (shell == null)
return null;
IWorkingSetSelectionDialog dialog= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSetSelectionDialog(shell, true);
if (dialog.open() == Window.OK) {
IWorkingSet[] workingSets= dialog.getSelection();
if (workingSets.length > 0)
return workingSets;
}
return null;
}
public IJavaSearchScope createJavaSearchScope(IWorkingSet[] workingSets) {
if (workingSets == null || workingSets.length < 1)
return EMPTY_SCOPE;
Set javaElements= new HashSet(workingSets.length * 10);
for (int i= 0; i < workingSets.length; i++)
addJavaElements(javaElements, workingSets[i]);
return createJavaSearchScope(javaElements);
}
public IJavaSearchScope createJavaSearchScope(IWorkingSet workingSet) {
Set javaElements= new HashSet(10);
addJavaElements(javaElements, workingSet);
return createJavaSearchScope(javaElements);
}
public IJavaSearchScope createJavaSearchScope(IResource[] resources) {
if (resources == null)
return EMPTY_SCOPE;
Set javaElements= new HashSet(resources.length);
addJavaElements(javaElements, resources);
return createJavaSearchScope(javaElements);
}
public IJavaSearchScope createJavaSearchScope(ISelection selection) {
if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
Iterator iter= ((IStructuredSelection)selection).iterator();
Set javaElements= new HashSet(((IStructuredSelection)selection).size());
while (iter.hasNext()) {
Object selectedElement= iter.next();
// Unpack search result view entry
if (selectedElement instanceof ISearchResultViewEntry)
selectedElement= ((ISearchResultViewEntry)selectedElement).getGroupByKey();
if (selectedElement instanceof IJavaElement)
addJavaElements(javaElements, (IJavaElement)selectedElement);
else if (selectedElement instanceof IResource)
addJavaElements(javaElements, (IResource)selectedElement);
else if (selectedElement instanceof IAdaptable) {
IResource resource= (IResource)((IAdaptable)selectedElement).getAdapter(IResource.class);
if (resource != null)
addJavaElements(javaElements, resource);
}
}
return createJavaSearchScope(javaElements);
}
return EMPTY_SCOPE;
}
private IJavaSearchScope createJavaSearchScope(Set javaElements) {
return SearchEngine.createJavaSearchScope((IJavaElement[])javaElements.toArray(new IJavaElement[javaElements.size()]));
}
private void addJavaElements(Set javaElements, IResource[] resources) {
for (int i= 0; i < resources.length; i++)
addJavaElements(javaElements, resources[i]);
}
private void addJavaElements(Set javaElements, IAdaptable resource) {
IJavaElement javaElement= (IJavaElement)resource.getAdapter(IJavaElement.class);
if (javaElement == null)
// not a Java resource
return;
if (javaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
// add other possible package fragments
try {
addJavaElements(javaElements, ((IFolder)resource).members());
} catch (CoreException ex) {
// don't add elements
}
}
addJavaElements(javaElements, javaElement);
}
private void addJavaElements(Set javaElements, IJavaElement javaElement) {
switch (javaElement.getElementType()) {
case IJavaElement.JAVA_PROJECT:
addJavaElements(javaElements, (IJavaProject)javaElement);
break;
default:
javaElements.add(javaElement);
}
}
private void addJavaElements(Set javaElements, IJavaProject javaProject) {
IPackageFragmentRoot[] roots;
try {
roots= javaProject.getPackageFragmentRoots();
} catch (JavaModelException ex) {
return;
}
for (int i= 0; i < roots.length; i++)
if (!roots[i].isExternal())
javaElements.add(roots[i]);
}
private void addJavaElements(Set javaElements, IWorkingSet workingSet) {
if (workingSet == null)
return;
IAdaptable[] elements= workingSet.getElements();
for (int i= 0; i < elements.length; i++) {
if (elements[i] instanceof IJavaElement)
addJavaElements(javaElements, (IJavaElement)elements[i]);
else
addJavaElements(javaElements, elements[i]);
}
}
}
|
31,374 |
Bug 31374 Package Explorer does not show children of linked directories
| null |
resolved fixed
|
ab92f6e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T12:05:03Z | 2003-02-07T20:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/StandardJavaElementContentProvider.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui;
import java.util.ArrayList;
import java.util.List;
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.runtime.CoreException;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
/**
* A base content provider for Java elements. It provides access to the
* Java element hierarchy without listening to changes in the Java model.
* If updating the presentation on Java model change is required than
* clients have to subclass, listen to Java model changes and have to update
* the UI using corresponding methods provided by the JFace viewers or their
* own UI presentation.
* <p>
* The following Java element hierarchy is surfaced by this content provider:
* <p>
* <pre>
Java model (<code>IJavaModel</code>)
Java project (<code>IJavaProject</code>)
package fragment root (<code>IPackageFragmentRoot</code>)
package fragment (<code>IPackageFragment</code>)
compilation unit (<code>ICompilationUnit</code>)
binary class file (<code>IClassFile</code>)
* </pre>
* </p>
* <p>
* Note that when the entire Java project is declared to be package fragment root,
* the corresponding package fragment root element that normally appears between the
* Java project and the package fragments is automatically filtered out.
* </p>
* This content provider can optionally return working copy elements for members
* below compilation units. If enabled, working copy members are returned for those
* compilation units in the Java element hierarchy for which a shared working copy exists
* in JDT core.
*
* @see org.eclipse.jdt.ui.IWorkingCopyProvider
* @see JavaCore#getSharedWorkingCopies(org.eclipse.jdt.core.IBufferFactory)
*
* @since 2.0
*/
public class StandardJavaElementContentProvider implements ITreeContentProvider, IWorkingCopyProvider {
protected static final Object[] NO_CHILDREN= new Object[0];
protected boolean fProvideMembers= false;
protected boolean fProvideWorkingCopy= false;
/**
* Creates a new content provider. The content provider does not
* provide members of compilation units or class files and it does
* not provide working copy elements.
*/
public StandardJavaElementContentProvider() {
}
/**
* Creates a new <code>StandardJavaElementContentProvider</code>.
*
* @param provideMembers if <code>true</code> members below compilation units
* and class files are provided.
* @param provideWorkingCopy if <code>true</code> the element provider provides
* working copies members of compilation units which have an associated working
* copy in JDT core. Otherwise only original elements are provided.
*/
public StandardJavaElementContentProvider(boolean provideMembers, boolean provideWorkingCopy) {
fProvideMembers= provideMembers;
fProvideWorkingCopy= provideWorkingCopy;
}
/**
* Returns whether members are provided when asking
* for a compilation units or class file for its children.
*
* @return <code>true</code> if the content provider provides members;
* otherwise <code>false</code> is returned
*/
public boolean getProvideMembers() {
return fProvideMembers;
}
/**
* Sets whether the content provider is supposed to return members
* when asking a compilation unit or class file for its children.
*
* @param b if <code>true</code> then members are provided.
* If <code>false</code> compilation units and class files are the
* leaves provided by this content provider.
*/
public void setProvideMembers(boolean b) {
fProvideMembers= b;
}
/**
* Returns whether the provided members are from a working
* copy or the original compilation unit.
*
* @return <code>true</code> if the content provider provides
* working copy members; otherwise <code>false</code> is
* returned
*
* @see #setProvideWorkingCopy(boolean)
*/
public boolean getProvideWorkingCopy() {
return fProvideWorkingCopy;
}
/**
* Sets whether the members are provided from a shared working copy
* that exists for a original compilation unit in the Java element hierarchy.
*
* @param b if <code>true</code> members are provided from a
* working copy if one exists in JDT core. If <code>false</code> the
* provider always returns original elements.
*/
public void setProvideWorkingCopy(boolean b) {
fProvideWorkingCopy= b;
}
/* (non-Javadoc)
* @see IWorkingCopyProvider#providesWorkingCopies()
*/
public boolean providesWorkingCopies() {
return fProvideWorkingCopy;
}
/* (non-Javadoc)
* Method declared on IStructuredContentProvider.
*/
public Object[] getElements(Object parent) {
return getChildren(parent);
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void dispose() {
}
/* (non-Javadoc)
* Method declared on ITreeContentProvider.
*/
public Object[] getChildren(Object element) {
if (!exists(element))
return NO_CHILDREN;
try {
if (element instanceof IJavaModel)
return getJavaProjects((IJavaModel)element);
if (element instanceof IJavaProject)
return getPackageFragmentRoots((IJavaProject)element);
if (element instanceof IPackageFragmentRoot)
return getPackageFragments((IPackageFragmentRoot)element);
if (element instanceof IPackageFragment)
return getPackageContents((IPackageFragment)element);
if (element instanceof IFolder)
return getResources((IFolder)element);
if (fProvideMembers && element instanceof ISourceReference && element instanceof IParent) {
if (fProvideWorkingCopy && element instanceof ICompilationUnit) {
element= JavaModelUtil.toWorkingCopy((ICompilationUnit) element);
}
return ((IParent)element).getChildren();
}
} catch (JavaModelException e) {
return NO_CHILDREN;
}
return NO_CHILDREN;
}
/* (non-Javadoc)
* @see ITreeContentProvider
*/
public boolean hasChildren(Object element) {
if (fProvideMembers) {
// assume CUs and class files are never empty
if (element instanceof ICompilationUnit ||
element instanceof IClassFile) {
return true;
}
} else {
// don't allow to drill down into a compilation unit or class file
if (element instanceof ICompilationUnit ||
element instanceof IClassFile ||
element instanceof IFile)
return false;
}
if (element instanceof IJavaProject) {
IJavaProject jp= (IJavaProject)element;
if (!jp.getProject().isOpen()) {
return false;
}
}
if (element instanceof IParent) {
try {
// when we have Java children return true, else we fetch all the children
if (((IParent)element).hasChildren())
return true;
} catch(JavaModelException e) {
return true;
}
}
Object[] children= getChildren(element);
return (children != null) && children.length > 0;
}
/* (non-Javadoc)
* Method declared on ITreeContentProvider.
*/
public Object getParent(Object element) {
if (!exists(element))
return null;
return internalGetParent(element);
}
private Object[] getPackageFragments(IPackageFragmentRoot root) throws JavaModelException {
IJavaElement[] fragments= root.getChildren();
Object[] nonJavaResources= root.getNonJavaResources();
if (nonJavaResources == null)
return fragments;
return concatenate(fragments, nonJavaResources);
}
protected Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException {
if (!project.getProject().isOpen())
return NO_CHILDREN;
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
List list= new ArrayList(roots.length);
// filter out package fragments that correspond to projects and
// replace them with the package fragments directly
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= (IPackageFragmentRoot)roots[i];
if (isProjectPackageFragmentRoot(root)) {
Object[] children= root.getChildren();
for (int k= 0; k < children.length; k++)
list.add(children[k]);
}
else if (hasChildren(root)) {
list.add(root);
}
}
return concatenate(list.toArray(), project.getNonJavaResources());
}
protected Object[] getJavaProjects(IJavaModel jm) throws JavaModelException {
return jm.getJavaProjects();
}
private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException {
if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
return concatenate(fragment.getCompilationUnits(), fragment.getNonJavaResources());
}
return concatenate(fragment.getClassFiles(), fragment.getNonJavaResources());
}
private Object[] getResources(IFolder folder) {
try {
// filter out folders that are package fragment roots
Object[] members= folder.members();
List nonJavaResources= new ArrayList();
for (int i= 0; i < members.length; i++) {
Object o= members[i];
if (!(o instanceof IFolder && JavaCore.create((IFolder)o) != null)) {
nonJavaResources.add(o);
}
}
return nonJavaResources.toArray();
} catch(CoreException e) {
return NO_CHILDREN;
}
}
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
protected boolean isClassPathChange(IJavaElementDelta delta) {
int flags= delta.getFlags();
return (delta.getKind() == IJavaElementDelta.CHANGED &&
((flags & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0) ||
((flags & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) ||
((flags & IJavaElementDelta.F_CLASSPATH_REORDER) != 0));
}
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
protected Object skipProjectPackageFragmentRoot(IPackageFragmentRoot root) {
try {
if (isProjectPackageFragmentRoot(root))
return root.getParent();
return root;
} catch(JavaModelException e) {
return root;
}
}
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
protected boolean isPackageFragmentEmpty(IJavaElement element) throws JavaModelException {
if (element instanceof IPackageFragment) {
IPackageFragment fragment= (IPackageFragment)element;
if (!(fragment.hasChildren() || fragment.getNonJavaResources().length > 0) && fragment.hasSubpackages())
return true;
}
return false;
}
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
protected boolean isProjectPackageFragmentRoot(IPackageFragmentRoot root) throws JavaModelException {
IResource resource= root.getResource();
return (resource instanceof IProject);
}
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
protected boolean exists(Object element) {
if (element == null) {
return false;
}
if (element instanceof IResource) {
return ((IResource)element).exists();
}
if (element instanceof IJavaElement) {
return ((IJavaElement)element).exists();
}
return true;
}
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
protected Object internalGetParent(Object element) {
if (element instanceof IJavaProject) {
return ((IJavaProject)element).getJavaModel();
}
// try to map resources to the containing package fragment
if (element instanceof IResource) {
IResource parent= ((IResource)element).getParent();
Object jParent= JavaCore.create(parent);
if (jParent != null)
return jParent;
return parent;
}
// for package fragments that are contained in a project package fragment
// we have to skip the package fragment root as the parent.
if (element instanceof IPackageFragment) {
IPackageFragmentRoot parent= (IPackageFragmentRoot)((IPackageFragment)element).getParent();
return skipProjectPackageFragmentRoot(parent);
}
if (element instanceof IJavaElement) {
IJavaElement candidate= ((IJavaElement)element).getParent();
// If the parent is a CU we might have shown working copy elements below CU level. If so
// return the original element instead of the working copy.
if (candidate != null && candidate.getElementType() == IJavaElement.COMPILATION_UNIT) {
candidate= JavaModelUtil.toOriginal((ICompilationUnit) candidate);
}
return candidate;
}
return null;
}
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
protected static Object[] concatenate(Object[] a1, Object[] a2) {
int a1Len= a1.length;
int a2Len= a2.length;
Object[] res= new Object[a1Len + a2Len];
System.arraycopy(a1, 0, res, 0, a1Len);
System.arraycopy(a2, 0, res, a1Len, a2Len);
return res;
}
}
|
31,114 |
Bug 31114 Moving linked resource onto self deletes linked resource
|
build 20030206 -create a linked folder LA. -move the linked folder to its parent project. ->the linked folder is deleted and an error message appears. The move operation should no be possible.
|
verified fixed
|
e010840
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T12:06:48Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/core
| |
31,114 |
Bug 31114 Moving linked resource onto self deletes linked resource
|
build 20030206 -create a linked folder LA. -move the linked folder to its parent project. ->the linked folder is deleted and an error message appears. The move operation should no be possible.
|
verified fixed
|
e010840
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T12:06:48Z | 2003-02-06T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/ReorgRefactoring.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
cases/org/eclipse/jdt/ui/tests/refactoring/MultiMoveTests.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ReorgTests.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/core
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/CopyPackageFragmentRootChange.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/core
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/CopyResourceChange.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/core
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/MovePackageFragmentRootChange.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/core
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/MoveResourceChange.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/core
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/PackageFragmentRootReorgChange.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/core
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/ResourceReorgChange.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/core
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/CopyRefactoring.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/core
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/ICopyQueries.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/core
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/IDeepCopyQuery.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/core
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/MoveRefactoring.java
| |
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46: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.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
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.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.refactoring.reorg.CopyRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.IPackageFragmentRootManipulationQuery;
import org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.SourceReferenceUtil;
import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction;
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.refactoring.QualifiedNameComponent;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardPage;
import org.eclipse.jdt.internal.ui.reorg.ReorgQueries;
import org.eclipse.jdt.internal.ui.reorg.DeleteSourceReferencesAction;
import org.eclipse.jdt.internal.ui.reorg.JdtCopyAction;
import org.eclipse.jdt.internal.ui.reorg.JdtMoveAction;
import org.eclipse.jdt.internal.ui.reorg.MockWorkbenchSite;
import org.eclipse.jdt.internal.ui.reorg.ReorgActionFactory;
import org.eclipse.jdt.internal.ui.reorg.ReorgMessages;
import org.eclipse.jdt.internal.ui.reorg.SimpleSelectionProvider;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
public class SelectionTransferDropAdapter extends JdtViewerDropAdapter implements TransferDropTargetListener {
private List fElements;
private MoveRefactoring fMoveRefactoring;
private int fCanMoveElements;
private CopyRefactoring fCopyRefactoring;
private int fCanCopyElements;
private ISelection fSelection;
private AddMethodStubAction fAddMethodStubAction;
private static final int DROP_TIME_DIFF_TRESHOLD= 150;
public SelectionTransferDropAdapter(StructuredViewer viewer) {
super(viewer, DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND);
fAddMethodStubAction= new AddMethodStubAction();
}
//---- 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;
fSelection= null;
fMoveRefactoring= null;
fCanMoveElements= 0;
fCopyRefactoring= null;
fCanCopyElements= 0;
}
public void validateDrop(Object target, DropTargetEvent event, int operation) {
event.detail= DND.DROP_NONE;
if (tooFast(event))
return;
initializeSelection();
try {
if (operation == DND.DROP_DEFAULT) {
event.detail= handleValidateDefault(target, event);
} else if (operation == DND.DROP_COPY) {
event.detail= handleValidateCopy(target, event);
} else if (operation == DND.DROP_MOVE) {
event.detail= handleValidateMove(target, event);
} else if (operation == DND.DROP_LINK) {
event.detail= handleValidateLink(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;
}
}
protected void initializeSelection(){
if (fElements != null)
return;
ISelection s= LocalSelectionTransfer.getInstance().getSelection();
if (!(s instanceof IStructuredSelection))
return;
fSelection= s;
fElements= ((IStructuredSelection)s).toList();
}
protected ISelection getSelection(){
return fSelection;
}
private boolean tooFast(DropTargetEvent event) {
return Math.abs(LocalSelectionTransfer.getInstance().getSelectionSetTime() - event.time) < DROP_TIME_DIFF_TRESHOLD;
}
public void drop(Object target, DropTargetEvent event) {
try{
if (event.detail == DND.DROP_MOVE) {
handleDropMove(target, event);
if (! canPasteSourceReferences(target))
return;
DeleteSourceReferencesAction delete= ReorgActionFactory.createDeleteSourceReferencesAction(getDragableSourceReferences());
delete.setAskForDeleteConfirmation(true);
delete.setCanDeleteGetterSetter(false);
delete.update(delete.getSelection());
if (delete.isEnabled())
delete.run();
} else if (event.detail == DND.DROP_COPY) {
handleDropCopy(target, event);
} else if (event.detail == DND.DROP_LINK) {
handleDropLink(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 handleValidateDefault(Object target, DropTargetEvent event) throws JavaModelException{
if (target == null)
return DND.DROP_NONE;
if (canPasteSourceReferences(target))
return handleValidateCopy(target, event);
else
return handleValidateMove(target, event);
}
private int handleValidateMove(Object target, DropTargetEvent event) throws JavaModelException{
if (target == null)
return DND.DROP_NONE;
if (canPasteSourceReferences(target)){
if (canMoveSelectedSourceReferences(target))
return DND.DROP_MOVE;
else
return DND.DROP_NONE;
}
if (fMoveRefactoring == null){
IPackageFragmentRootManipulationQuery query= JdtMoveAction.createUpdateClasspathQuery(getViewer().getControl().getShell());
fMoveRefactoring= new MoveRefactoring(fElements, JavaPreferencesSettings.getCodeGenerationSettings(), query, new ReorgQueries());
}
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 handleDropLink(Object target, DropTargetEvent event) {
if (fAddMethodStubAction.init((IType)target, getSelection()))
fAddMethodStubAction.run();
}
private int handleValidateLink(Object target, DropTargetEvent event) {
if (target instanceof IType && AddMethodStubAction.canActionBeAdded((IType)target, getSelection()))
return DND.DROP_LINK;
else
return DND.DROP_NONE;
}
private void handleDropMove(final Object target, DropTargetEvent event) throws JavaModelException{
if (canPasteSourceReferences(target)){
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(pasteAction.getSelection());
if (!pasteAction.isEnabled()){
event.detail= DND.DROP_NONE;
return;
}
pasteAction.run();
return;
}
private int handleValidateCopy(Object target, DropTargetEvent event) throws JavaModelException{
if (canPasteSourceReferences(target))
return DND.DROP_COPY;
if (fCopyRefactoring == null){
IPackageFragmentRootManipulationQuery query= JdtCopyAction.createUpdateClasspathQuery(getViewer().getControl().getShell());
fCopyRefactoring= new CopyRefactoring(fElements, new ReorgQueries(), query);
}
if (!canCopyElements())
return DND.DROP_NONE;
if (fCopyRefactoring.isValidDestination(target))
return DND.DROP_COPY;
else
return DND.DROP_NONE;
}
private boolean canMoveSelectedSourceReferences(Object target) throws JavaModelException{
ICompilationUnit targetCu= getCompilationUnit(target);
if (targetCu == null)
return false;
ISourceReference[] elements= getDragableSourceReferences();
for (int i= 0; i < elements.length; i++) {
if (targetCu.equals(SourceReferenceUtil.getCompilationUnit(elements[i])))
return false;
}
return true;
}
private static ICompilationUnit getCompilationUnit(Object target){
if (target instanceof ISourceReference)
return SourceReferenceUtil.getCompilationUnit((ISourceReference)target);
else
return null;
}
private boolean canPasteSourceReferences(Object target) throws JavaModelException{
ISourceReference[] elements= getDragableSourceReferences();
if (elements.length != fElements.size())
return false;
SelectionDispatchAction pasteAction= ReorgActionFactory.createPasteAction(elements, target);
pasteAction.update(pasteAction.getSelection());
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)){
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 MockWorkbenchSite(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() && !ref.canUpdateQualifiedNames()) {
setShowPreview(false);
return true;
}
switch (showMoveDialog(ref)){
case IDialogConstants.CANCEL_ID:
setShowPreview(false);
return false;
case IDialogConstants.OK_ID:
setShowPreview(false);
return true;
case PREVIEW_ID:
setShowPreview(true);
return true;
default:
Assert.isTrue(false); //not expected to get here
return false;
}
}
private static int showMoveDialog(MoveRefactoring ref) {
Shell shell= JavaPlugin.getActiveWorkbenchShell().getShell();
final UpdateDialog dialog= new UpdateDialog(shell, ref);
shell.getDisplay().syncExec(new Runnable() {
public void run() {
dialog.open();
}
});
return dialog.getReturnCode();
}
private static class UpdateDialog extends Dialog {
private Button fPreview;
private MoveRefactoring fRefactoring;
private Button fReferenceCheckbox;
private Button fQualifiedNameCheckbox;
private QualifiedNameComponent fQualifiedNameComponent;
public UpdateDialog(Shell parentShell, MoveRefactoring refactoring) {
super(parentShell);
fRefactoring= refactoring;
}
protected void configureShell(Shell shell) {
shell.setText(PackagesMessages.getString("SelectionTransferDropAdapter.dialog.title")); //$NON-NLS-1$
super.configureShell(shell);
}
protected void createButtonsForButtonBar(Composite parent) {
fPreview= createButton(parent, PREVIEW_ID, ReorgMessages.getString("JdtMoveAction.preview"), false); //$NON-NLS-1$
super.createButtonsForButtonBar(parent);
}
protected void buttonPressed(int buttonId) {
if (buttonId == PREVIEW_ID) {
setReturnCode(PREVIEW_ID);
close();
} else {
super.buttonPressed(buttonId);
}
}
protected Control createDialogArea(Composite parent) {
Composite result= (Composite)super.createDialogArea(parent);
addUpdateReferenceComponent(result);
addUpdateQualifiedNameComponent(result, ((GridLayout)result.getLayout()).marginWidth);
return result;
}
private void updateButtons() {
Button okButton= getButton(IDialogConstants.OK_ID);
boolean okEnabled= true; // we keep this since the code got copied from JdtMoveAction.
okButton.setEnabled(okEnabled);
fReferenceCheckbox.setEnabled(okEnabled && canUpdateReferences());
fRefactoring.setUpdateReferences(fReferenceCheckbox.getEnabled() && fReferenceCheckbox.getSelection());
if (fQualifiedNameCheckbox != null) {
boolean enabled= okEnabled && fRefactoring.canEnableQualifiedNameUpdating();
fQualifiedNameCheckbox.setEnabled(enabled);
if (enabled) {
fQualifiedNameComponent.setEnabled(fRefactoring.getUpdateQualifiedNames());
if (fRefactoring.getUpdateQualifiedNames())
okButton.setEnabled(false);
} else {
fQualifiedNameComponent.setEnabled(false);
}
fRefactoring.setUpdateQualifiedNames(fQualifiedNameCheckbox.getEnabled() && fQualifiedNameCheckbox.getSelection());
}
boolean preview= okEnabled;
if (preview)
preview=
fRefactoring.getUpdateQualifiedNames() && fRefactoring.canEnableQualifiedNameUpdating() ||
fReferenceCheckbox.getSelection() && canUpdateReferences();
fPreview.setEnabled(preview);
}
private void addUpdateReferenceComponent(Composite result) {
fReferenceCheckbox= new Button(result, SWT.CHECK);
fReferenceCheckbox.setText(ReorgMessages.getString("JdtMoveAction.update_references")); //$NON-NLS-1$
fReferenceCheckbox.setSelection(fRefactoring.getUpdateReferences());
fReferenceCheckbox.setEnabled(canUpdateReferences());
fReferenceCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fRefactoring.setUpdateReferences(((Button)e.widget).getSelection());
updateButtons();
}
});
}
private boolean canUpdateReferences() {
try{
return fRefactoring.canUpdateReferences();
} catch (JavaModelException e){
return false;
}
}
private void addUpdateQualifiedNameComponent(Composite parent, int marginWidth) {
if (!fRefactoring.canUpdateQualifiedNames())
return;
fQualifiedNameCheckbox= new Button(parent, SWT.CHECK);
int indent= marginWidth + fQualifiedNameCheckbox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x;
fQualifiedNameCheckbox.setText(RefactoringMessages.getString("RenameInputWizardPage.update_qualified_names")); //$NON-NLS-1$
fQualifiedNameCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fQualifiedNameCheckbox.setSelection(fRefactoring.getUpdateQualifiedNames());
fQualifiedNameComponent= new QualifiedNameComponent(parent, SWT.NONE, fRefactoring, getRefactoringSettings());
fQualifiedNameComponent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridData gd= (GridData)fQualifiedNameComponent.getLayoutData();
gd.horizontalAlignment= GridData.FILL;
gd.horizontalIndent= indent;
fQualifiedNameComponent.setEnabled(false);
fQualifiedNameCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
boolean enabled= ((Button)e.widget).getSelection();
fQualifiedNameComponent.setEnabled(enabled);
fRefactoring.setUpdateQualifiedNames(enabled);
updateButtons();
}
});
}
protected IDialogSettings getRefactoringSettings() {
IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings();
if (settings == null)
return null;
IDialogSettings result= settings.getSection(RefactoringWizardPage.REFACTORING_SETTINGS);
if (result == null) {
result= new DialogSettings(RefactoringWizardPage.REFACTORING_SETTINGS);
settings.addSection(result);
}
return result;
}
}
}
}
|
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/JdtMoveAction.java
|
package org.eclipse.jdt.internal.ui.reorg;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.MoveProjectAction;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation;
import org.eclipse.jdt.internal.ui.refactoring.QualifiedNameComponent;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringSaveHelper;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardPage;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringErrorDialogUtil;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatus;
import org.eclipse.jdt.internal.corext.refactoring.reorg.IPackageFragmentRootManipulationQuery;
import org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils;
public class JdtMoveAction extends ReorgDestinationAction {
public static final int PREVIEW_ID= IDialogConstants.CLIENT_ID + 1;
private boolean fShowPreview= false;
public JdtMoveAction(IWorkbenchSite site) {
super(site);
setText(ReorgMessages.getString("moveAction.label"));//$NON-NLS-1$
}
public boolean canOperateOn(IStructuredSelection selection) {
if (selection.isEmpty())
return false;
if (ClipboardActionUtil.hasOnlyProjects(selection))
return selection.size() == 1;
else
return super.canOperateOn(selection);
}
protected void run(IStructuredSelection selection) {
if (ClipboardActionUtil.hasOnlyProjects(selection)){
moveProject(selection);
} else {
if (!needsSaving(selection)) {
super.run(selection);
} else {
RefactoringSaveHelper helper= new RefactoringSaveHelper();
try {
if (helper.saveEditors()) {
super.run(selection);
}
} finally {
helper.triggerBuild();
}
}
}
}
private boolean needsSaving(IStructuredSelection selection) {
for (Iterator iter= selection.iterator(); iter.hasNext();) {
Object element= (Object) iter.next();
if (element instanceof ICompilationUnit || element instanceof IType)
return true;
}
return false;
}
public static ElementTreeSelectionDialog makeDialog(Shell parent, MoveRefactoring refactoring) {
StandardJavaElementContentProvider cp= new StandardJavaElementContentProvider() {
public boolean hasChildren(Object element) {
// prevent the + from being shown in front of packages
return !(element instanceof IPackageFragment) && super.hasChildren(element);
}
};
MoveDestinationDialog dialog= new MoveDestinationDialog(
parent, new DestinationRenderer(JavaElementLabelProvider.SHOW_SMALL_ICONS),
cp, refactoring);
return dialog;
}
/* non java-doc
* see @ReorgDestinationAction#isOkToProceed
*/
String getActionName() {
return ReorgMessages.getString("moveAction.name"); //$NON-NLS-1$
}
/* non java-doc
* see @ReorgDestinationAction#getDestinationDialogMessage
*/
String getDestinationDialogMessage() {
return ReorgMessages.getString("moveAction.destination.label"); //$NON-NLS-1$
}
/* non java-doc
* see @ReorgDestinationAction#createRefactoring
*/
ReorgRefactoring createRefactoring(List elements){
IPackageFragmentRootManipulationQuery query= createUpdateClasspathQuery(getShell());
return new MoveRefactoring(elements, JavaPreferencesSettings.getCodeGenerationSettings(), query, new ReorgQueries());
}
ElementTreeSelectionDialog createDestinationSelectionDialog(Shell parent, ILabelProvider labelProvider, StandardJavaElementContentProvider cp, ReorgRefactoring refactoring){
return new MoveDestinationDialog(parent, labelProvider, cp, (MoveRefactoring)refactoring);
}
/* non java-doc
* see @ReorgDestinationAction#isOkToProceed
*/
protected boolean isOkToProceed(ReorgRefactoring refactoring) throws JavaModelException{
return isOkToMoveReadOnly(refactoring);
}
protected void setShowPreview(boolean showPreview) {
fShowPreview = showPreview;
}
private static boolean isOkToMoveReadOnly(ReorgRefactoring refactoring){
if (! hasReadOnlyElements(refactoring))
return true;
return MessageDialog.openQuestion(
JavaPlugin.getActiveWorkbenchShell(),
ReorgMessages.getString("moveAction.checkMove"), //$NON-NLS-1$
ReorgMessages.getString("moveAction.error.readOnly")); //$NON-NLS-1$
}
private static boolean hasReadOnlyElements(ReorgRefactoring refactoring){
for (Iterator iter= refactoring.getElementsToReorg().iterator(); iter.hasNext(); ){
if (ReorgUtils.shouldConfirmReadOnly(iter.next()))
return true;
}
return false;
}
protected Object openDialog(ElementTreeSelectionDialog dialog) {
Object result= super.openDialog(dialog);
if (dialog instanceof MoveDestinationDialog) {
fShowPreview= dialog.getReturnCode() == PREVIEW_ID;
} else {
fShowPreview= false;
}
return result;
}
/* non java-doc
* @see ReorgDestinationAction#doReorg(ReorgRefactoring)
*/
void doReorg(ReorgRefactoring refactoring) throws JavaModelException{
if (fShowPreview){
openWizard(getShell(), refactoring);
return;
}
CheckConditionsOperation runnable= new CheckConditionsOperation(refactoring, CheckConditionsOperation.PRECONDITIONS);
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(false, false, runnable);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), ReorgMessages.getString("JdtMoveAction.move"), ReorgMessages.getString("JdtMoveAction.exception")); //$NON-NLS-1$ //$NON-NLS-2$
return;
} catch (InterruptedException e) {
Assert.isTrue(false); //cannot happen - not cancelable
}
RefactoringStatus status= runnable.getStatus();
if (status == null)
return;
if (status.hasFatalError())
RefactoringErrorDialogUtil.open(ReorgMessages.getString("JdtMoveAction.move"), status);//$NON-NLS-1$
else
super.doReorg(refactoring);
}
public static void openWizard(Shell parent, ReorgRefactoring refactoring) {
//XX incorrect help
RefactoringWizard wizard= new RefactoringWizard(refactoring, ReorgMessages.getString("JdtMoveAction.move"), IJavaHelpContextIds.MOVE_CU_ERROR_WIZARD_PAGE); //$NON-NLS-1$
wizard.setChangeCreationCancelable(false);
new RefactoringWizardDialog(parent, wizard).open();
return;
}
private void moveProject(IStructuredSelection selection){
MoveProjectAction action= new MoveProjectAction(JavaPlugin.getActiveWorkbenchShell());
action.selectionChanged(selection);
action.run();
}
//--- static inner classes
private static class MoveDestinationDialog extends ElementTreeSelectionDialog {
private MoveRefactoring fRefactoring;
private Button fReferenceCheckbox;
private Button fQualifiedNameCheckbox;
private QualifiedNameComponent fQualifiedNameComponent;
private Button fPreview;
MoveDestinationDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, MoveRefactoring refactoring) {
super(parent, labelProvider, contentProvider);
fRefactoring= refactoring;
setDoubleClickSelects(false);
}
protected void updateOKStatus() {
super.updateOKStatus();
try{
Button okButton= getOkButton();
boolean okEnabled= okButton.getEnabled();
fRefactoring.setDestination(getFirstResult());
fReferenceCheckbox.setEnabled(okEnabled && canUpdateReferences());
fRefactoring.setUpdateReferences(fReferenceCheckbox.getEnabled() && fReferenceCheckbox.getSelection());
if (fQualifiedNameCheckbox != null) {
boolean enabled= okEnabled && fRefactoring.canEnableQualifiedNameUpdating();
fQualifiedNameCheckbox.setEnabled(enabled);
if (enabled) {
fQualifiedNameComponent.setEnabled(fRefactoring.getUpdateQualifiedNames());
if (fRefactoring.getUpdateQualifiedNames())
okButton.setEnabled(false);
} else {
fQualifiedNameComponent.setEnabled(false);
}
fRefactoring.setUpdateQualifiedNames(fQualifiedNameCheckbox.getEnabled() && fQualifiedNameCheckbox.getSelection());
}
boolean preview= okEnabled;
if (preview)
preview=
fRefactoring.getUpdateQualifiedNames() && fRefactoring.canEnableQualifiedNameUpdating() ||
fReferenceCheckbox.getSelection() && fRefactoring.canUpdateReferences();
fPreview.setEnabled(preview);
} catch (JavaModelException e){
ExceptionHandler.handle(e, ReorgMessages.getString("JdtMoveAction.move"), ReorgMessages.getString("JdtMoveAction.exception")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
protected void buttonPressed(int buttonId) {
super.buttonPressed(buttonId);
if (buttonId == PREVIEW_ID) {
setReturnCode(PREVIEW_ID);
close();
}
}
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.MOVE_DESTINATION_DIALOG);
}
protected void createButtonsForButtonBar(Composite parent) {
fPreview= createButton(parent, PREVIEW_ID, ReorgMessages.getString("JdtMoveAction.preview"), false); //$NON-NLS-1$
super.createButtonsForButtonBar(parent);
}
protected Control createDialogArea(Composite parent) {
Composite result= (Composite)super.createDialogArea(parent);
addUpdateReferenceComponent(result);
addUpdateQualifiedNameComponent(result, ((GridLayout)result.getLayout()).marginWidth);
return result;
}
private void addUpdateReferenceComponent(Composite result) {
fReferenceCheckbox= new Button(result, SWT.CHECK);
fReferenceCheckbox.setText(ReorgMessages.getString("JdtMoveAction.update_references")); //$NON-NLS-1$
fReferenceCheckbox.setSelection(fRefactoring.getUpdateReferences());
fReferenceCheckbox.setEnabled(canUpdateReferences());
fReferenceCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fRefactoring.setUpdateReferences(((Button)e.widget).getSelection());
updateOKStatus();
}
});
}
private boolean canUpdateReferences() {
try{
return fRefactoring.canUpdateReferences();
} catch (JavaModelException e){
return false;
}
}
private void addUpdateQualifiedNameComponent(Composite parent, int marginWidth) {
if (!fRefactoring.canUpdateQualifiedNames())
return;
fQualifiedNameCheckbox= new Button(parent, SWT.CHECK);
int indent= marginWidth + fQualifiedNameCheckbox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x;
fQualifiedNameCheckbox.setText(RefactoringMessages.getString("RenameInputWizardPage.update_qualified_names")); //$NON-NLS-1$
fQualifiedNameCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fQualifiedNameCheckbox.setSelection(fRefactoring.getUpdateQualifiedNames());
fQualifiedNameComponent= new QualifiedNameComponent(parent, SWT.NONE, fRefactoring, getRefactoringSettings());
fQualifiedNameComponent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridData gd= (GridData)fQualifiedNameComponent.getLayoutData();
gd.horizontalAlignment= GridData.FILL;
gd.horizontalIndent= indent;
fQualifiedNameComponent.setEnabled(false);
fQualifiedNameCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
boolean enabled= ((Button)e.widget).getSelection();
fQualifiedNameComponent.setEnabled(enabled);
fRefactoring.setUpdateQualifiedNames(enabled);
updateOKStatus();
}
});
}
protected IDialogSettings getRefactoringSettings() {
IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings();
if (settings == null)
return null;
IDialogSettings result= settings.getSection(RefactoringWizardPage.REFACTORING_SETTINGS);
if (result == null) {
result= new DialogSettings(RefactoringWizardPage.REFACTORING_SETTINGS);
settings.addSection(result);
}
return result;
}
}
public static IPackageFragmentRootManipulationQuery createUpdateClasspathQuery(Shell shell){
String messagePattern= ReorgMessages.getString("JdtMoveAction.referenced") + //$NON-NLS-1$
ReorgMessages.getString("JdtMoveAction.update_classpath"); //$NON-NLS-1$
return new PackageFragmentRootManipulationQuery(shell, ReorgMessages.getString("JdtMoveAction.Move"), messagePattern); //$NON-NLS-1$
}
}
|
31,113 |
Bug 31113 Don't offer to do a deep copy/move of linked resources
| null |
verified fixed
|
43e4e2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T13:08:59Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/ReorgQueries.java
|
package org.eclipse.jdt.internal.ui.reorg;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
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.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.refactoring.Checks;
import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatus;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenamePackageRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ICopyQueries;
import org.eclipse.jdt.internal.corext.refactoring.reorg.IDeepCopyQuery;
import org.eclipse.jdt.internal.corext.refactoring.reorg.INewNameQuery;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils;
import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil;
import org.eclipse.jdt.internal.corext.util.Resources;
public class ReorgQueries implements ICopyQueries {
private static final String EMPTY= " "; //XXX workaround for bug#16256 //$NON-NLS-1$
private IDeepCopyQuery fDeepCopyQuery;
public ReorgQueries() {
//just one instance, so that we get the correct 'yes to all' behavior
fDeepCopyQuery= new DeepCopyQuery();
}
private static String removeTrailingJava(String name) {
Assert.isTrue(name.endsWith(".java")); //$NON-NLS-1$
return name.substring(0, name.length() - ".java".length()); //$NON-NLS-1$
}
public INewNameQuery createNewCompilationUnitNameQuery(ICompilationUnit cu) {
String[] keys= {removeTrailingJava(cu.getElementName())};
String message= ReorgMessages.getFormattedString("ReorgQueries.enterNewNameQuestion", keys); //$NON-NLS-1$
return createStaticQuery(createCompilationUnitNameValidator(cu), message, removeTrailingJava(cu.getElementName()));
}
public INewNameQuery createNewResourceNameQuery(IResource res) {
String[] keys= {res.getName()};
String message= ReorgMessages.getFormattedString("ReorgQueries.enterNewNameQuestion", keys); //$NON-NLS-1$
return createStaticQuery(createResourceNameValidator(res), message, res.getName());
}
public INewNameQuery createNewPackageNameQuery(IPackageFragment pack) {
String[] keys= {pack.getElementName()};
String message= ReorgMessages.getFormattedString("ReorgQueries.enterNewNameQuestion", keys); //$NON-NLS-1$
return createStaticQuery(createPackageNameValidator(pack), message, pack.getElementName());
}
public INewNameQuery createNullQuery(){
return createStaticQuery(null);
}
public INewNameQuery createStaticQuery(final String newName){
return new INewNameQuery(){
public String getNewName() {
return newName;
}
};
}
private static INewNameQuery createStaticQuery(final IInputValidator validator, final String message, final String initial){
return new INewNameQuery(){
public String getNewName() {
InputDialog dialog= new InputDialog(JavaPlugin.getActiveWorkbenchShell(), ReorgMessages.getString("ReorgQueries.nameConflictMessage"), message, initial, validator); //$NON-NLS-1$
if (dialog.open() == Window.CANCEL)
throw new OperationCanceledException();
return dialog.getValue();
}
};
}
private static IInputValidator createResourceNameValidator(final IResource res){
IInputValidator validator= new IInputValidator(){
public String isValid(String newText) {
if (newText == null || "".equals(newText) || res.getParent() == null) //$NON-NLS-1$
return EMPTY;
if (res.getParent().findMember(newText) != null)
return ReorgMessages.getString("ReorgQueries.resourceWithThisNameAlreadyExists"); //$NON-NLS-1$
if (! res.getParent().getFullPath().isValidSegment(newText))
return ReorgMessages.getString("ReorgQueries.invalidNameMessage"); //$NON-NLS-1$
IStatus status= res.getParent().getWorkspace().validateName(newText, res.getType());
if (status.getSeverity() == IStatus.ERROR)
return status.getMessage();
if (res.getName().equalsIgnoreCase(newText))
return ReorgMessages.getString("ReorgQueries.resourceExistsWithDifferentCaseMassage"); //$NON-NLS-1$
return null;
}
};
return validator;
}
private static IInputValidator createCompilationUnitNameValidator(final ICompilationUnit cu) {
IInputValidator validator= new IInputValidator(){
public String isValid(String newText) {
if (newText == null || "".equals(newText)) //$NON-NLS-1$
return EMPTY;
String newCuName= newText + ".java"; //$NON-NLS-1$
IStatus status= JavaConventions.validateCompilationUnitName(newCuName);
if (status.getSeverity() == IStatus.ERROR)
return status.getMessage();
RefactoringStatus refStatus;
try {
refStatus= Checks.checkCompilationUnitNewName(cu, newText);
} catch (JavaModelException e) {
return EMPTY;
}
if (refStatus.hasFatalError())
return refStatus.getFirstMessage(RefactoringStatus.FATAL);
if (cu.getElementName().equalsIgnoreCase(newCuName))
return ReorgMessages.getString("ReorgQueries.resourceExistsWithDifferentCaseMassage"); //$NON-NLS-1$
return null;
}
};
return validator;
}
private static IInputValidator createPackageNameValidator(final IPackageFragment pack) {
IInputValidator validator= new IInputValidator(){
public String isValid(String newText) {
if (newText == null || "".equals(newText)) //$NON-NLS-1$
return EMPTY;
IStatus status= JavaConventions.validatePackageName(newText);
if (status.getSeverity() == IStatus.ERROR)
return status.getMessage();
IJavaElement parent= pack.getParent();
try {
if (parent instanceof IPackageFragmentRoot){
if (! RenamePackageRefactoring.isPackageNameOkInRoot(newText, (IPackageFragmentRoot)parent))
return ReorgMessages.getString("ReorgQueries.packagewithThatNameexistsMassage"); //$NON-NLS-1$
}
} catch (JavaModelException e) {
return EMPTY;
}
if (pack.getElementName().equalsIgnoreCase(newText))
return ReorgMessages.getString("ReorgQueries.resourceExistsWithDifferentCaseMassage"); //$NON-NLS-1$
return null;
}
};
return validator;
}
public IDeepCopyQuery getDeepCopyQuery() {
return fDeepCopyQuery;
}
private static class DeepCopyQuery implements IDeepCopyQuery{
private boolean alwaysDeepCopy= false;
private boolean neverDeepCopy= false;
private boolean fCanceled= false;
public boolean performDeepCopy(final IResource source) {
final Shell parentShell= JavaPlugin.getActiveWorkbenchShell();
final int[] result = new int[1];
IPath location = source.getLocation();
if (location == null) {
//undefined path variable
return false;
}
if (location.toFile().exists() == false) {
//link target does not exist
return false;
}
if (alwaysDeepCopy) {
return true;
}
if (neverDeepCopy) {
return false;
}
// Dialogs need to be created and opened in the UI thread
Runnable query = new Runnable() {
public void run() {
int resultId[]= {
IDialogConstants.YES_ID,
IDialogConstants.YES_TO_ALL_ID,
IDialogConstants.NO_ID,
IDialogConstants.NO_TO_ALL_ID,
IDialogConstants.CANCEL_ID};
String message= ReorgMessages.getFormattedString("ReorgQueries.deep_copy", //$NON-NLS-1$
new String[] {source.getFullPath().makeRelative().toString()});
MessageDialog dialog= new MessageDialog(
parentShell,
ReorgMessages.getString("ReorgQueries.Linked_Resource"), //$NON-NLS-1$
null,
message,
MessageDialog.QUESTION,
new String[] {
IDialogConstants.YES_LABEL,
IDialogConstants.YES_TO_ALL_LABEL,
IDialogConstants.NO_LABEL,
IDialogConstants.NO_TO_ALL_LABEL,
IDialogConstants.CANCEL_LABEL },
0);
dialog.open();
result[0]= resultId[dialog.getReturnCode()];
}
};
parentShell.getDisplay().syncExec(query);
if (result[0] == IDialogConstants.YES_TO_ALL_ID) {
alwaysDeepCopy= true;
return true;
}
if (result[0] == IDialogConstants.YES_ID) {
return true;
}
if (result[0] == IDialogConstants.NO_TO_ALL_ID) {
neverDeepCopy= true;
}
if (result[0] == IDialogConstants.CANCEL_ID) {
fCanceled= true;
throw new OperationCanceledException();
}
return false;
}
}
static class OverwriteQuery {
private boolean alwaysOverwriteNonReadOnly= false;
private boolean alwaysOverwrite= false;
private boolean fCanceled= false;
public boolean overwrite(final Object element) {
IResource resource= ResourceUtil.getResource(element);
if (resource != null){
IPath location = resource.getLocation();
if (location == null) {
//undefined path variable
return false;
}
if (location.toFile().exists() == false) {
//link target does not exist
return false;
}
}
if (fCanceled)
return false;
if (alwaysOverwrite)
return true;
final boolean isReadOnly= isReadOnly(element);
if (alwaysOverwriteNonReadOnly && ! isReadOnly)
return true;
final Shell parentShell= JavaPlugin.getActiveWorkbenchShell();
final int[] result = new int[1];
// Dialogs need to be created and opened in the UI thread
Runnable query = new Runnable() {
public void run() {
int resultId[]= {
IDialogConstants.YES_ID,
IDialogConstants.YES_TO_ALL_ID,
IDialogConstants.NO_ID,
IDialogConstants.CANCEL_ID};
String message= createMessage(element, isReadOnly);
MessageDialog dialog= new MessageDialog(
parentShell,
ReorgMessages.getString("ReorgQueries.Confirm_Overwritting"), //$NON-NLS-1$
null,
message,
MessageDialog.QUESTION,
new String[] {
IDialogConstants.YES_LABEL,
IDialogConstants.YES_TO_ALL_LABEL,
IDialogConstants.NO_LABEL,
IDialogConstants.CANCEL_LABEL },
0);
dialog.open();
result[0]= resultId[dialog.getReturnCode()];
}
};
parentShell.getDisplay().syncExec(query);
if (result[0] == IDialogConstants.YES_TO_ALL_ID) {
alwaysOverwriteNonReadOnly= true;
if (isReadOnly)
alwaysOverwrite= true;
return true;
} else if (result[0] == IDialogConstants.YES_ID) {
return true;
} else if (result[0] == IDialogConstants.CANCEL_ID) {
fCanceled= true;
return false;
} else if (result[0] == IDialogConstants.NO_ID) {
return false;
}
Assert.isTrue(false);
return false;
}
public String createMessage(Object element, boolean isReadOnly) {
String[] keys= {ReorgUtils.getName(element)};
if (isReadOnly)
return ReorgMessages.getFormattedString("ReorgQueries.exists_read-only", keys); //$NON-NLS-1$
else
return ReorgMessages.getFormattedString("ReorgQueries.exists", keys); //$NON-NLS-1$
}
public boolean isCanceled(){
return fCanceled;
}
private static boolean isReadOnly(Object element) {
if (element instanceof IResource)
return isReadOnlyResource((IResource)element);
else if (element instanceof IJavaElement){
IResource resource= ResourceUtil.getResource(element);
if (resource == null)
return false;
if (isReadOnlyResource(resource))
return true;
return ((IJavaElement)element).isReadOnly();
} else
return false;
}
private static boolean isReadOnlyResource(IResource resource) {
IStatus status= Resources.makeCommittable(resource, null);
if (status.isOK())
return false;
if (status.getCode() == IJavaStatusConstants.VALIDATE_EDIT_CHANGED_CONTENT)
return false;
if (status.getCode() == IResourceStatus.OUT_OF_SYNC_LOCAL)
return false;
return true;
}
}
}
|
31,395 |
Bug 31395 Child window of Preferences dialog centers between screens
|
On the Preferences->Java->Code Generation->Names tab, the Edit button opens a dialog that is split between multiple monitors, instead of centering on the main Preference window like the rest of its child windows do.
|
resolved fixed
|
01b69c0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T14:23:51Z | 2003-02-08T07:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeFormatterConfigurationBlock.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 org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jdt.core.ICodeFormatter;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
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.util.TabFolderLayout;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
/*
* The page for setting code formatter options
*/
public class CodeFormatterConfigurationBlock extends OptionsConfigurationBlock {
// Preference store keys, see JavaCore.getOptions
private static final String PREF_NEWLINE_OPENING_BRACES= JavaCore.FORMATTER_NEWLINE_OPENING_BRACE;
private static final String PREF_NEWLINE_CONTROL_STATEMENT= JavaCore.FORMATTER_NEWLINE_CONTROL;
private static final String PREF_NEWLINE_CLEAR_ALL= JavaCore.FORMATTER_CLEAR_BLANK_LINES;
private static final String PREF_NEWLINE_ELSE_IF= JavaCore.FORMATTER_NEWLINE_ELSE_IF;
private static final String PREF_NEWLINE_EMPTY_BLOCK= JavaCore.FORMATTER_NEWLINE_EMPTY_BLOCK;
private static final String PREF_LINE_SPLIT= JavaCore.FORMATTER_LINE_SPLIT;
private static final String PREF_STYLE_COMPACT_ASSIGNEMENT= JavaCore.FORMATTER_COMPACT_ASSIGNMENT;
private static final String PREF_TAB_CHAR= JavaCore.FORMATTER_TAB_CHAR;
private static final String PREF_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE;
private static final String PREF_SPACE_CASTEXPRESSION= JavaCore.FORMATTER_SPACE_CASTEXPRESSION;
// values
private static final String INSERT= JavaCore.INSERT;
private static final String DO_NOT_INSERT= JavaCore.DO_NOT_INSERT;
private static final String COMPACT= JavaCore.COMPACT;
private static final String NORMAL= JavaCore.NORMAL;
private static final String TAB= JavaCore.TAB;
private static final String SPACE= JavaCore.SPACE;
private static final String CLEAR_ALL= JavaCore.CLEAR_ALL;
private static final String PRESERVE_ONE= JavaCore.PRESERVE_ONE;
private String fPreviewText;
private IDocument fPreviewDocument;
private Text fTabSizeTextBox;
private SourceViewer fSourceViewer;
private PixelConverter fPixelConverter;
private IStatus fLineLengthStatus;
private IStatus fTabSizeStatus;
public CodeFormatterConfigurationBlock(IStatusChangeListener context, IJavaProject project) {
super(context, project);
fPreviewDocument= new Document();
fPreviewText= loadPreviewFile("CodeFormatterPreviewCode.txt"); //$NON-NLS-1$
fLineLengthStatus= new StatusInfo();
fTabSizeStatus= new StatusInfo();
}
protected String[] getAllKeys() {
return new String[] {
PREF_NEWLINE_OPENING_BRACES, PREF_NEWLINE_CONTROL_STATEMENT, PREF_NEWLINE_CLEAR_ALL,
PREF_NEWLINE_ELSE_IF, PREF_NEWLINE_EMPTY_BLOCK, PREF_LINE_SPLIT,
PREF_STYLE_COMPACT_ASSIGNEMENT, PREF_TAB_CHAR, PREF_TAB_SIZE, PREF_SPACE_CASTEXPRESSION
};
}
protected Control createContents(Composite parent) {
fPixelConverter= new PixelConverter(parent);
int textWidth= fPixelConverter.convertWidthInCharsToPixels(6);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
TabFolder folder= new TabFolder(composite, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
String[] insertNotInsert= new String[] { INSERT, DO_NOT_INSERT };
layout= new GridLayout();
layout.numColumns= 2;
Composite newlineComposite= new Composite(folder, SWT.NULL);
newlineComposite.setLayout(layout);
String label= PreferencesMessages.getString("CodeFormatterPreferencePage.newline_opening_braces.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_OPENING_BRACES, insertNotInsert, 0);
label= PreferencesMessages.getString("CodeFormatterPreferencePage.newline_control_statement.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_CONTROL_STATEMENT, insertNotInsert, 0);
label= PreferencesMessages.getString("CodeFormatterPreferencePage.newline_clear_lines"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_CLEAR_ALL, new String[] { CLEAR_ALL, PRESERVE_ONE }, 0);
label= PreferencesMessages.getString("CodeFormatterPreferencePage.newline_else_if.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_ELSE_IF, insertNotInsert, 0);
label= PreferencesMessages.getString("CodeFormatterPreferencePage.newline_empty_block.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_EMPTY_BLOCK, insertNotInsert, 0);
layout= new GridLayout();
layout.numColumns= 2;
Composite lineSplittingComposite= new Composite(folder, SWT.NULL);
lineSplittingComposite.setLayout(layout);
label= PreferencesMessages.getString("CodeFormatterPreferencePage.split_line.label"); //$NON-NLS-1$
addTextField(lineSplittingComposite, label, PREF_LINE_SPLIT, 0, textWidth);
layout= new GridLayout();
layout.numColumns= 2;
Composite styleComposite= new Composite(folder, SWT.NULL);
styleComposite.setLayout(layout);
label= PreferencesMessages.getString("CodeFormatterPreferencePage.style_compact_assignement.label"); //$NON-NLS-1$
addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_ASSIGNEMENT, new String[] { COMPACT, NORMAL }, 0);
label= PreferencesMessages.getString("CodeFormatterPreferencePage.style_space_castexpression.label"); //$NON-NLS-1$
addCheckBox(styleComposite, label, PREF_SPACE_CASTEXPRESSION, insertNotInsert, 0);
label= PreferencesMessages.getString("CodeFormatterPreferencePage.tab_char.label"); //$NON-NLS-1$
addCheckBox(styleComposite, label, PREF_TAB_CHAR, new String[] { TAB, SPACE }, 0);
label= PreferencesMessages.getString("CodeFormatterPreferencePage.tab_size.label"); //$NON-NLS-1$
fTabSizeTextBox= addTextField(styleComposite, label, PREF_TAB_SIZE, 0, textWidth);
fTabSizeTextBox.setTextLimit(3);
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CodeFormatterPreferencePage.tab.newline.tabtitle")); //$NON-NLS-1$
item.setControl(newlineComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CodeFormatterPreferencePage.tab.linesplit.tabtitle")); //$NON-NLS-1$
item.setControl(lineSplittingComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CodeFormatterPreferencePage.tab.style.tabtitle")); //$NON-NLS-1$
item.setControl(styleComposite);
fSourceViewer= createPreview(parent);
updatePreview();
return composite;
}
private SourceViewer createPreview(Composite parent) {
SourceViewer previewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
previewViewer.configure(new JavaSourceViewerConfiguration(tools, null));
previewViewer.getTextWidget().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
previewViewer.getTextWidget().setTabs(getPositiveIntValue((String) fWorkingValues.get(PREF_TAB_SIZE), 0));
previewViewer.setEditable(false);
previewViewer.setDocument(fPreviewDocument);
Control control= previewViewer.getControl();
GridData gdata= new GridData(GridData.FILL_BOTH);
gdata.widthHint= fPixelConverter.convertWidthInCharsToPixels(30);
gdata.heightHint= fPixelConverter.convertHeightInCharsToPixels(12);
control.setLayoutData(gdata);
return previewViewer;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#validateSettings(java.lang.String, java.lang.String)
*/
protected void validateSettings(String changedKey, String newValue) {
if (changedKey == null || PREF_LINE_SPLIT.equals(changedKey)) {
fLineLengthStatus= validatePositiveNumber(newValue);
}
if (changedKey == null || PREF_TAB_SIZE.equals(changedKey)) {
fTabSizeStatus= validatePositiveNumber(newValue);
int oldTabSize= fSourceViewer.getTextWidget().getTabs();
if (fTabSizeStatus.matches(IStatus.ERROR)) {
fWorkingValues.put(PREF_TAB_SIZE, String.valueOf(oldTabSize)); // set back
} else {
fSourceViewer.getTextWidget().setTabs(getPositiveIntValue(newValue, 0));
}
}
updatePreview();
fContext.statusChanged(StatusUtil.getMoreSevere(fLineLengthStatus, fTabSizeStatus));
}
private String loadPreviewFile(String filename) {
String separator= System.getProperty("line.separator"); //$NON-NLS-1$
StringBuffer btxt= new StringBuffer(512);
BufferedReader rin= null;
try {
rin= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename)));
String line;
while ((line= rin.readLine()) != null) {
if (btxt.length() > 0) {
btxt.append(separator);
}
btxt.append(line);
}
} catch (IOException io) {
JavaPlugin.log(io);
} finally {
if (rin != null) {
try { rin.close(); } catch (IOException e) {}
}
}
return btxt.toString();
}
private void updatePreview() {
ICodeFormatter formatter= ToolFactory.createDefaultCodeFormatter(fWorkingValues);
fPreviewDocument.set(formatter.format(fPreviewText, 0, null, "\n")); //$NON-NLS-1$
}
private IStatus validatePositiveNumber(String number) {
StatusInfo status= new StatusInfo();
if (number.length() == 0) {
status.setError(PreferencesMessages.getString("CodeFormatterPreferencePage.empty_input")); //$NON-NLS-1$
} else {
try {
int value= Integer.parseInt(number);
if (value < 0) {
status.setError(PreferencesMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$
}
} catch (NumberFormatException e) {
status.setError(PreferencesMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$
}
}
return status;
}
private static int getPositiveIntValue(String string, int dflt) {
try {
int i= Integer.parseInt(string);
if (i >= 0) {
return i;
}
} catch (NumberFormatException e) {
}
return dflt;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#getFullBuildDialogStrings(boolean)
*/
protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
return null; // no build required
}
}
|
31,395 |
Bug 31395 Child window of Preferences dialog centers between screens
|
On the Preferences->Java->Code Generation->Names tab, the Edit button opens a dialog that is split between multiple monitors, instead of centering on the main Preference window like the rest of its child windows do.
|
resolved fixed
|
01b69c0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T14:23:51Z | 2003-02-08T07:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerConfigurationBlock.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
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.util.TabFolderLayout;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
/**
*/
public class CompilerConfigurationBlock extends OptionsConfigurationBlock {
// Preference store keys, see JavaCore.getOptions
private static final String PREF_LOCAL_VARIABLE_ATTR= JavaCore.COMPILER_LOCAL_VARIABLE_ATTR;
private static final String PREF_LINE_NUMBER_ATTR= JavaCore.COMPILER_LINE_NUMBER_ATTR;
private static final String PREF_SOURCE_FILE_ATTR= JavaCore.COMPILER_SOURCE_FILE_ATTR;
private static final String PREF_CODEGEN_UNUSED_LOCAL= JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL;
private static final String PREF_CODEGEN_TARGET_PLATFORM= JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM;
private static final String PREF_PB_UNREACHABLE_CODE= JavaCore.COMPILER_PB_UNREACHABLE_CODE;
private static final String PREF_PB_INVALID_IMPORT= JavaCore.COMPILER_PB_INVALID_IMPORT;
private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= JavaCore.COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD;
private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= JavaCore.COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME;
private static final String PREF_PB_DEPRECATION= JavaCore.COMPILER_PB_DEPRECATION;
private static final String PREF_PB_HIDDEN_CATCH_BLOCK= JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK;
private static final String PREF_PB_UNUSED_LOCAL= JavaCore.COMPILER_PB_UNUSED_LOCAL;
private static final String PREF_PB_UNUSED_PARAMETER= JavaCore.COMPILER_PB_UNUSED_PARAMETER;
private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= JavaCore.COMPILER_PB_SYNTHETIC_ACCESS_EMULATION;
private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= JavaCore.COMPILER_PB_NON_NLS_STRING_LITERAL;
private static final String PREF_PB_ASSERT_AS_IDENTIFIER= JavaCore.COMPILER_PB_ASSERT_IDENTIFIER;
private static final String PREF_PB_MAX_PER_UNIT= JavaCore.COMPILER_PB_MAX_PER_UNIT;
private static final String PREF_PB_UNUSED_IMPORT= JavaCore.COMPILER_PB_UNUSED_IMPORT;
private static final String PREF_PB_UNUSED_PRIVATE= JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER;
private static final String PREF_PB_STATIC_ACCESS_RECEIVER= JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER;
private static final String PREF_PB_NO_EFFECT_ASSIGNMENT= JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT;
private static final String PREF_PB_CHAR_ARRAY_IN_CONCAT= JavaCore.COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION;
private static final String PREF_SOURCE_COMPATIBILITY= JavaCore.COMPILER_SOURCE;
private static final String PREF_COMPLIANCE= JavaCore.COMPILER_COMPLIANCE;
private static final String PREF_RESOURCE_FILTER= JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER;
private static final String PREF_BUILD_INVALID_CLASSPATH= JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH;
private static final String PREF_BUILD_CLEAN_OUTPUT_FOLDER= JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER;
private static final String PREF_PB_INCOMPLETE_BUILDPATH= JavaCore.CORE_INCOMPLETE_CLASSPATH;
private static final String PREF_PB_CIRCULAR_BUILDPATH= JavaCore.CORE_CIRCULAR_CLASSPATH;
private static final String PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE= JavaCore.COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE;
private static final String PREF_PB_DUPLICATE_RESOURCE= JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE;
private static final String PREF_PB_INCOMPATIBLE_INTERFACE_METHOD= JavaCore.COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD;
private static final String INTR_DEFAULT_COMPLIANCE= "internal.default.compliance"; //$NON-NLS-1$
// values
private static final String GENERATE= JavaCore.GENERATE;
private static final String DO_NOT_GENERATE= JavaCore.DO_NOT_GENERATE;
private static final String PRESERVE= JavaCore.PRESERVE;
private static final String OPTIMIZE_OUT= JavaCore.OPTIMIZE_OUT;
private static final String VERSION_1_1= JavaCore.VERSION_1_1;
private static final String VERSION_1_2= JavaCore.VERSION_1_2;
private static final String VERSION_1_3= JavaCore.VERSION_1_3;
private static final String VERSION_1_4= JavaCore.VERSION_1_4;
private static final String ERROR= JavaCore.ERROR;
private static final String WARNING= JavaCore.WARNING;
private static final String IGNORE= JavaCore.IGNORE;
private static final String ABORT= JavaCore.ABORT;
private static final String CLEAN= JavaCore.CLEAN;
private static final String ENABLED= JavaCore.ENABLED;
private static final String DISABLED= JavaCore.DISABLED;
private static final String PRIORITY_HIGH= JavaCore.COMPILER_TASK_PRIORITY_HIGH;
private static final String PRIORITY_NORMAL= JavaCore.COMPILER_TASK_PRIORITY_NORMAL;
private static final String PRIORITY_LOW= JavaCore.COMPILER_TASK_PRIORITY_LOW;
private static final String DEFAULT= "default"; //$NON-NLS-1$
private static final String USER= "user"; //$NON-NLS-1$
private ArrayList fComplianceControls;
private PixelConverter fPixelConverter;
private IStatus fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus;
public CompilerConfigurationBlock(IStatusChangeListener context, IJavaProject project) {
super(context, project);
fComplianceControls= new ArrayList();
fComplianceStatus= new StatusInfo();
fMaxNumberProblemsStatus= new StatusInfo();
fResourceFilterStatus= new StatusInfo();
}
protected String[] getAllKeys() {
return new String[] {
PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL,
PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_UNREACHABLE_CODE, PREF_PB_INVALID_IMPORT, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD,
PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, PREF_PB_DEPRECATION, PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL,
PREF_PB_UNUSED_PARAMETER, PREF_PB_SYNTHETIC_ACCESS_EMULATION, PREF_PB_NON_EXTERNALIZED_STRINGS,
PREF_PB_ASSERT_AS_IDENTIFIER, PREF_PB_UNUSED_IMPORT, PREF_PB_MAX_PER_UNIT, PREF_SOURCE_COMPATIBILITY, PREF_COMPLIANCE,
PREF_RESOURCE_FILTER, PREF_BUILD_INVALID_CLASSPATH, PREF_PB_STATIC_ACCESS_RECEIVER, PREF_PB_INCOMPLETE_BUILDPATH,
PREF_PB_CIRCULAR_BUILDPATH, PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, PREF_BUILD_CLEAN_OUTPUT_FOLDER,
PREF_PB_DUPLICATE_RESOURCE, PREF_PB_NO_EFFECT_ASSIGNMENT, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD,
PREF_PB_UNUSED_PRIVATE, PREF_PB_CHAR_ARRAY_IN_CONCAT
};
}
protected final Map getOptions(boolean inheritJavaCoreOptions) {
Map map= super.getOptions(inheritJavaCoreOptions);
map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map));
return map;
}
protected final Map getDefaultOptions() {
Map map= super.getDefaultOptions();
map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map));
return map;
}
/**
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
fPixelConverter= new PixelConverter(parent);
fShell= parent.getShell();
TabFolder folder= new TabFolder(parent, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite problemsComposite= createProblemsTabContent(folder);
Composite styleComposite= createStyleTabContent(folder);
Composite complianceComposite= createComplianceTabContent(folder);
Composite othersComposite= createOthersTabContent(folder);
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.problems.tabtitle")); //$NON-NLS-1$
item.setControl(problemsComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.style.tabtitle")); //$NON-NLS-1$
item.setControl(styleComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.compliance.tabtitle")); //$NON-NLS-1$
item.setControl(complianceComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.others.tabtitle")); //$NON-NLS-1$
item.setControl(othersComposite);
validateSettings(null, null);
return folder;
}
private Composite createStyleTabContent(TabFolder folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
GridLayout layout= new GridLayout();
layout.numColumns= 2;
//layout.verticalSpacing= 2;
Composite styleComposite= new Composite(folder, SWT.NULL);
styleComposite.setLayout(layout);
Label description= new Label(styleComposite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.style.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 2;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$
addComboBox(styleComposite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_method_naming.label"); //$NON-NLS-1$
addComboBox(styleComposite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_incompatible_interface_method.label"); //$NON-NLS-1$
addComboBox(styleComposite, label, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_hidden_catchblock.label"); //$NON-NLS-1$
addComboBox(styleComposite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_static_access_receiver.label"); //$NON-NLS-1$
addComboBox(styleComposite, label, PREF_PB_STATIC_ACCESS_RECEIVER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_synth_access_emul.label"); //$NON-NLS-1$
addComboBox(styleComposite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_no_effect_assignment.label"); //$NON-NLS-1$
addComboBox(styleComposite, label, PREF_PB_NO_EFFECT_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_char_array_in_concat.label"); //$NON-NLS-1$
addComboBox(styleComposite, label, PREF_PB_CHAR_ARRAY_IN_CONCAT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
return styleComposite;
}
private Composite createOthersTabContent(TabFolder folder) {
String[] abortIgnoreValues= new String[] { ABORT, IGNORE };
String[] cleanIgnoreValues= new String[] { CLEAN, IGNORE };
String[] errorWarning= new String[] { ERROR, WARNING };
String[] errorWarningLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning") //$NON-NLS-1$
};
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite othersComposite= new Composite(folder, SWT.NULL);
othersComposite.setLayout(layout);
Label description= new Label(othersComposite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.build_warnings.description")); //$NON-NLS-1$
GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan= 2;
// gd.widthHint= convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
Composite combos= new Composite(othersComposite, SWT.NULL);
gd= new GridData(GridData.FILL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan= 2;
combos.setLayoutData(gd);
GridLayout cl= new GridLayout();
cl.numColumns=2; cl.marginWidth= 0; cl.marginHeight= 0;
combos.setLayout(cl);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_incomplete_build_path.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_INCOMPLETE_BUILDPATH, errorWarning, errorWarningLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_build_path_cycles.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_CIRCULAR_BUILDPATH, errorWarning, errorWarningLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_duplicate_resources.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_DUPLICATE_RESOURCE, errorWarning, errorWarningLabels, 0);
Composite textField= new Composite(othersComposite, SWT.NULL);
gd= new GridData(GridData.FILL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan= 2;
textField.setLayoutData(gd);
cl= new GridLayout();
cl.numColumns=2; cl.marginWidth= 0; cl.marginHeight= 0;
textField.setLayout(cl);
gd= new GridData();
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(6);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_max_per_unit.label"); //$NON-NLS-1$
Text text= addTextField(textField, label, PREF_PB_MAX_PER_UNIT, 0, 0);
text.setTextLimit(6);
text.setLayoutData(gd);
label= PreferencesMessages.getString("CompilerConfigurationBlock.build_invalid_classpath.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_BUILD_INVALID_CLASSPATH, abortIgnoreValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.build_clean_outputfolder.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_BUILD_CLEAN_OUTPUT_FOLDER, cleanIgnoreValues, 0);
description= new Label(othersComposite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.resource_filter.description")); //$NON-NLS-1$
gd= new GridData(GridData.FILL);
gd.horizontalSpan= 2;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(60);
description.setLayoutData(gd);
label= PreferencesMessages.getString("CompilerConfigurationBlock.resource_filter.label"); //$NON-NLS-1$
text= addTextField(othersComposite, label, PREF_RESOURCE_FILTER, 0, 0);
gd= (GridData) text.getLayoutData();
gd.grabExcessHorizontalSpace= true;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(10);
return othersComposite;
}
private Composite createProblemsTabContent(Composite folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
String[] enabledDisabled= new String[] { ENABLED, DISABLED };
GridLayout layout= new GridLayout();
layout.numColumns= 2;
//layout.verticalSpacing= 2;
Composite problemsComposite= new Composite(folder, SWT.NULL);
problemsComposite.setLayout(layout);
Label description= new Label(problemsComposite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.problems.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 2;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
Composite combos= new Composite(problemsComposite, SWT.NULL);
gd= new GridData();
gd.horizontalSpan= 2;
combos.setLayoutData(gd);
GridLayout cl= new GridLayout();
cl.numColumns=2; cl.marginWidth= 0; cl.marginHeight= 0;
combos.setLayout(cl);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unreachable_code.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNREACHABLE_CODE, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_invalid_import.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_INVALID_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_local.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_parameter.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_imports.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNUSED_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_private.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNUSED_PRIVATE, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_non_externalized_strings.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_deprecation.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_deprecation_in_deprecation.label"); //$NON-NLS-1$
addCheckBox(problemsComposite, label, PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, enabledDisabled, 0);
return problemsComposite;
}
private Composite createComplianceTabContent(Composite folder) {
GridLayout layout= new GridLayout();
layout.numColumns= 1;
String[] values34= new String[] { VERSION_1_3, VERSION_1_4 };
String[] values34Labels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$
};
Composite compComposite= new Composite(folder, SWT.NULL);
compComposite.setLayout(layout);
layout= new GridLayout();
layout.numColumns= 2;
Group group= new Group(compComposite, SWT.NONE);
group.setText(PreferencesMessages.getString("CompilerConfigurationBlock.compliance.group.label")); //$NON-NLS-1$
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.compiler_compliance.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_COMPLIANCE, values34, values34Labels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.default_settings.label"); //$NON-NLS-1$
addCheckBox(group, label, INTR_DEFAULT_COMPLIANCE, new String[] { DEFAULT, USER }, 0);
int indent= fPixelConverter.convertWidthInCharsToPixels(2);
Control[] otherChildren= group.getChildren();
String[] values14= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4 };
String[] values14Labels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.version11"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version12"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$
};
label= PreferencesMessages.getString("CompilerConfigurationBlock.codegen_targetplatform.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_CODEGEN_TARGET_PLATFORM, values14, values14Labels, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.source_compatibility.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_SOURCE_COMPATIBILITY, values34, values34Labels, indent);
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_assert_as_identifier.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, indent);
Control[] allChildren= group.getChildren();
fComplianceControls.addAll(Arrays.asList(allChildren));
fComplianceControls.removeAll(Arrays.asList(otherChildren));
layout= new GridLayout();
layout.numColumns= 2;
group= new Group(compComposite, SWT.NONE);
group.setText(PreferencesMessages.getString("CompilerConfigurationBlock.classfiles.group.label")); //$NON-NLS-1$
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE };
label= PreferencesMessages.getString("CompilerConfigurationBlock.variable_attr.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_LOCAL_VARIABLE_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.line_number_attr.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_LINE_NUMBER_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.source_file_attr.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_SOURCE_FILE_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.codegen_unused_local.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }, 0);
return compComposite;
}
/* (non-javadoc)
* Update fields and validate.
* @param changedKey Key that changed, or null, if all changed.
*/
protected 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();
}
fComplianceStatus= validateCompliance();
} else if (PREF_SOURCE_COMPATIBILITY.equals(changedKey) ||
PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey) ||
PREF_PB_ASSERT_AS_IDENTIFIER.equals(changedKey)) {
fComplianceStatus= validateCompliance();
} else if (PREF_PB_MAX_PER_UNIT.equals(changedKey)) {
fMaxNumberProblemsStatus= validateMaxNumberProblems();
} else if (PREF_RESOURCE_FILTER.equals(changedKey)) {
fResourceFilterStatus= validateResourceFilters();
} else {
return;
}
} else {
updateComplianceEnableState();
fComplianceStatus= validateCompliance();
fMaxNumberProblemsStatus= validateMaxNumberProblems();
fResourceFilterStatus= validateResourceFilters();
}
IStatus status= StatusUtil.getMostSevere(new IStatus[] { fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus });
fContext.statusChanged(status);
}
private IStatus validateCompliance() {
StatusInfo status= new StatusInfo();
if (checkValue(PREF_COMPLIANCE, VERSION_1_3)) {
if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13src14.error")); //$NON-NLS-1$
return status;
} else if (checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.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(PreferencesMessages.getString("CompilerConfigurationBlock.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(PreferencesMessages.getString("CompilerConfigurationBlock.src14tgt14.error")); //$NON-NLS-1$
return status;
}
}
return status;
}
private IStatus validateMaxNumberProblems() {
String number= (String) fWorkingValues.get(PREF_PB_MAX_PER_UNIT);
StatusInfo status= new StatusInfo();
if (number.length() == 0) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.empty_input")); //$NON-NLS-1$
} else {
try {
int value= Integer.parseInt(number);
if (value <= 0) {
status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$
}
} catch (NumberFormatException e) {
status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$
}
}
return status;
}
private IStatus validateResourceFilters() {
String text= (String) fWorkingValues.get(PREF_RESOURCE_FILTER);
IWorkspace workspace= ResourcesPlugin.getWorkspace();
String[] filters= getTokens(text, ","); //$NON-NLS-1$
for (int i= 0; i < filters.length; i++) {
String fileName= filters[i].replace('*', 'x');
int resourceType= IResource.FILE;
int lastCharacter= fileName.length() - 1;
if (lastCharacter >= 0 && fileName.charAt(lastCharacter) == '/') {
fileName= fileName.substring(0, lastCharacter);
resourceType= IResource.FOLDER;
}
IStatus status= workspace.validateName(fileName, resourceType);
if (status.matches(IStatus.ERROR)) {
String message= PreferencesMessages.getFormattedString("CompilerConfigurationBlock.filter.invalidsegment.error", status.getMessage()); //$NON-NLS-1$
return new StatusInfo(IStatus.ERROR, message);
}
}
return new StatusInfo();
}
private IStatus validateTaskTags() {
return new StatusInfo();
}
/*
* 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 static String getCurrentCompliance(Map map) {
Object complianceLevel= map.get(PREF_COMPLIANCE);
if ((VERSION_1_3.equals(complianceLevel)
&& IGNORE.equals(map.get(PREF_PB_ASSERT_AS_IDENTIFIER))
&& VERSION_1_3.equals(map.get(PREF_SOURCE_COMPATIBILITY))
&& VERSION_1_1.equals(map.get(PREF_CODEGEN_TARGET_PLATFORM)))
|| (VERSION_1_4.equals(complianceLevel)
&& ERROR.equals(map.get(PREF_PB_ASSERT_AS_IDENTIFIER))
&& VERSION_1_4.equals(map.get(PREF_SOURCE_COMPATIBILITY))
&& VERSION_1_4.equals(map.get(PREF_CODEGEN_TARGET_PLATFORM)))) {
return DEFAULT;
}
return USER;
}
protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
String title= PreferencesMessages.getString("CompilerConfigurationBlock.needsbuild.title"); //$NON-NLS-1$
String message;
if (workspaceSettings) {
message= PreferencesMessages.getString("CompilerConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$
} else {
message= PreferencesMessages.getString("CompilerConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$
}
return new String[] { title, message };
}
}
|
31,395 |
Bug 31395 Child window of Preferences dialog centers between screens
|
On the Preferences->Java->Code Generation->Names tab, the Edit button opens a dialog that is split between multiple monitors, instead of centering on the main Preference window like the rest of its child windows do.
|
resolved fixed
|
01b69c0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T14:23:51Z | 2003-02-08T07:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NameConventionConfigurationBlock.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
/*
* The page to configure name conventions
*/
public class NameConventionConfigurationBlock extends OptionsConfigurationBlock {
private final static int FIELD= 1;
private final static int STATIC= 2;
private final static int ARGUMENT= 3;
private final static int LOCAL= 4;
// Preference store keys, see JavaCore.getOptions
private static final String PREF_FIELD_PREFIXES= JavaCore.CODEASSIST_FIELD_PREFIXES;
private static final String PREF_FIELD_SUFFIXES= JavaCore.CODEASSIST_FIELD_SUFFIXES;
private static final String PREF_STATIC_FIELD_PREFIXES= JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES;
private static final String PREF_STATIC_FIELD_SUFFIXES= JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES;
private static final String PREF_ARGUMENT_PREFIXES= JavaCore.CODEASSIST_ARGUMENT_PREFIXES;
private static final String PREF_ARGUMENT_SUFFIXES= JavaCore.CODEASSIST_ARGUMENT_SUFFIXES;
private static final String PREF_LOCAL_PREFIXES= JavaCore.CODEASSIST_LOCAL_PREFIXES;
private static final String PREF_LOCAL_SUFFIXES= JavaCore.CODEASSIST_LOCAL_SUFFIXES;
private static class NameConventionEntry {
public int kind;
public String prefix;
public String suffix;
public String prefixkey;
public String suffixkey;
}
private class NameConventionInputDialog extends StatusDialog implements IDialogFieldListener {
private StringDialogField fPrefixField;
private StringDialogField fSuffixField;
private NameConventionEntry fEntry;
private DialogField fMessageField;
public NameConventionInputDialog(Shell parent, String title, String message, NameConventionEntry entry) {
super(parent);
fEntry= entry;
setTitle(title);
fMessageField= new DialogField();
fMessageField.setLabelText(message);
fPrefixField= new StringDialogField();
fPrefixField.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.dialog.prefix")); //$NON-NLS-1$
fPrefixField.setDialogFieldListener(this);
fSuffixField= new StringDialogField();
fSuffixField.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.dialog.suffix")); //$NON-NLS-1$
fSuffixField.setDialogFieldListener(this);
fPrefixField.setText(entry.prefix);
fSuffixField.setText(entry.suffix);
}
public NameConventionEntry getResult() {
NameConventionEntry res= new NameConventionEntry();
res.prefix= fPrefixField.getText();
res.suffix= fSuffixField.getText();
res.prefixkey= fEntry.prefixkey;
res.suffixkey= fEntry.suffixkey;
res.kind= fEntry.kind;
return res;
}
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite) super.createDialogArea(parent);
Composite inner= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
inner.setLayout(layout);
fMessageField.doFillIntoGrid(inner, 2);
fPrefixField.doFillIntoGrid(inner, 2);
fSuffixField.doFillIntoGrid(inner, 2);
LayoutUtil.setHorizontalGrabbing(fPrefixField.getTextControl(null));
LayoutUtil.setWidthHint(fPrefixField.getTextControl(null), convertWidthInCharsToPixels(45));
LayoutUtil.setWidthHint(fSuffixField.getTextControl(null), convertWidthInCharsToPixels(45));
fPrefixField.postSetFocusOnDialogField(parent.getDisplay());
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField)
*/
public void dialogFieldChanged(DialogField field) {
// validate
IStatus prefixStatus= validateIdentifiers(getTokens(fPrefixField.getText(), ","), true); //$NON-NLS-1$
IStatus suffixStatus= validateIdentifiers(getTokens(fSuffixField.getText(), ","), false); //$NON-NLS-1$
updateStatus(StatusUtil.getMoreSevere(suffixStatus, prefixStatus));
}
private IStatus validateIdentifiers(String[] values, boolean prefix) {
for (int i= 0; i < values.length; i++) {
String val= values[i];
if (val.length() == 0) {
if (prefix) {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("NameConventionConfigurationBlock.error.emptyprefix")); //$NON-NLS-1$
} else {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("NameConventionConfigurationBlock.error.emptysuffix")); //$NON-NLS-1$
}
}
String name= prefix ? val + "x" : "x" + val; //$NON-NLS-2$ //$NON-NLS-1$
IStatus status= JavaConventions.validateFieldName(name);
if (status.matches(IStatus.ERROR)) {
if (prefix) {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("NameConventionConfigurationBlock.error.invalidprefix", val)); //$NON-NLS-1$
} else {
return new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("NameConventionConfigurationBlock.error.invalidsuffix", val)); //$NON-NLS-1$
}
}
}
return new StatusInfo();
}
/*
* @see org.eclipse.jface.window.Window#configureShell(Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
//WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.IMPORT_ORGANIZE_INPUT_DIALOG);
}
}
private static class NameConventionLabelProvider extends LabelProvider implements ITableLabelProvider {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
*/
public Image getImage(Object element) {
return getColumnImage(element, 0);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
*/
public String getText(Object element) {
return getColumnText(element, 0);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
public Image getColumnImage(Object element, int columnIndex) {
if (columnIndex != 0) {
return null;
}
NameConventionEntry entry= (NameConventionEntry) element;
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
switch (entry.kind) {
case FIELD:
return registry.get(JavaPluginImages.DESC_FIELD_PUBLIC);
case STATIC:
return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_FIELD_PUBLIC, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE));
case ARGUMENT:
return registry.get(JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE);
default:
return registry.get(JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE);
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
public String getColumnText(Object element, int columnIndex) {
NameConventionEntry entry= (NameConventionEntry) element;
if (columnIndex == 0) {
switch (entry.kind) {
case FIELD:
return PreferencesMessages.getString("NameConventionConfigurationBlock.field.label"); //$NON-NLS-1$
case STATIC:
return PreferencesMessages.getString("NameConventionConfigurationBlock.static.label"); //$NON-NLS-1$
case ARGUMENT:
return PreferencesMessages.getString("NameConventionConfigurationBlock.arg.label"); //$NON-NLS-1$
default:
return PreferencesMessages.getString("NameConventionConfigurationBlock.local.label"); //$NON-NLS-1$
}
} else if (columnIndex == 1) {
return entry.prefix;
} else {
return entry.suffix;
}
}
}
private class NameConventionAdapter implements IListAdapter, IDialogFieldListener {
private boolean canEdit(ListDialogField field) {
return field.getSelectedElements().size() == 1;
}
public void customButtonPressed(ListDialogField field, int index) {
doEditButtonPressed(index);
}
public void selectionChanged(ListDialogField field) {
field.enableButton(0, canEdit(field));
}
public void doubleClicked(ListDialogField field) {
if (canEdit(field)) {
doEditButtonPressed(0);
}
}
public void dialogFieldChanged(DialogField field) {
validateSettings(null, null);
}
}
private ListDialogField fNameConventionList;
public NameConventionConfigurationBlock(IStatusChangeListener context, IJavaProject project) {
super(context, project);
NameConventionAdapter adapter= new NameConventionAdapter();
String[] buttons= new String[] {
/* 0 */ PreferencesMessages.getString("NameConventionConfigurationBlock.list.edit.button") //$NON-NLS-1$
};
fNameConventionList= new ListDialogField(adapter, buttons, new NameConventionLabelProvider());
fNameConventionList.setDialogFieldListener(adapter);
fNameConventionList.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.list.label")); //$NON-NLS-1$
String[] columnsHeaders= new String[] {
PreferencesMessages.getString("NameConventionConfigurationBlock.list.name.column"), //$NON-NLS-1$
PreferencesMessages.getString("NameConventionConfigurationBlock.list.prefix.column"), //$NON-NLS-1$
PreferencesMessages.getString("NameConventionConfigurationBlock.list.suffix.column"), //$NON-NLS-1$
};
ColumnLayoutData[] data= new ColumnLayoutData[] {
new ColumnWeightData(3),
new ColumnWeightData(2),
new ColumnWeightData(2)
};
fNameConventionList.setTableColumns(new ListDialogField.ColumnsDescription(data, columnsHeaders, true));
unpackEntries();
if (fNameConventionList.getSize() > 0) {
fNameConventionList.selectFirstElement();
} else {
fNameConventionList.enableButton(0, false);
}
}
protected String[] getAllKeys() {
return new String[] {
PREF_FIELD_PREFIXES, PREF_FIELD_SUFFIXES, PREF_STATIC_FIELD_PREFIXES, PREF_STATIC_FIELD_SUFFIXES,
PREF_ARGUMENT_PREFIXES, PREF_ARGUMENT_SUFFIXES, PREF_LOCAL_PREFIXES, PREF_LOCAL_SUFFIXES
};
}
protected Control createContents(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
int heightHint= converter.convertHeightInCharsToPixels(5);
fNameConventionList.doFillIntoGrid(composite, 3);
LayoutUtil.setHorizontalSpan(fNameConventionList.getLabelControl(null), 2);
LayoutUtil.setHorizontalGrabbing(fNameConventionList.getListControl(null));
LayoutUtil.setHeigthHint(fNameConventionList.getListControl(null), heightHint);
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#validateSettings(java.lang.String, java.lang.String)
*/
protected void validateSettings(String changedKey, String newValue) {
// no validation
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#updateControls()
*/
protected void updateControls() {
unpackEntries();
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#getFullBuildDialogStrings(boolean)
*/
protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
return null; // no build required
}
private void createEntry(List list, String prefixKey, String suffixKey, int kind) {
NameConventionEntry entry= new NameConventionEntry();
entry.kind= kind;
entry.suffixkey= suffixKey;
entry.prefixkey= prefixKey;
entry.suffix= (String) fWorkingValues.get(suffixKey);
entry.prefix= (String) fWorkingValues.get(prefixKey);
list.add(entry);
}
private void unpackEntries() {
ArrayList list= new ArrayList(4);
createEntry(list, PREF_FIELD_PREFIXES, PREF_FIELD_SUFFIXES, FIELD);
createEntry(list, PREF_STATIC_FIELD_PREFIXES, PREF_STATIC_FIELD_SUFFIXES, STATIC);
createEntry(list, PREF_ARGUMENT_PREFIXES, PREF_ARGUMENT_SUFFIXES, ARGUMENT);
createEntry(list, PREF_LOCAL_PREFIXES, PREF_LOCAL_SUFFIXES, LOCAL);
fNameConventionList.setElements(list);
}
private void packEntries() {
for (int i= 0; i < fNameConventionList.getSize(); i++) {
NameConventionEntry entry= (NameConventionEntry) fNameConventionList.getElement(i);
fWorkingValues.put(entry.suffixkey, entry.suffix);
fWorkingValues.put(entry.prefixkey, entry.prefix);
}
}
private void doEditButtonPressed(int index) {
NameConventionEntry entry= (NameConventionEntry) fNameConventionList.getSelectedElements().get(0);
String title;
String message;
switch (entry.kind) {
case FIELD:
title= PreferencesMessages.getString("NameConventionConfigurationBlock.field.dialog.title"); //$NON-NLS-1$
message= PreferencesMessages.getString("NameConventionConfigurationBlock.field.dialog.message"); //$NON-NLS-1$
break;
case STATIC:
title= PreferencesMessages.getString("NameConventionConfigurationBlock.static.dialog.title"); //$NON-NLS-1$
message= PreferencesMessages.getString("NameConventionConfigurationBlock.static.dialog.message"); //$NON-NLS-1$
break;
case ARGUMENT:
title= PreferencesMessages.getString("NameConventionConfigurationBlock.arg.dialog.title"); //$NON-NLS-1$
message= PreferencesMessages.getString("NameConventionConfigurationBlock.arg.dialog.message"); //$NON-NLS-1$
break;
default:
title= PreferencesMessages.getString("NameConventionConfigurationBlock.local.dialog.title"); //$NON-NLS-1$
message= PreferencesMessages.getString("NameConventionConfigurationBlock.local.dialog.message"); //$NON-NLS-1$
}
NameConventionInputDialog dialog= new NameConventionInputDialog(getShell(), title, message, entry);
if (dialog.open() == TodoTaskInputDialog.OK) {
fNameConventionList.replaceElement(entry, dialog.getResult());
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#performOk(boolean)
*/
public boolean performOk(boolean enabled) {
packEntries();
return super.performOk(enabled);
}
}
|
31,395 |
Bug 31395 Child window of Preferences dialog centers between screens
|
On the Preferences->Java->Code Generation->Names tab, the Edit button opens a dialog that is split between multiple monitors, instead of centering on the main Preference window like the rest of its child windows do.
|
resolved fixed
|
01b69c0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T14:23:51Z | 2003-02-08T07:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/OptionsConfigurationBlock.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.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.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
/**
*/
public abstract class OptionsConfigurationBlock {
protected 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();
}
}
protected Map fWorkingValues;
protected ArrayList fCheckBoxes;
protected ArrayList fComboBoxes;
protected ArrayList fTextBoxes;
private SelectionListener fSelectionListener;
private ModifyListener fTextModifyListener;
protected IStatusChangeListener fContext;
protected Shell fShell;
protected IJavaProject fProject; // project or null
public OptionsConfigurationBlock(IStatusChangeListener context, IJavaProject project) {
fContext= context;
fProject= project;
fWorkingValues= getOptions(true);
fCheckBoxes= new ArrayList();
fComboBoxes= new ArrayList();
fTextBoxes= new ArrayList(2);
}
protected abstract String[] getAllKeys();
protected Map getOptions(boolean inheritJavaCoreOptions) {
if (fProject != null) {
return fProject.getOptions(inheritJavaCoreOptions);
} else {
return JavaCore.getOptions();
}
}
protected Map getDefaultOptions() {
return JavaCore.getDefaultOptions();
}
public final boolean hasProjectSpecificOptions() {
if (fProject != null) {
Map settings= fProject.getOptions(false);
String[] allKeys= getAllKeys();
for (int i= 0; i < allKeys.length; i++) {
if (settings.get(allKeys[i]) != null) {
return true;
}
}
}
return false;
}
protected final void setOptions(Map map) {
if (fProject != null) {
fProject.setOptions(map);
} else {
JavaCore.setOptions((Hashtable) map);
}
}
protected Shell getShell() {
return fShell;
}
protected abstract Control createContents(Composite parent);
protected 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(getSelectionListener());
String currValue= (String)fWorkingValues.get(key);
checkBox.setSelection(data.getSelection(currValue) == 0);
fCheckBoxes.add(checkBox);
}
protected void addComboBox(Composite parent, String label, String key, String[] values, String[] valueLabels, int indent) {
ControlData data= new ControlData(key, values);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalIndent= indent;
Label labelControl= new Label(parent, SWT.LEFT | SWT.WRAP);
labelControl.setText(label);
labelControl.setLayoutData(gd);
Combo comboBox= new Combo(parent, SWT.READ_ONLY);
comboBox.setItems(valueLabels);
comboBox.setData(data);
comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
comboBox.addSelectionListener(getSelectionListener());
String currValue= (String)fWorkingValues.get(key);
comboBox.select(data.getSelection(currValue));
fComboBoxes.add(comboBox);
}
protected Text addTextField(Composite parent, String label, String key, int indent, int widthHint) {
Label labelControl= new Label(parent, SWT.NONE);
labelControl.setText(label);
labelControl.setLayoutData(new GridData());
Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE);
textBox.setData(key);
textBox.setLayoutData(new GridData());
String currValue= (String) fWorkingValues.get(key);
textBox.setText(currValue);
textBox.addModifyListener(getTextModifyListener());
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
if (widthHint != 0) {
data.widthHint= widthHint;
}
data.horizontalIndent= indent;
textBox.setLayoutData(data);
fTextBoxes.add(textBox);
return textBox;
}
protected SelectionListener getSelectionListener() {
if (fSelectionListener == null) {
fSelectionListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
controlChanged(e.widget);
}
};
}
return fSelectionListener;
}
protected ModifyListener getTextModifyListener() {
if (fTextModifyListener == null) {
fTextModifyListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
textChanged((Text) e.widget);
}
};
}
return fTextModifyListener;
}
protected 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);
}
protected void textChanged(Text textControl) {
String key= (String) textControl.getData();
String number= textControl.getText();
fWorkingValues.put(key, number);
validateSettings(key, number);
}
protected 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.
*/
protected abstract void validateSettings(String changedKey, String newValue);
protected String[] getTokens(String text, String separator) {
StringTokenizer tok= new StringTokenizer(text, separator); //$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;
}
public boolean performOk(boolean enabled) {
String[] allKeys= getAllKeys();
Map actualOptions= getOptions(false);
// preserve other options
boolean hasChanges= false;
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String oldVal= (String) actualOptions.get(key);
String val= null;
if (enabled) {
val= (String) fWorkingValues.get(key);
if (!val.equals(oldVal)) {
hasChanges= true;
actualOptions.put(key, val);
}
} else {
if (oldVal != null) {
actualOptions.remove(key);
hasChanges= true;
}
}
}
if (hasChanges) {
boolean doBuild= false;
String[] strings= getFullBuildDialogStrings(fProject == null);
if (strings != null) {
MessageDialog dialog= new MessageDialog(getShell(), strings[0], null, strings[1], MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
int res= dialog.open();
if (res == 0) {
doBuild= true;
} else if (res != 1) {
return false; // cancel pressed
}
}
setOptions(actualOptions);
if (doBuild) {
doFullBuild();
}
}
return true;
}
protected abstract String[] getFullBuildDialogStrings(boolean workspaceSettings);
protected void doFullBuild() {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
if (fProject != null) {
fProject.getProject().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
} else {
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= PreferencesMessages.getString("OptionsConfigurationBlock.builderror.title"); //$NON-NLS-1$
String message= PreferencesMessages.getString("OptionsConfigurationBlock.builderror.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
}
public void performDefaults() {
fWorkingValues= getDefaultOptions();
updateControls();
validateSettings(null, null);
}
protected void updateControls() {
// update the UI
for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
Button curr= (Button) fCheckBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.setSelection(data.getSelection(currValue) == 0);
}
for (int i= fComboBoxes.size() - 1; i >= 0; i--) {
Combo curr= (Combo) fComboBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.select(data.getSelection(currValue));
}
for (int i= fTextBoxes.size() - 1; i >= 0; i--) {
Text curr= (Text) fTextBoxes.get(i);
String key= (String) curr.getData();
String currValue= (String) fWorkingValues.get(key);
curr.setText(currValue);
}
}
}
|
31,395 |
Bug 31395 Child window of Preferences dialog centers between screens
|
On the Preferences->Java->Code Generation->Names tab, the Edit button opens a dialog that is split between multiple monitors, instead of centering on the main Preference window like the rest of its child windows do.
|
resolved fixed
|
01b69c0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T14:23:51Z | 2003-02-08T07:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/TodoTaskConfigurationBlock.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
/**
*/
public class TodoTaskConfigurationBlock extends OptionsConfigurationBlock {
private static final String PREF_COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
private static final String PREF_COMPILER_TASK_PRIORITIES= JavaCore.COMPILER_TASK_PRIORITIES;
private static final String PRIORITY_HIGH= JavaCore.COMPILER_TASK_PRIORITY_HIGH;
private static final String PRIORITY_NORMAL= JavaCore.COMPILER_TASK_PRIORITY_NORMAL;
private static final String PRIORITY_LOW= JavaCore.COMPILER_TASK_PRIORITY_LOW;
public static class TodoTask {
public String name;
public String priority;
}
private static class TodoTaskLabelProvider extends LabelProvider implements ITableLabelProvider {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
*/
public Image getImage(Object element) {
return null; // JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_INFO);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
*/
public String getText(Object element) {
return getColumnText(element, 0);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
public String getColumnText(Object element, int columnIndex) {
TodoTask task= (TodoTask) element;
if (columnIndex == 0) {
return task.name;
} else {
if (PRIORITY_HIGH.equals(task.priority)) {
return PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.high.priority"); //$NON-NLS-1$
} else if (PRIORITY_NORMAL.equals(task.priority)) {
return PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.normal.priority"); //$NON-NLS-1$
} else {
return PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.low.priority"); //$NON-NLS-1$
}
}
}
}
private PixelConverter fPixelConverter;
private IStatus fTaskTagsStatus;
private ListDialogField fTodoTasksList;
public TodoTaskConfigurationBlock(IStatusChangeListener context, IJavaProject project) {
super(context, project);
TaskTagAdapter adapter= new TaskTagAdapter();
String[] buttons= new String[] {
/* 0 */ PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.add.button"), //$NON-NLS-1$
/* 1 */ PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.remove.button"), //$NON-NLS-1$
null,
/* 3 */ PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.edit.button"), //$NON-NLS-1$
};
fTodoTasksList= new ListDialogField(adapter, buttons, new TodoTaskLabelProvider());
fTodoTasksList.setDialogFieldListener(adapter);
fTodoTasksList.setLabelText(PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.label")); //$NON-NLS-1$
fTodoTasksList.setRemoveButtonIndex(1);
String[] columnsHeaders= new String[] {
PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.name.column"), //$NON-NLS-1$
PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.priority.column"), //$NON-NLS-1$
};
fTodoTasksList.setTableColumns(new ListDialogField.ColumnsDescription(columnsHeaders, true));
unpackTodoTasks();
if (fTodoTasksList.getSize() > 0) {
fTodoTasksList.selectFirstElement();
} else {
fTodoTasksList.enableButton(3, false);
}
fTaskTagsStatus= new StatusInfo();
}
protected final String[] getAllKeys() {
return new String[] {
PREF_COMPILER_TASK_TAGS, PREF_COMPILER_TASK_PRIORITIES
};
}
public class TaskTagAdapter implements IListAdapter, IDialogFieldListener {
private boolean canEdit(ListDialogField field) {
return field.getSelectedElements().size() == 1;
}
public void customButtonPressed(ListDialogField field, int index) {
doTodoButtonPressed(index);
}
public void selectionChanged(ListDialogField field) {
field.enableButton(3, canEdit(field));
}
public void doubleClicked(ListDialogField field) {
if (canEdit(field)) {
doTodoButtonPressed(3);
}
}
public void dialogFieldChanged(DialogField field) {
validateSettings(PREF_COMPILER_TASK_TAGS, null);
}
}
protected Control createContents(Composite parent) {
fPixelConverter= new PixelConverter(parent);
fShell= parent.getShell();
Composite markersComposite= createMarkersTabContent(parent);
validateSettings(null, null);
return markersComposite;
}
private Composite createMarkersTabContent(Composite folder) {
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
Composite markersComposite= new Composite(folder, SWT.NULL);
markersComposite.setLayout(layout);
layout= new GridLayout();
layout.numColumns= 2;
Group group= new Group(markersComposite, SWT.NONE);
group.setText(PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.taskmarkers.label")); //$NON-NLS-1$
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
fTodoTasksList.doFillIntoGrid(group, 3);
LayoutUtil.setHorizontalSpan(fTodoTasksList.getLabelControl(null), 2);
LayoutUtil.setHorizontalGrabbing(fTodoTasksList.getListControl(null));
return markersComposite;
}
protected void validateSettings(String changedKey, String newValue) {
if (changedKey != null) {
if (PREF_COMPILER_TASK_TAGS.equals(changedKey)) {
fTaskTagsStatus= validateTaskTags();
} else {
return;
}
} else {
fTaskTagsStatus= validateTaskTags();
}
IStatus status= fTaskTagsStatus; //StatusUtil.getMostSevere(new IStatus[] { fTaskTagsStatus });
fContext.statusChanged(status);
}
private IStatus validateTaskTags() {
return new StatusInfo();
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#performOk(boolean)
*/
public boolean performOk(boolean enabled) {
packTodoTasks();
return super.performOk(enabled);
}
protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
String title= PreferencesMessages.getString("TodoTaskConfigurationBlock.needsbuild.title"); //$NON-NLS-1$
String message;
if (fProject == null) {
message= PreferencesMessages.getString("TodoTaskConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$
} else {
message= PreferencesMessages.getString("TodoTaskConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$
}
return new String[] { title, message };
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#updateControls()
*/
protected void updateControls() {
unpackTodoTasks();
}
private void unpackTodoTasks() {
String currTags= (String) fWorkingValues.get(PREF_COMPILER_TASK_TAGS);
String currPrios= (String) fWorkingValues.get(PREF_COMPILER_TASK_PRIORITIES);
String[] tags= getTokens(currTags, ","); //$NON-NLS-1$
String[] prios= getTokens(currPrios, ","); //$NON-NLS-1$
ArrayList elements= new ArrayList(tags.length);
for (int i= 0; i < tags.length; i++) {
TodoTask task= new TodoTask();
task.name= tags[i].trim();
task.priority= (i < prios.length) ? prios[i] : PRIORITY_NORMAL;
elements.add(task);
}
fTodoTasksList.setElements(elements);
}
private void packTodoTasks() {
StringBuffer tags= new StringBuffer();
StringBuffer prios= new StringBuffer();
List list= fTodoTasksList.getElements();
for (int i= 0; i < list.size(); i++) {
if (i > 0) {
tags.append(',');
prios.append(',');
}
TodoTask elem= (TodoTask) list.get(i);
tags.append(elem.name);
prios.append(elem.priority);
}
fWorkingValues.put(PREF_COMPILER_TASK_TAGS, tags.toString());
fWorkingValues.put(PREF_COMPILER_TASK_PRIORITIES, prios.toString());
}
private void doTodoButtonPressed(int index) {
TodoTask edited= null;
if (index != 0) {
edited= (TodoTask) fTodoTasksList.getSelectedElements().get(0);
}
TodoTaskInputDialog dialog= new TodoTaskInputDialog(getShell(), edited, fTodoTasksList.getElements());
if (dialog.open() == TodoTaskInputDialog.OK) {
if (edited != null) {
fTodoTasksList.replaceElement(edited, dialog.getResult());
} else {
fTodoTasksList.addElement(dialog.getResult());
}
}
}
}
|
31,351 |
Bug 31351 "Extrude" is not a good name for the quick assist
|
build I20030206 We should not use "extrude" to describe this quick assist. "extrude" means forcing (often through some device) to produce something. We should find a brief phrase to describe the operation and use it instead. I assume we are avoiding extract since it is used in the various refactorings. This assist causes the program to behave differently - it should be clear from the description that the transformation has this characteristic.
|
resolved fixed
|
27f17d7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T14:35:06Z | 2003-02-07T17:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java
|
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.*;
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.BodyDeclaration;
import org.eclipse.jdt.core.dom.CatchClause;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.ForStatement;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.TryStatement;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.WhileStatement;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
/**
*/
public class QuickAssistProcessor implements ICorrectionProcessor {
/**
* Constructor for CodeManipulationProcessor.
*/
public QuickAssistProcessor() {
super();
}
public void process(ICorrectionContext context, List resultingCollections) throws CoreException {
int id= context.getProblemId();
if (id != 0) { // no proposals for problem locations
return;
}
getAssignToVariableProposals(context, resultingCollections);
getCatchClauseToThrowsProposals(context, resultingCollections);
getRenameLocalProposals(context, resultingCollections);
getUnWrapProposals(context, resultingCollections);
}
private void getAssignToVariableProposals(ICorrectionContext context, List resultingCollections) throws CoreException {
ASTNode node= context.getCoveringNode();
Statement statement= ASTResolving.findParentStatement(node);
if (!(statement instanceof ExpressionStatement)) {
return;
}
ExpressionStatement expressionStatement= (ExpressionStatement) statement;
Expression expression= expressionStatement.getExpression();
if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
return; // too confusing and not helpful
}
ITypeBinding typeBinding= expression.resolveTypeBinding();
typeBinding= ASTResolving.normalizeTypeBinding(typeBinding);
if (typeBinding == null) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
AssignToVariableAssistProposal localProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.LOCAL, expressionStatement, typeBinding, 2);
resultingCollections.add(localProposal);
ASTNode type= ASTResolving.findParentType(expression);
if (type != null) {
AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(cu, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, 1);
resultingCollections.add(fieldProposal);
}
}
private void getCatchClauseToThrowsProposals(ICorrectionContext context, List resultingCollections) throws CoreException {
ASTNode node= context.getCoveringNode();
CatchClause catchClause= (CatchClause) ASTResolving.findAncestor(node, ASTNode.CATCH_CLAUSE);
if (catchClause == null) {
return;
}
Type type= catchClause.getException().getType();
if (!type.isSimpleType()) {
return;
}
BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(catchClause);
if (!(bodyDeclaration instanceof MethodDeclaration)) {
return;
}
MethodDeclaration methodDeclaration= (MethodDeclaration) bodyDeclaration;
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
AST ast= methodDeclaration.getAST();
TryStatement tryStatement= (TryStatement) catchClause.getParent();
if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
rewrite.markAsRemoved(catchClause);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.createCopy((ASTNode) statements.get(0), (ASTNode) statements.get(statements.size() - 1));
rewrite.markAsReplaced(tryStatement, placeholder);
} else {
rewrite.markAsRemoved(tryStatement);
}
}
ITypeBinding binding= type.resolveBinding();
if (binding == null || isNotYetThrown(binding, methodDeclaration.thrownExceptions())) {
Name name= ((SimpleType) type).getName();
Name newName= (Name) ASTNode.copySubtree(ast, name);
rewrite.markAsInserted(newName);
methodDeclaration.thrownExceptions().add(newName);
}
String label= CorrectionMessages.getString("QuickAssistProcessor.catchclausetothrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
proposal.ensureNoModifications();
resultingCollections.add(proposal);
}
private boolean isNotYetThrown(ITypeBinding binding, List thrownExcpetions) {
for (int i= 0; i < thrownExcpetions.size(); i++) {
Name name= (Name) thrownExcpetions.get(i);
ITypeBinding elem= (ITypeBinding) name.resolveBinding();
if (elem != null) {
ITypeBinding curr= binding;
if (curr != null && curr != elem) {
curr= curr.getSuperclass();
}
if (curr != null) {
return false;
}
}
}
return true;
}
private void getRenameLocalProposals(ICorrectionContext context, List resultingCollections) throws CoreException {
ASTNode node= context.getCoveringNode();
if (!(node instanceof SimpleName)) {
return;
}
SimpleName name= (SimpleName) node;
IBinding binding= name.resolveBinding();
if (binding == null || binding.getKind() == IBinding.PACKAGE) {
return;
}
LinkedNamesAssistProposal proposal= new LinkedNamesAssistProposal(name);
resultingCollections.add(proposal);
}
private ASTNode getCopyOfInner(ASTRewrite rewrite, Statement statement) {
if (statement.getNodeType() == ASTNode.BLOCK) {
Block block= (Block) statement;
List innerStatements= block.statements();
int nStatements= innerStatements.size();
if (nStatements == 1) {
return rewrite.createCopy((ASTNode) innerStatements.get(0));
} else if (nStatements > 1) {
return rewrite.createCopy((ASTNode) innerStatements.get(0), (ASTNode) innerStatements.get(nStatements - 1));
}
return null;
} else {
return rewrite.createCopy(statement);
}
}
private void getUnWrapProposals(ICorrectionContext context, List resultingCollections) throws CoreException {
ASTNode node= context.getCoveringNode();
if (node == null) {
return;
}
ASTRewrite rewrite= new ASTRewrite(context.getASTRoot());
ASTNode outer= node;
Block block= null;
if (outer.getNodeType() == ASTNode.BLOCK) {
block= (Block) outer;
outer= block.getParent();
}
Statement body= null;
if (outer instanceof IfStatement) {
IfStatement ifStatement= (IfStatement) outer;
Statement elseBlock= ifStatement.getElseStatement();
if (elseBlock == null || ((elseBlock instanceof Block) && ((Block) elseBlock).statements().isEmpty())) {
body= ifStatement.getThenStatement();
}
} else if (outer instanceof WhileStatement) {
body=((WhileStatement) outer).getBody();
} else if (outer instanceof ForStatement) {
body=((ForStatement) outer).getBody();
} else if (outer instanceof DoStatement) {
body=((DoStatement) outer).getBody();
} else if (outer instanceof TryStatement) {
TryStatement tryStatement= (TryStatement) outer;
if (tryStatement.catchClauses().isEmpty()) {
body= tryStatement.getBody();
}
} else if (outer instanceof AnonymousClassDeclaration) {
List decls= ((AnonymousClassDeclaration) outer).bodyDeclarations();
for (int i= 0; i < decls.size(); i++) {
ASTNode elem= (ASTNode) decls.get(i);
if (elem instanceof MethodDeclaration) {
Block curr= ((MethodDeclaration) elem).getBody();
if (curr != null && !curr.statements().isEmpty()) {
if (body != null) {
return;
}
body= curr;
}
} else if (elem instanceof TypeDeclaration) {
return;
}
}
outer= ASTResolving.findParentStatement(outer);
} else if (outer instanceof Block) {
// -> a block in a block
body= block;
outer= block;
}
if (body == null) {
return;
}
ASTNode inner= getCopyOfInner(rewrite, body);
if (inner != null) {
rewrite.markAsReplaced(outer, inner);
String label= CorrectionMessages.getString("QuickAssistProcessor.extrude.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image);
proposal.ensureNoModifications();
resultingCollections.add(proposal);
}
}
}
|
31,389 |
Bug 31389 Remove unused private fields - broken with >1 field/line
|
M5: Declare some variables like this: private int v1, v2; Use v2 in the code. (You might also have to turn on the compiler option to make unused fields a warning not ignored). Press ctrl-1 on the variable declaration line, select "remove". The whole line is removed even though v1 was the only unused variable.
|
resolved fixed
|
ff35e78
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:02:12Z | 2003-02-08T02:06:40Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java
|
package org.eclipse.jdt.ui.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
public class LocalCorrectionsQuickFixTest extends QuickFixTest {
private static final Class THIS= LocalCorrectionsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public LocalCorrectionsQuickFixTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new LocalCorrectionsQuickFixTest("testMissingConstructor"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN__JAVADOC_STUBS, false);
CodeTemplates.getCodeTemplate(CodeTemplates.CATCHBLOCK).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.CONSTRUCTORSTUB).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.METHODSTUB).setPattern("");
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testFieldAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return (new File(\"x.txt\")).separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return File.separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testInheritedAccessOnStatic() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public static void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
pack0.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" b.foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" B.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.A;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" A.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testQualifiedAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" t.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" Thread.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testThisAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" E.goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testThisAccessToStaticField() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" this.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" E.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInVarDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= o;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= (Thread) o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Object th= o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class Container {\n");
buf.append(" public List[] getLists() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("Container.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= (ArrayList[]) c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" List[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInFieldDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= System.currentTimeMillis();\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= (int) System.currentTimeMillis();\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" long time= System.currentTimeMillis();\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= (String) iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return (String[]) list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public Object[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastOnCastExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (ArrayList) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" Cloneable a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo().substring(2);\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionRemoveMoreSpecific() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" try {\n");
buf.append(" this.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionOnSuper() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("import java.io.FileNotFoundException;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() throws FileNotFoundException {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUncaughtExceptionOnThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() throws IOException {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
boolean BUG_25417= true;
public void testUncaughtExceptionDuplicate() throws Exception {
if (BUG_25417) {
return;
}
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class MyException extends Exception {\n");
buf.append("}\n");
pack1.createCompilationUnit("MyException.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException, ParseException, MyException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" try {\n");
buf.append(" m2();\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" } catch (MyException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testMultipleUncaughtExceptions() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2); // 2 uncaught exceptions
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException, ParseException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlock() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockSingle() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockWithFinally() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnimplementedMethods() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public abstract class E implements Inter{\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnimplementedMethods2() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public abstract class InterImpl implements Inter {\n");
buf.append(" protected abstract int[] getMusic() throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("InterImpl.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public abstract class E extends InterImpl {\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("\n");
buf.append(" protected int[] getMusic() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnitializedVariable() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s = 0;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorInDefaultConstructor1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" public F(Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorInDefaultConstructor2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class F {\n");
buf.append(" public F(Runnable runnable) throws IOException {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public F(int i, Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(int i, Runnable runnable) {\n");
buf.append(" super(i, runnable);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) throws IOException {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testNotVisibleConstructorInDefaultConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" private F() {\n");
buf.append(" }\n");
buf.append(" public F(Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnhandledExceptionInDefaultConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class F {\n");
buf.append(" public F() throws IOException{\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E() throws IOException {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateMethod() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append(" \n");
buf.append(" private void foo() {\n");
buf.append(" fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateConstructor() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" private E(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateType() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private class F {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
|
31,389 |
Bug 31389 Remove unused private fields - broken with >1 field/line
|
M5: Declare some variables like this: private int v1, v2; Use v2 in the code. (You might also have to turn on the compiler option to make unused fields a warning not ignored). Press ctrl-1 on the variable declaration line, select "remove". The whole line is removed even though v1 was the only unused variable.
|
resolved fixed
|
ff35e78
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:02:12Z | 2003-02-08T02:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Renaud Waldura <[email protected]> - Access to static proposal
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Selection;
import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSUtil;
import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer;
import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard;
/**
*/
public class LocalCorrectionsSubProcessor {
public static void addCastProposals(ICorrectionContext context, List proposals) throws CoreException {
String[] args= context.getProblemArguments();
if (args.length != 2) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
String castType= args[1];
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (!(selectedNode instanceof Expression)) {
return;
}
Expression nodeToCast= (Expression) selectedNode;
int parentNodeType= selectedNode.getParent().getNodeType();
if (parentNodeType == ASTNode.ASSIGNMENT) {
Assignment assign= (Assignment) selectedNode.getParent();
if (selectedNode.equals(assign.getLeftHandSide())) {
nodeToCast= assign.getRightHandSide();
}
} else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent();
if (selectedNode.equals(frag.getName())) {
nodeToCast= frag.getInitializer();
}
}
{
ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent());
String label;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 1, image); //$NON-NLS-1$
String simpleCastType= proposal.addImport(castType);
if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changecast.description", castType); //$NON-NLS-1$
CastExpression expression= (CastExpression) nodeToCast;
rewrite.markAsReplaced(expression.getType(), rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE));
} else {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", castType); //$NON-NLS-1$
Expression expressionCopy= (Expression) rewrite.createCopy(nodeToCast);
Type typeCopy= (Type) rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE);
CastExpression castExpression= astRoot.getAST().newCastExpression();
castExpression.setExpression(expressionCopy);
castExpression.setType(typeCopy);
rewrite.markAsReplaced(nodeToCast, castExpression);
}
proposal.setDisplayName(label);
proposal.ensureNoModifications();
proposals.add(proposal);
}
// change method return statement to actual type
if (parentNodeType == ASTNode.RETURN_STATEMENT) {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (binding != null && decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
Type newReturnType= ASTResolving.getTypeFromTypeBinding(astRoot.getAST(), binding);
rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", binding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(binding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent();
ASTNode parent= fragment.getParent();
Type type= null;
if (parent instanceof VariableDeclarationStatement) {
VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent;
if (stmt.fragments().size() == 1) {
type= stmt.getType();
}
} else if (parent instanceof FieldDeclaration) {
FieldDeclaration decl= (FieldDeclaration) parent;
if (decl.fragments().size() == 1) {
type= decl.getType();
}
}
if (type != null) {
ImportEdit edit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String typeName= edit.addImport(args[0]);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast_var.description", typeName); //$NON-NLS-1$
ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, type.getStartPosition(), type.getLength(), typeName, 1);
varProposal.getRootTextEdit().add(edit);
proposals.add(varProposal);
}
}
}
public static void addUncaughtExceptionProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
while (selectedNode != null && !(selectedNode instanceof Statement)) {
selectedNode= selectedNode.getParent();
}
if (selectedNode == null) {
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
SurroundWithTryCatchRefactoring refactoring= new SurroundWithTryCatchRefactoring(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null);
refactoring.setSaveChanges(false);
if (refactoring.checkActivationBasics(astRoot, null).isOK()) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 4, image);
proposals.add(proposal);
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl == null) {
return;
}
ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(selectedNode.getStartPosition(), selectedNode.getLength()));
if (uncaughtExceptions.length == 0) {
return;
}
TryStatement surroundingTry= (TryStatement) ASTNodes.getParent(selectedNode, ASTNode.TRY_STATEMENT);
if (surroundingTry != null) {
ASTRewrite rewrite= new ASTRewrite(surroundingTry);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
AST ast= astRoot.getAST();
List catchClauses= surroundingTry.catchClauses();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setName(ast.newSimpleName("e")); //$NON-NLS-1$
var.setType(ast.newSimpleType(name));
CatchClause newClause= ast.newCatchClause();
newClause.setException(var);
rewrite.markAsInserted(newClause);
catchClauses.add(newClause);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (decl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
AST ast= astRoot.getAST();
MethodDeclaration methodDecl= (MethodDeclaration) decl;
List exceptions= methodDecl.thrownExceptions();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
rewrite.markAsInserted(name);
exceptions.add(name);
}
for (int i= 0; i < exceptions.size(); i++) {
Name elem= (Name) exceptions.get(i);
if (canRemove(elem.resolveTypeBinding(), uncaughtExceptions)) {
rewrite.markAsRemoved(elem);
}
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
private static boolean canRemove(ITypeBinding curr, ITypeBinding[] addedExceptions) {
while (curr != null) {
for (int i= 0; i < addedExceptions.length; i++) {
if (curr == addedExceptions[i]) {
return true;
}
}
curr= curr.getSuperclass();
}
return false;
}
public static void addUnreachableCatchProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
if (selectedNode.getNodeType() == ASTNode.BLOCK && selectedNode.getParent().getNodeType() == ASTNode.CATCH_CLAUSE ) {
CatchClause clause= (CatchClause) selectedNode.getParent();
TryStatement tryStatement= (TryStatement) clause.getParent();
ASTRewrite rewrite= new ASTRewrite(tryStatement.getParent());
if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
rewrite.markAsRemoved(clause);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.createCopy((ASTNode) statements.get(0), (ASTNode) statements.get(statements.size() - 1));
rewrite.markAsReplaced(tryStatement, placeholder);
} else {
rewrite.markAsRemoved(tryStatement);
}
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removecatchclause.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addNLSProposals(ICorrectionContext context, List proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 0) {
public void apply(IDocument document) {
try {
NLSRefactoring refactoring= new NLSRefactoring(cu);
ExternalizeWizard wizard= new ExternalizeWizard(refactoring);
String dialogTitle= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.dialog.title"); //$NON-NLS-1$
new RefactoringStarter().activate(refactoring, wizard, JavaPlugin.getActiveWorkbenchShell(), dialogTitle, true);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
};
proposals.add(proposal);
TextEdit edit= NLSUtil.createNLSEdit(cu, context.getOffset());
if (edit != null) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addnon-nls.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
CUCorrectionProposal nlsProposal= new CUCorrectionProposal(label, cu, 6, image);
nlsProposal.getRootTextEdit().add(edit);
proposals.add(nlsProposal);
}
}
/**
* A static field or method is accessed using a non-static reference. E.g.
* <pre>
* File f = new File();
* f.pathSeparator;
* </pre>
* This correction changes <code>f</code> above to <code>File</code>.
*
* @param context
* @param proposals
*/
public static void addInstanceAccessToStaticProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
Expression qualifier= null;
IBinding accessBinding= null;
if (selectedNode instanceof QualifiedName) {
QualifiedName name= (QualifiedName) selectedNode;
qualifier= name.getQualifier();
accessBinding= name.resolveBinding();
} else if (selectedNode instanceof SimpleName) {
ASTNode parent= selectedNode.getParent();
if (parent instanceof FieldAccess) {
FieldAccess fieldAccess= (FieldAccess) parent;
qualifier= fieldAccess.getExpression();
accessBinding= fieldAccess.getName().resolveBinding();
}
} else if (selectedNode instanceof MethodInvocation) {
MethodInvocation methodInvocation= (MethodInvocation) selectedNode;
qualifier= methodInvocation.getExpression();
accessBinding= methodInvocation.getName().resolveBinding();
} else if (selectedNode instanceof FieldAccess) {
FieldAccess fieldAccess= (FieldAccess) selectedNode;
qualifier= fieldAccess.getExpression();
accessBinding= fieldAccess.getName().resolveBinding();
}
ITypeBinding declaringTypeBinding= null;
if (accessBinding != null) {
if (accessBinding instanceof IMethodBinding) {
declaringTypeBinding= ((IMethodBinding) accessBinding).getDeclaringClass();
} else if (accessBinding instanceof IVariableBinding) {
declaringTypeBinding= ((IVariableBinding) accessBinding).getDeclaringClass();
}
if (declaringTypeBinding != null) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(declaringTypeBinding.getName()));
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostaticdefining.description", declaringTypeBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(declaringTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (qualifier != null) {
ITypeBinding instanceTypeBinding= ASTResolving.normalizeTypeBinding(qualifier.resolveTypeBinding());
if (instanceTypeBinding != null && instanceTypeBinding != declaringTypeBinding) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(instanceTypeBinding.getName()));
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostatic.description", instanceTypeBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image);
proposal.addImport(instanceTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
public static void addUnimplementedMethodsProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
ASTNode typeNode= null;
if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent().getNodeType() == ASTNode.TYPE_DECLARATION) {
typeNode= selectedNode.getParent();
} else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
typeNode= creation.getAnonymousClassDeclaration();
}
if (typeNode != null) {
UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 10);
proposals.add(proposal);
}
if (typeNode instanceof TypeDeclaration) {
TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode;
ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeStaticProposal(cu, typeDeclaration);
proposals.add(proposal);
}
}
public static void addUninitializedLocalVariableProposal(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (!(selectedNode instanceof Name)) {
return;
}
Name name= (Name) selectedNode;
IBinding binding= name.resolveBinding();
if (!(binding instanceof IVariableBinding)) {
return;
}
IVariableBinding varBinding= (IVariableBinding) binding;
CompilationUnit astRoot= context.getASTRoot();
ASTNode node= astRoot.findDeclaringNode(binding);
if (node instanceof VariableDeclarationFragment) {
ASTRewrite rewrite= new ASTRewrite(node.getParent());
VariableDeclarationFragment fragment= (VariableDeclarationFragment) node;
if (fragment.getInitializer() != null) {
return;
}
Expression expression= ASTResolving.getInitExpression(astRoot.getAST(), varBinding.getType());
if (expression == null) {
return;
}
fragment.setInitializer(expression);
rewrite.markAsInserted(expression);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.uninitializedvariable.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addConstructorFromSuperclassProposal(ICorrectionContext context, List proposals) {
ASTNode selectedNode= context.getCoveringNode();
if (!(selectedNode instanceof Name && selectedNode.getParent() instanceof TypeDeclaration)) {
return;
}
TypeDeclaration typeDeclaration= (TypeDeclaration) selectedNode.getParent();
ITypeBinding binding= typeDeclaration.resolveBinding();
if (binding == null || binding.getSuperclass() == null) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
IMethodBinding[] methods= binding.getSuperclass().getDeclaredMethods();
for (int i= 0; i < methods.length; i++) {
IMethodBinding curr= methods[i];
if (curr.isConstructor() && !Modifier.isPrivate(curr.getModifiers())) {
proposals.add(new ConstructorFromSuperclassProposal(cu, typeDeclaration, curr, 2));
}
}
}
public static void addUnusedMemberProposal(ICorrectionContext context, List proposals) throws CoreException {
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(selectedNode);
if (declaration != null) {
ASTRewrite rewrite= new ASTRewrite(declaration.getParent());
rewrite.markAsRemoved(declaration);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removeunusedmember.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
|
31,323 |
Bug 31323 QuickAssist only wraps 2 lines
|
build I20030206. 1. Start with the following class public class Test { public static void main(String[] args) { int x = 3; x++; int y=x*x; } } 2. Select the THREE lines of code in the main method. 3. Press ctrl-1 4. If you select any of the quick assists (do, for, if, try, while), only the first TWO lines of the code are inserted. When I selected FOUR lines, still only the first TWO lines were inserted.
|
resolved fixed
|
87ec917
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:21:16Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavaCorrectionAssistant.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.Iterator;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation;
import org.eclipse.jdt.internal.ui.javaeditor.JavaAnnotationIterator;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
public class JavaCorrectionAssistant extends ContentAssistant {
private ITextViewer fViewer;
private IEditorPart fEditor;
private Position fPosition;
/**
* Constructor for CorrectionAssistant.
*/
public JavaCorrectionAssistant(IEditorPart editor) {
super();
Assert.isNotNull(editor);
fEditor= editor;
JavaCorrectionProcessor processor= new JavaCorrectionProcessor(editor);
setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE);
setContentAssistProcessor(processor, JavaPartitionScanner.JAVA_STRING);
enableAutoActivation(false);
enableAutoInsert(false);
setContextInformationPopupOrientation(CONTEXT_INFO_ABOVE);
setInformationControlCreator(getInformationControlCreator());
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
Color c= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager);
setProposalSelectorForeground(c);
c= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager);
setProposalSelectorBackground(c);
}
private IInformationControlCreator getInformationControlCreator() {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, new HTMLTextPresenter());
}
};
}
private static Color getColor(IPreferenceStore store, String key, IColorManager manager) {
RGB rgb= PreferenceConverter.getColor(store, key);
return manager.getColor(rgb);
}
public void install(ITextViewer textViewer) {
super.install(textViewer);
fViewer= textViewer;
}
/**
* Show completions at caret position. If current
* position does not contain quick fixes look for
* next quick fix on same line by moving from left
* to right and restarting at end of line if the
* beginning of the line is reached.
*
* @see org.eclipse.jface.text.contentassist.IContentAssistant#showPossibleCompletions()
*/
public String showPossibleCompletions() {
if (fViewer == null)
// Let superclass deal with this
return super.showPossibleCompletions();
int initalOffset= fViewer.getSelectedRange().x;
int invocationOffset;
int invocationLength;
if (areMultipleLinesSelected()) {
try {
IDocument document= fViewer.getDocument();
IRegion start= document.getLineInformationOfOffset(initalOffset);
invocationOffset= start.getOffset();
int line= document.getLineOfOffset(initalOffset);
if (line + 1 < document.getNumberOfLines()) {
IRegion end= document.getLineInformation(line + 1);
invocationLength= end.getOffset() - invocationOffset + end.getLength();
} else {
invocationLength= start.getLength();
}
} catch (BadLocationException ex) {
invocationOffset= initalOffset;
invocationLength= 0;
}
} else {
invocationOffset= computeOffsetWithCorrection(initalOffset);
invocationLength= 0;
}
if (invocationOffset != -1) {
storePosition();
fViewer.setSelectedRange(invocationOffset, invocationLength);
fViewer.revealRange(invocationOffset, invocationLength);
} else {
fPosition= null;
}
String errorMsg= super.showPossibleCompletions();
return errorMsg;
}
/**
* Find offset which contains corrections.
* Search on same line by moving from left
* to right and restarting at end of line if the
* beginning of the line is reached.
*
* @return an offset where corrections are available or -1 if none
*/
private int computeOffsetWithCorrection(int initalOffset) {
if (fViewer == null || fViewer.getDocument() == null)
return -1;
IRegion lineInfo= null;
try {
lineInfo= fViewer.getDocument().getLineInformationOfOffset(initalOffset);
} catch (BadLocationException ex) {
return -1;
}
int startOffset= lineInfo.getOffset();
int endOffset= startOffset + lineInfo.getLength();
int result= computeOffsetWithCorrection(startOffset, endOffset, initalOffset);
if (result > 0)
return result;
else
return -1;
}
/**
* @return the best matching offset with corrections or -1 if nothing is found
*/
private int computeOffsetWithCorrection(int startOffset, int endOffset, int initialOffset) {
IAnnotationModel model= JavaUI.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput());
int invocationOffset= -1;
int offsetOfFirstProblem= Integer.MAX_VALUE;
Iterator iter= new JavaAnnotationIterator(model, true);
while (iter.hasNext()) {
IJavaAnnotation annot= (IJavaAnnotation)iter.next();
Position pos= model.getPosition((Annotation)annot);
if (isIncluded(pos, startOffset, endOffset)) {
if (JavaCorrectionProcessor.hasCorrections(annot)) {
offsetOfFirstProblem= Math.min(offsetOfFirstProblem, pos.getOffset());
invocationOffset= computeBestOffset(invocationOffset, pos, initialOffset);
if (initialOffset == invocationOffset)
return initialOffset;
}
}
}
if (initialOffset < offsetOfFirstProblem && offsetOfFirstProblem != Integer.MAX_VALUE)
return offsetOfFirstProblem;
else
return invocationOffset;
}
private boolean isIncluded(Position pos, int lineStart, int lineEnd) {
return (pos != null) && (pos.getOffset() >= lineStart && (pos.getOffset() + pos.getLength() <= lineEnd));
}
/**
* Computes and returns the invocation offset given a new
* position, the initial offset and the best invocation offset
* found so far.
* <p>
* The closest offset to the left of the initial offset is the
* best. If there is no offset on the left, the closest on the
* right is the best.</p>
*/
private int computeBestOffset(int invocationOffset, Position pos, int initalOffset) {
int newOffset= pos.offset;
if (newOffset <= initalOffset && initalOffset <= newOffset + pos.length)
return initalOffset;
if (invocationOffset < 0)
return newOffset;
if (newOffset <= initalOffset && invocationOffset >= initalOffset)
return newOffset;
if (newOffset <= initalOffset && invocationOffset < initalOffset)
return Math.max(invocationOffset, newOffset);
if (invocationOffset <= initalOffset)
return invocationOffset;
return Math.max(invocationOffset, newOffset);
}
/*
* @see org.eclipse.jface.text.contentassist.ContentAssistant#possibleCompletionsClosed()
*/
protected void possibleCompletionsClosed() {
super.possibleCompletionsClosed();
restorePosition();
}
/**
* Returns <code>true</code> if one line is completely selected or if multiple lines are selected.
* Being completely selected means that all characters except the new line characters are
* selected.
*
* @return <code>true</code> if one or multiple lines are selected
* @since 2.1
*/
private boolean areMultipleLinesSelected() {
Point s= fViewer.getSelectedRange();
if (s.y == 0)
return false;
try {
IDocument document= fViewer.getDocument();
int startLine= document.getLineOfOffset(s.x);
int endLine= document.getLineOfOffset(s.x + s.y);
IRegion line= document.getLineInformation(startLine);
return startLine != endLine || (s.x == line.getOffset() && s.y == line.getLength());
} catch (BadLocationException x) {
return false;
}
}
private void storePosition() {
int initalOffset= fViewer.getSelectedRange().x;
int length= fViewer.getSelectedRange().y;
fPosition= new Position(initalOffset, length);
}
private void restorePosition() {
if (fPosition != null && !fPosition.isDeleted()) {
fViewer.setSelectedRange(fPosition.offset, fPosition.length);
fViewer.revealRange(fPosition.offset, fPosition.length);
}
fPosition= null;
}
}
|
31,445 |
Bug 31445 QualifiedNameFinder loads Search plug-in
|
Build I20030207 QualifiedNameFinder forces the Search plug-in to be loaded. It should only load the Search plug-in when the user selects to search for qualified strings. Affected refactorings are all those that reference QualifiedNameFinder (through a field).
|
verified fixed
|
e81e606
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:39:07Z | 2003-02-10T12:26:40Z |
org.eclipse.jdt.ui/core
| |
31,445 |
Bug 31445 QualifiedNameFinder loads Search plug-in
|
Build I20030207 QualifiedNameFinder forces the Search plug-in to be loaded. It should only load the Search plug-in when the user selects to search for qualified strings. Affected refactorings are all those that reference QualifiedNameFinder (through a field).
|
verified fixed
|
e81e606
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:39:07Z | 2003-02-10T12:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenamePackageRefactoring.java
| |
31,445 |
Bug 31445 QualifiedNameFinder loads Search plug-in
|
Build I20030207 QualifiedNameFinder forces the Search plug-in to be loaded. It should only load the Search plug-in when the user selects to search for qualified strings. Affected refactorings are all those that reference QualifiedNameFinder (through a field).
|
verified fixed
|
e81e606
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:39:07Z | 2003-02-10T12:26:40Z |
org.eclipse.jdt.ui/core
| |
31,445 |
Bug 31445 QualifiedNameFinder loads Search plug-in
|
Build I20030207 QualifiedNameFinder forces the Search plug-in to be loaded. It should only load the Search plug-in when the user selects to search for qualified strings. Affected refactorings are all those that reference QualifiedNameFinder (through a field).
|
verified fixed
|
e81e606
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:39:07Z | 2003-02-10T12:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameTypeRefactoring.java
| |
31,445 |
Bug 31445 QualifiedNameFinder loads Search plug-in
|
Build I20030207 QualifiedNameFinder forces the Search plug-in to be loaded. It should only load the Search plug-in when the user selects to search for qualified strings. Affected refactorings are all those that reference QualifiedNameFinder (through a field).
|
verified fixed
|
e81e606
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:39:07Z | 2003-02-10T12:26:40Z |
org.eclipse.jdt.ui/core
| |
31,445 |
Bug 31445 QualifiedNameFinder loads Search plug-in
|
Build I20030207 QualifiedNameFinder forces the Search plug-in to be loaded. It should only load the Search plug-in when the user selects to search for qualified strings. Affected refactorings are all those that reference QualifiedNameFinder (through a field).
|
verified fixed
|
e81e606
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:39:07Z | 2003-02-10T12:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/MoveRefactoring.java
| |
31,445 |
Bug 31445 QualifiedNameFinder loads Search plug-in
|
Build I20030207 QualifiedNameFinder forces the Search plug-in to be loaded. It should only load the Search plug-in when the user selects to search for qualified strings. Affected refactorings are all those that reference QualifiedNameFinder (through a field).
|
verified fixed
|
e81e606
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:39:07Z | 2003-02-10T12:26:40Z |
org.eclipse.jdt.ui/core
| |
31,445 |
Bug 31445 QualifiedNameFinder loads Search plug-in
|
Build I20030207 QualifiedNameFinder forces the Search plug-in to be loaded. It should only load the Search plug-in when the user selects to search for qualified strings. Affected refactorings are all those that reference QualifiedNameFinder (through a field).
|
verified fixed
|
e81e606
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:39:07Z | 2003-02-10T12:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/util/QualifiedNameFinder.java
| |
31,445 |
Bug 31445 QualifiedNameFinder loads Search plug-in
|
Build I20030207 QualifiedNameFinder forces the Search plug-in to be loaded. It should only load the Search plug-in when the user selects to search for qualified strings. Affected refactorings are all those that reference QualifiedNameFinder (through a field).
|
verified fixed
|
e81e606
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:39:07Z | 2003-02-10T12:26:40Z |
org.eclipse.jdt.ui/core
| |
31,445 |
Bug 31445 QualifiedNameFinder loads Search plug-in
|
Build I20030207 QualifiedNameFinder forces the Search plug-in to be loaded. It should only load the Search plug-in when the user selects to search for qualified strings. Affected refactorings are all those that reference QualifiedNameFinder (through a field).
|
verified fixed
|
e81e606
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T15:39:07Z | 2003-02-10T12:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/util/QualifiedNameSearchResult.java
| |
31,221 |
Bug 31221 provide filter for closed projects [filters]
|
20030206 closed projects are non-java projects but it does not work the other way so there's no (filter-based) way to remove only closed projects
|
resolved fixed
|
ac4a921
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T16:41:55Z | 2003-02-07T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/ClosedProjectFilter.java
| |
31,221 |
Bug 31221 provide filter for closed projects [filters]
|
20030206 closed projects are non-java projects but it does not work the other way so there's no (filter-based) way to remove only closed projects
|
resolved fixed
|
ac4a921
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T16:41:55Z | 2003-02-07T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/NonJavaElementFilter.java
| |
31,221 |
Bug 31221 provide filter for closed projects [filters]
|
20030206 closed projects are non-java projects but it does not work the other way so there's no (filter-based) way to remove only closed projects
|
resolved fixed
|
ac4a921
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T16:41:55Z | 2003-02-07T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/NonJavaProjectsFilter.java
| |
31,478 |
Bug 31478 Inline actions doen't check if resource is on class path
|
20030206 Title says it all.
|
resolved fixed
|
d03f33a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T17:52:15Z | 2003-02-10T18:00:00Z |
org.eclipse.jdt.ui/ui
| |
31,478 |
Bug 31478 Inline actions doen't check if resource is on class path
|
20030206 Title says it all.
|
resolved fixed
|
d03f33a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T17:52:15Z | 2003-02-10T18:00:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/InlineConstantAction.java
| |
31,478 |
Bug 31478 Inline actions doen't check if resource is on class path
|
20030206 Title says it all.
|
resolved fixed
|
d03f33a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T17:52:15Z | 2003-02-10T18:00:00Z |
org.eclipse.jdt.ui/ui
| |
31,478 |
Bug 31478 Inline actions doen't check if resource is on class path
|
20030206 Title says it all.
|
resolved fixed
|
d03f33a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T17:52:15Z | 2003-02-10T18:00:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/InlineMethodAction.java
| |
31,478 |
Bug 31478 Inline actions doen't check if resource is on class path
|
20030206 Title says it all.
|
resolved fixed
|
d03f33a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T17:52:15Z | 2003-02-10T18:00:00Z |
org.eclipse.jdt.ui/ui
| |
31,478 |
Bug 31478 Inline actions doen't check if resource is on class path
|
20030206 Title says it all.
|
resolved fixed
|
d03f33a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T17:52:15Z | 2003-02-10T18:00:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/RenameTempAction.java
| |
31,478 |
Bug 31478 Inline actions doen't check if resource is on class path
|
20030206 Title says it all.
|
resolved fixed
|
d03f33a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T17:52:15Z | 2003-02-10T18:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/InlineAction.java
|
package org.eclipse.jdt.ui.actions;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.actions.InlineConstantAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.refactoring.code.InlineConstantRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.code.InlineTempRefactoring;
/**
* Inlines a method, local variable or a static final field.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*/
public class InlineAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private final InlineTempAction fInlineTemp;
private final InlineMethodAction fInlineMethod;
private final InlineConstantAction fInlineConstant;
/**
* Creates a new <code>InlineAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public InlineAction(IWorkbenchSite site) {
super(site);
setText(RefactoringMessages.getString("InlineAction.Inline")); //$NON-NLS-1$
fInlineTemp = new InlineTempAction(site);
fInlineMethod = new InlineMethodAction(site);
fInlineConstant = new InlineConstantAction(site);
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public InlineAction(CompilationUnitEditor editor) {
//don't want to call 'this' here - it'd create useless action objects
super(editor.getEditorSite());
setText(RefactoringMessages.getString("InlineAction.Inline")); //$NON-NLS-1$
fEditor= editor;
fInlineTemp = new InlineTempAction(editor);
fInlineMethod = new InlineMethodAction(editor);
fInlineConstant = new InlineConstantAction(editor);
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
}
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.ISelection)
*/
protected void selectionChanged(ISelection selection) {
fInlineConstant.update(selection);
fInlineMethod.update(selection);
fInlineTemp.update(selection);
setEnabled(computeEnablementState());
}
private boolean computeEnablementState() {
return fInlineTemp.isEnabled() || fInlineConstant.isEnabled() || fInlineMethod.isEnabled();
}
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
*/
protected void run(ITextSelection selection) {
ICompilationUnit cu= getCompilationUnit();
if (cu == null)
return;
if (fInlineTemp.isEnabled() && tryInlineTemp(cu, selection))
return;
if (fInlineMethod.isEnabled() && tryInlineMethod(cu, selection))
return;
if (fInlineConstant.isEnabled() && tryInlineConstant(cu, selection))
return;
MessageDialog.openInformation(getShell(), RefactoringMessages.getString("InlineAction.dialog_title"), RefactoringMessages.getString("InlineAction.select")); //$NON-NLS-1$ //$NON-NLS-2$
}
private boolean tryInlineTemp(ICompilationUnit cu, ITextSelection selection){
InlineTempRefactoring inlineTemp= new InlineTempRefactoring(cu, selection.getOffset(), selection.getLength());
if (inlineTemp.checkIfTempSelectedSelected().hasFatalError())
return false;
fInlineTemp.run(selection);
return true;
}
private boolean tryInlineMethod(ICompilationUnit cu, ITextSelection selection){
InlineMethodRefactoring inlineMethodRef= InlineMethodRefactoring.create(
cu, selection.getOffset(), selection.getLength(),
JavaPreferencesSettings.getCodeGenerationSettings());
if (inlineMethodRef == null)
return false;
fInlineMethod.run(selection);
return true;
}
private boolean tryInlineConstant(ICompilationUnit cu, ITextSelection selection){
InlineConstantRefactoring inlineConstantRef= InlineConstantRefactoring.create(
cu, selection.getOffset(), selection.getLength(),
JavaPreferencesSettings.getCodeGenerationSettings());
if (inlineConstantRef == null || inlineConstantRef.checkStaticFinalConstantNameSelected().hasFatalError())
return false;
fInlineConstant.run(selection);
return true;
}
private ICompilationUnit getCompilationUnit() {
return SelectionConverter.getInputAsCompilationUnit(fEditor);
}
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
*/
protected void run(IStructuredSelection selection) {
if (fInlineConstant.isEnabled())
fInlineConstant.run(selection);
else if (fInlineMethod.isEnabled())
fInlineMethod.run(selection);
else
//inline temp will never be enabled on IStructuredSelection
//don't bother running it
Assert.isTrue(! fInlineTemp.isEnabled());
}
}
|
31,478 |
Bug 31478 Inline actions doen't check if resource is on class path
|
20030206 Title says it all.
|
resolved fixed
|
d03f33a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T17:52:15Z | 2003-02-10T18:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/InlineTempAction.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.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.refactoring.InlineTempInputPage;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.corext.refactoring.base.Refactoring;
import org.eclipse.jdt.internal.corext.refactoring.code.InlineTempRefactoring;
/**
* Inlines the value of a local variable at all places where a read reference
* is used.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class InlineTempAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private static final String DIALOG_MESSAGE_TITLE= RefactoringMessages.getString("InlineTempAction.inline_temp");//$NON-NLS-1$
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public InlineTempAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(SelectionConverter.canOperateOn(fEditor));
}
public InlineTempAction(IWorkbenchSite site) {
super(site);
setText(RefactoringMessages.getString("InlineTempAction.label"));//$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(ITextSelection selection) {
//do nothing
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(ITextSelection selection) {
try{
Refactoring refactoring= createRefactoring(SelectionConverter.getInputAsCompilationUnit(fEditor), selection);
new RefactoringStarter().activate(refactoring, createWizard(refactoring), getShell(), DIALOG_MESSAGE_TITLE, false);
} catch (JavaModelException e){
ExceptionHandler.handle(e, DIALOG_MESSAGE_TITLE, RefactoringMessages.getString("NewTextRefactoringAction.exception")); //$NON-NLS-1$
}
}
/**
* Note: this method is for internal use only. Clients should not call this method.
*/
protected Refactoring createRefactoring(ICompilationUnit cunit, ITextSelection selection) {
return new InlineTempRefactoring(cunit, selection.getOffset(), selection.getLength());
}
/**
* Note: this method is for internal use only. Clients should not call this method.
*/
protected RefactoringWizard createWizard(Refactoring refactoring) {
String helpId= IJavaHelpContextIds.INLINE_TEMP_ERROR_WIZARD_PAGE;
String pageTitle= RefactoringMessages.getString("InlineTempAction.inline_temp"); //$NON-NLS-1$
RefactoringWizard result= new RefactoringWizard((InlineTempRefactoring)refactoring, pageTitle, helpId) {
protected void addUserInputPages() {
addPage(new InlineTempInputPage());
}
protected int getMessageLineWidthInChars() {
return 0;
}
};
result.setExpandFirstNode(true);
return result;
}
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
*/
protected void run(IStructuredSelection selection) {
//do nothing
}
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection)
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(false);
}
}
|
31,229 |
Bug 31229 code templates pref page: opening a dialog on typing is unexpected [code manipulation]
|
20030206 when i start typing (or even press an arrow key) in the template preview a dialog pops up it's unexpected and unusual
|
resolved fixed
|
5e51940
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T18:15:39Z | 2003-02-07T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeTemplateBlock.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
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.SourceViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.corext.template.Template;
import org.eclipse.jdt.internal.corext.template.TemplateSet;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
/**
*/
public class CodeTemplateBlock {
private class CodeTemplateAdapter implements ITreeListAdapter, IDialogFieldListener {
private final Object[] NO_CHILDREN= new Object[0];
private CodeTemplates fTemplates;
public CodeTemplateAdapter(CodeTemplates templates) {
fTemplates= templates;
}
public void customButtonPressed(TreeListDialogField field, int index) {
doButtonPressed(index, field.getSelectedElements());
}
public void selectionChanged(TreeListDialogField field) {
List selected= field.getSelectedElements();
field.enableButton(IDX_EDIT, canEdit(selected));
field.enableButton(IDX_EXPORT, !selected.isEmpty());
updateSourceViewerInput(selected);
}
public void doubleClicked(TreeListDialogField field) {
List selected= field.getSelectedElements();
if (canEdit(selected)) {
doButtonPressed(IDX_EDIT, selected);
}
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element == COMMENT_NODE || element == CODE_NODE) {
return getTemplateOfCategory(element == COMMENT_NODE);
}
return NO_CHILDREN;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof Template) {
Template template= (Template) element;
if (template.getName().endsWith(CodeTemplates.COMMENT_SUFFIX)) {
return COMMENT_NODE;
}
return CODE_NODE;
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return (element == COMMENT_NODE || element == CODE_NODE);
}
public void dialogFieldChanged(DialogField field) {
}
}
private static class CodeTemplateLabelProvider extends LabelProvider {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
*/
public Image getImage(Object element) {
if (element == COMMENT_NODE) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_JAVADOCTAG);
}
if (element == CODE_NODE) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPCONT);
}
Template template = (Template) element;
String name= template.getName();
if (CodeTemplates.CATCHBLOCK.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
} else if (CodeTemplates.METHODSTUB.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_MISC_DEFAULT);
} else if (CodeTemplates.CONSTRUCTORSTUB.equals(name)) {
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE));
} else if (CodeTemplates.NEWTYPE.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CUNIT);
} else if (CodeTemplates.TYPECOMMENT.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CLASS);
} else if (CodeTemplates.METHODCOMMENT.equals(name)) {
return JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
} else if (CodeTemplates.OVERRIDECOMMENT.equals(name)) {
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PROTECTED, JavaElementImageDescriptor.OVERRIDES, JavaElementImageProvider.SMALL_SIZE));
} else if (CodeTemplates.CONSTRUCTORCOMMENT.equals(name)) {
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE));
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
*/
public String getText(Object element) {
if (element == COMMENT_NODE || element == CODE_NODE) {
return (String) element;
}
Template template = (Template) element;
String name= template.getName();
if (CodeTemplates.CATCHBLOCK.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.catchblock.label"); //$NON-NLS-1$
} else if (CodeTemplates.METHODSTUB.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.methodstub.label"); //$NON-NLS-1$
} else if (CodeTemplates.CONSTRUCTORSTUB.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.constructorstub.label"); //$NON-NLS-1$
} else if (CodeTemplates.NEWTYPE.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.newtype.label"); //$NON-NLS-1$
} else if (CodeTemplates.TYPECOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.typecomment.label"); //$NON-NLS-1$
} else if (CodeTemplates.METHODCOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.methodcomment.label"); //$NON-NLS-1$
} else if (CodeTemplates.OVERRIDECOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.overridecomment.label"); //$NON-NLS-1$
} else if (CodeTemplates.CONSTRUCTORCOMMENT.equals(name)) {
return PreferencesMessages.getString("CodeTemplateBlock.constructorcomment.label"); //$NON-NLS-1$
}
return template.getDescription();
}
}
private final static int IDX_EDIT= 0;
private final static int IDX_IMPORT= 2;
private final static int IDX_EXPORT= 3;
private final static int IDX_EXPORTALL= 4;
private final static Object COMMENT_NODE= PreferencesMessages.getString("CodeTemplateBlock.templates.comment.node"); //$NON-NLS-1$
private final static Object CODE_NODE= PreferencesMessages.getString("CodeTemplateBlock.templates.code.node"); //$NON-NLS-1$
private static final String PREF_JAVADOC_STUBS= PreferenceConstants.CODEGEN__JAVADOC_STUBS;
private TreeListDialogField fCodeTemplateTree;
private SelectionButtonDialogField fCreateJavaDocComments;
protected CodeTemplates fTemplates;
private PixelConverter fPixelConverter;
private SourceViewer fPatternViewer;
private Control fSWTWidget;
public CodeTemplateBlock() {
fTemplates= CodeTemplates.getInstance();
CodeTemplateAdapter adapter= new CodeTemplateAdapter(fTemplates);
String[] buttonLabels= new String[] {
/* IDX_EDIT*/ PreferencesMessages.getString("CodeTemplateBlock.templates.edit.button"), //$NON-NLS-1$
/* */ null,
/* IDX_IMPORT */ PreferencesMessages.getString("CodeTemplateBlock.templates.import.button"), //$NON-NLS-1$
/* IDX_EXPORT */ PreferencesMessages.getString("CodeTemplateBlock.templates.export.button"), //$NON-NLS-1$
/* IDX_EXPORTALL */ PreferencesMessages.getString("CodeTemplateBlock.templates.exportall.button") //$NON-NLS-1$
};
fCodeTemplateTree= new TreeListDialogField(adapter, buttonLabels, new CodeTemplateLabelProvider());
fCodeTemplateTree.setDialogFieldListener(adapter);
fCodeTemplateTree.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.templates.label")); //$NON-NLS-1$
fCodeTemplateTree.enableButton(IDX_EXPORT, false);
fCodeTemplateTree.enableButton(IDX_EDIT, false);
fCodeTemplateTree.addElement(COMMENT_NODE);
fCodeTemplateTree.addElement(CODE_NODE);
fCreateJavaDocComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateJavaDocComments.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.createcomment.label")); //$NON-NLS-1$
fCreateJavaDocComments.setSelection(PreferenceConstants.getPreferenceStore().getBoolean(PREF_JAVADOC_STUBS));
fCodeTemplateTree.selectFirstElement();
}
protected Control createContents(Composite parent) {
fPixelConverter= new PixelConverter(parent);
fSWTWidget= parent;
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
//layout.marginHeight= 0;
//layout.marginWidth= 0;
layout.numColumns= 2;
composite.setLayout(layout);
fCreateJavaDocComments.doFillIntoGrid(composite, 2);
fCodeTemplateTree.doFillIntoGrid(composite, 3);
LayoutUtil.setHorizontalSpan(fCodeTemplateTree.getLabelControl(null), 2);
LayoutUtil.setHorizontalGrabbing(fCodeTemplateTree.getTreeControl(null));
fPatternViewer= createViewer(composite, 2);
return composite;
}
private Shell getShell() {
if (fSWTWidget != null) {
return fSWTWidget.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private SourceViewer createViewer(Composite parent, int nColumns) {
Label label= new Label(parent, SWT.NONE);
label.setText(PreferencesMessages.getString("CodeTemplateBlock.preview")); //$NON-NLS-1$
GridData data= new GridData();
data.horizontalSpan= nColumns;
label.setLayoutData(data);
SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
IDocument document= new Document();
IDocumentPartitioner partitioner= tools.createDocumentPartitioner();
document.setDocumentPartitioner(partitioner);
partitioner.connect(document);
viewer.configure(new JavaSourceViewerConfiguration(tools, null));
viewer.setEditable(false);
viewer.setDocument(document);
viewer.getTextWidget().setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
viewer.getTextWidget().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
doKeyInSourcePressed();
}
});
Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
viewer.getTextWidget().setFont(font);
Control control= viewer.getControl();
data= new GridData(GridData.FILL_BOTH);
data.horizontalSpan= nColumns;
data.heightHint= fPixelConverter.convertHeightInCharsToPixels(5);
control.setLayoutData(data);
return viewer;
}
protected Template[] getTemplateOfCategory(boolean isComment) {
ArrayList res= new ArrayList();
Template[] templates= fTemplates.getTemplates();
for (int i= 0; i < templates.length; i++) {
Template curr= templates[i];
if (isComment == curr.getName().endsWith(CodeTemplates.COMMENT_SUFFIX)) {
res.add(curr);
}
}
return (Template[]) res.toArray(new Template[res.size()]);
}
protected static boolean canEdit(List selected) {
return selected.size() == 1 && (selected.get(0) instanceof Template);
}
protected void updateSourceViewerInput(List selection) {
if (fPatternViewer == null || fPatternViewer.getTextWidget().isDisposed()) {
return;
}
if (selection.size() == 1 && selection.get(0) instanceof Template) {
Template template= (Template) selection.get(0);
fPatternViewer.getDocument().set(template.getPattern());
} else {
fPatternViewer.getDocument().set(""); //$NON-NLS-1$
}
}
protected void doKeyInSourcePressed() {
List selected= fCodeTemplateTree.getSelectedElements();
if (canEdit(selected)) {
doButtonPressed(IDX_EDIT, selected);
}
}
protected void doButtonPressed(int buttonIndex, List selected) {
if (buttonIndex == IDX_EDIT) {
edit((Template) selected.get(0));
} else if (buttonIndex == IDX_EXPORT) {
export(selected);
} else if (buttonIndex == IDX_EXPORTALL) {
exportAll();
} else {
import_();
}
}
private void edit(Template template) {
Template newTemplate= new Template(template);
EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true, false, new String[0]);
if (dialog.open() == EditTemplateDialog.OK) {
// changed
template.setDescription(newTemplate.getDescription());
template.setPattern(newTemplate.getPattern());
fCodeTemplateTree.refresh(template);
fCodeTemplateTree.selectElements(new StructuredSelection(template));
}
}
private void import_() {
FileDialog dialog= new FileDialog(getShell());
dialog.setText(PreferencesMessages.getString("CodeTemplateBlock.import.title")); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {PreferencesMessages.getString("CodeTemplateBlock.import.extension")}); //$NON-NLS-1$
String path= dialog.open();
if (path != null) {
try {
fTemplates.addFromFile(new File(path), false);
} catch (CoreException e) {
openReadErrorDialog(e);
}
fCodeTemplateTree.refresh();
}
}
private void exportAll() {
export(fTemplates);
}
private void export(List selected) {
TemplateSet templateSet= new TemplateSet(fTemplates.getTemplateTag());
for (int i= 0; i < selected.size(); i++) {
Object curr= selected.get(i);
if (curr instanceof Template) {
addToTemplateSet(templateSet, (Template) curr);
} else {
Template[] templates= getTemplateOfCategory(curr == COMMENT_NODE);
for (int k= 0; k < templates.length; k++) {
addToTemplateSet(templateSet, templates[k]);
}
}
}
export(templateSet);
}
private void addToTemplateSet(TemplateSet set, Template template) {
if (set.getFirstTemplate(template.getName()) == null) {
set.add(template);
}
}
private void export(TemplateSet templateSet) {
FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
dialog.setText(PreferencesMessages.getFormattedString("CodeTemplateBlock.export.title", String.valueOf(templateSet.getTemplates().length))); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {PreferencesMessages.getString("CodeTemplateBlock.export.extension")}); //$NON-NLS-1$
dialog.setFileName(PreferencesMessages.getString("CodeTemplateBlock.export.filename")); //$NON-NLS-1$
String path= dialog.open();
if (path == null)
return;
File file= new File(path);
if (!file.exists() || confirmOverwrite(file)) {
try {
templateSet.saveToFile(file);
} catch (CoreException e) {
JavaPlugin.log(e);
openWriteErrorDialog(e);
}
}
}
private boolean confirmOverwrite(File file) {
return MessageDialog.openQuestion(getShell(),
PreferencesMessages.getString("CodeTemplateBlock.export.exists.title"), //$NON-NLS-1$
PreferencesMessages.getFormattedString("CodeTemplateBlock.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$
}
public void performDefaults() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fCreateJavaDocComments.setSelection(prefs.getDefaultBoolean(PREF_JAVADOC_STUBS));
try {
fTemplates.restoreDefaults();
} catch (CoreException e) {
JavaPlugin.log(e);
openReadErrorDialog(e);
}
// refresh
fCodeTemplateTree.refresh();
}
public boolean performOk(boolean enabled) {
IPreferenceStore prefs= PreferenceConstants.getPreferenceStore();
prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected());
JavaPlugin.getDefault().savePluginPreferences();
try {
fTemplates.save();
} catch (CoreException e) {
JavaPlugin.log(e);
openWriteErrorDialog(e);
}
return true;
}
public void performCancel() {
try {
fTemplates.reset();
} catch (CoreException e) {
openReadErrorDialog(e);
}
}
private void openReadErrorDialog(CoreException e) {
String title= PreferencesMessages.getString("CodeTemplateBlock.error.read.title"); //$NON-NLS-1$
String message= PreferencesMessages.getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
private void openWriteErrorDialog(CoreException e) {
String title= PreferencesMessages.getString("CodeTemplateBlock.error.write.title"); //$NON-NLS-1$
String message= PreferencesMessages.getString("CodeTemplateBlock.error.write.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
}
|
31,307 |
Bug 31307 Preview in "Push Down" flickers distractingly
|
- open "Push Down" dialog for a method that calls a private method - press "Preview" -> You get some errors. - scroll through the errors using the next action in the upper right corner -> the preview is first feeded with the new document and caret offset 0 and then reposition to the error offset. This is distracting. setRedraw should be called around the two method invocations.
|
resolved fixed
|
f31bedd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T18:36:43Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/ui
| |
31,307 |
Bug 31307 Preview in "Push Down" flickers distractingly
|
- open "Push Down" dialog for a method that calls a private method - press "Preview" -> You get some errors. - scroll through the errors using the next action in the upper right corner -> the preview is first feeded with the new document and caret offset 0 and then reposition to the error offset. This is distracting. setRedraw should be called around the two method invocations.
|
resolved fixed
|
f31bedd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T18:36:43Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/SourceContextViewer.java
| |
31,088 |
Bug 31088 member sort pref page - incorrect message
|
20030206 it should say that this order is used by the Sort Members action otherwise people will have no clue in order order that action will sort their files
|
resolved fixed
|
6da3023
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T18:52:34Z | 2003-02-06T14:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/MembersOrderPreferencePage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
public class MembersOrderPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String ALL_ENTRIES= "T,SI,SF,SM,I,F,C,M"; //$NON-NLS-1$
private static final String PREF_OUTLINE_SORT_OPTION= PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER;
public static final String CONSTRUCTORS= "C"; //$NON-NLS-1$
public static final String FIELDS= "F"; //$NON-NLS-1$
public static final String METHODS= "M"; //$NON-NLS-1$
public static final String STATIC_METHODS= "SM"; //$NON-NLS-1$
public static final String STATIC_FIELDS= "SF"; //$NON-NLS-1$
public static final String INIT= "I"; //$NON-NLS-1$
public static final String STATIC_INIT= "SI"; //$NON-NLS-1$
public static final String TYPES= "T"; //$NON-NLS-1$
private ListDialogField fSortOrderList;
private final int DEFAULT= 0;
private static List getSortOrderList(String string) {
StringTokenizer tokenizer= new StringTokenizer(string, ","); //$NON-NLS-1$
List entries= new ArrayList();
for (int i= 0; tokenizer.hasMoreTokens(); i++) {
String token= tokenizer.nextToken();
entries.add(token);
}
return entries;
}
private static boolean isValidEntries(List entries) {
StringTokenizer tokenizer= new StringTokenizer(ALL_ENTRIES, ","); //$NON-NLS-1$
int i= 0;
for (; tokenizer.hasMoreTokens(); i++) {
String token= tokenizer.nextToken();
if (!entries.contains(token))
return false;
}
return i == entries.size();
}
public MembersOrderPreferencePage() {
//set the preference store
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
String string= getPreferenceStore().getString(PREF_OUTLINE_SORT_OPTION);
String upLabel= PreferencesMessages.getString("MembersOrderPreferencePage.button.up"); //$NON-NLS-1$
String downLabel= PreferencesMessages.getString("MembersOrderPreferencePage.button.down"); //$NON-NLS-1$
String[] buttonlabels= new String[] { upLabel, downLabel };
fSortOrderList= new ListDialogField(null, buttonlabels, new MemberSortLabelProvider());
fSortOrderList.setDownButtonIndex(1);
fSortOrderList.setUpButtonIndex(0);
//validate entries stored in store, false get defaults
List entries= getSortOrderList(string);
if (!isValidEntries(entries)) {
string= JavaPlugin.getDefault().getPreferenceStore().getDefaultString(PREF_OUTLINE_SORT_OPTION);
entries= getSortOrderList(string);
}
fSortOrderList.setElements(entries);
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.SORT_ORDER_PREFERENCE_PAGE);
}
/*
* @see org.eclipse.jface.preference.PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
GridData data= new GridData();
data.verticalAlignment= GridData.FILL;
data.horizontalAlignment= GridData.FILL_HORIZONTAL;
composite.setLayoutData(data);
createSortOrderListDialogField(composite, 3);
return composite;
}
private void createSortOrderListDialogField(Composite composite, int span) {
Label sortLabel= new Label(composite, SWT.NONE);
sortLabel.setText(PreferencesMessages.getString("MembersOrderPreferencePage.label.description")); //$NON-NLS-1$
GridData gridData= new GridData();
gridData.horizontalAlignment= GridData.FILL_HORIZONTAL;
gridData.horizontalSpan= span;
sortLabel.setLayoutData(gridData);
fSortOrderList.doFillIntoGrid(composite, span);
LayoutUtil.setHorizontalGrabbing(fSortOrderList.getListControl(null));
}
/*
* @see org.eclipse.ui.IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/*
* @see org.eclipse.jface.preference.PreferencePage#performDefaults()
*/
protected void performDefaults() {
String string= getPreferenceStore().getDefaultString(PREF_OUTLINE_SORT_OPTION);
fSortOrderList.setElements(getSortOrderList(string));
}
/*
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
//reorders elements in the Outline based on selection
public boolean performOk() {
//update outline view
//save preferences
IPreferenceStore store= getPreferenceStore();
StringBuffer buf= new StringBuffer();
List curr= fSortOrderList.getElements();
for (Iterator iter= curr.iterator(); iter.hasNext();) {
String s= (String) iter.next();
buf.append(s);
buf.append(',');
}
store.setValue(PREF_OUTLINE_SORT_OPTION, buf.toString());
JavaPlugin.getDefault().savePluginPreferences();
return true;
}
private class MemberSortLabelProvider extends LabelProvider {
public MemberSortLabelProvider() {
}
/*
* @see org.eclipse.jface.viewers.ILabelProvider#getText(Object)
*/
public String getText(Object element) {
if (element instanceof String) {
String s= (String) element;
if (s.equals(FIELDS)) {
return PreferencesMessages.getString("MembersOrderPreferencePage.fields.label"); //$NON-NLS-1$
} else if (s.equals(CONSTRUCTORS)) {
return PreferencesMessages.getString("MembersOrderPreferencePage.constructors.label"); //$NON-NLS-1$
} else if (s.equals(METHODS)) {
return PreferencesMessages.getString("MembersOrderPreferencePage.methods.label"); //$NON-NLS-1$
} else if (s.equals(STATIC_FIELDS)) {
return PreferencesMessages.getString("MembersOrderPreferencePage.staticfields.label"); //$NON-NLS-1$
} else if (s.equals(STATIC_METHODS)) {
return PreferencesMessages.getString("MembersOrderPreferencePage.staticmethods.label"); //$NON-NLS-1$
} else if (s.equals(INIT)) {
return PreferencesMessages.getString("MembersOrderPreferencePage.initialisers.label"); //$NON-NLS-1$
} else if (s.equals(STATIC_INIT)) {
return PreferencesMessages.getString("MembersOrderPreferencePage.staticinitialisers.label"); //$NON-NLS-1$
} else if (s.equals(TYPES)) {
return PreferencesMessages.getString("MembersOrderPreferencePage.types.label"); //$NON-NLS-1$
}
}
return ""; //$NON-NLS-1$
}
/*
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(Object)
*/
public Image getImage(Object element) {
//access to image registry
ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry();
ImageDescriptor descriptor= null;
if (element instanceof String) {
String s= (String) element;
if (s.equals(FIELDS)) {
//0 will give the default field image
descriptor= JavaElementImageProvider.getFieldImageDescriptor(false, Flags.AccPublic);
} else if (s.equals(CONSTRUCTORS)) {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, DEFAULT);
//add a constructor adornment to the image descriptor
descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE);
} else if (s.equals(METHODS)) {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, Flags.AccPublic);
} else if (s.equals(STATIC_FIELDS)) {
descriptor= JavaElementImageProvider.getFieldImageDescriptor(false, Flags.AccPublic);
//add a constructor adornment to the image descriptor
descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
} else if (s.equals(STATIC_METHODS)) {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, Flags.AccPublic);
//add a constructor adornment to the image descriptor
descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
} else if (s.equals(INIT)) {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, DEFAULT);
} else if (s.equals(STATIC_INIT)) {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, DEFAULT);
descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
} else if (s.equals(TYPES)) {
descriptor= JavaElementImageProvider.getTypeImageDescriptor(false, true, Flags.AccPublic);
} else {
descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, DEFAULT);
}
return registry.get(descriptor);
}
return null;
}
}
}
|
31,226 |
Bug 31226 Add Constructor Quick fix: Method body stub used, not constructor
|
20030206 Add Constructor Quick fix: Method body stub used, not constructor 1. quick fix on B import java.rmi.server.Operation; public class B extends Operation { }
|
resolved fixed
|
a5d3245
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T18:57:30Z | 2003-02-07T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ConstructorFromSuperclassProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMethod;
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.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.Javadoc;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.SuperConstructorInvocation;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Binding2JavaModel;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
public class ConstructorFromSuperclassProposal extends ASTRewriteCorrectionProposal {
private TypeDeclaration fTypeNode;
private IMethodBinding fSuperConstructor;
public ConstructorFromSuperclassProposal(ICompilationUnit cu, TypeDeclaration typeNode, IMethodBinding superConstructor, int relevance) {
super(null, cu, null, relevance, null);
fTypeNode= typeNode;
fSuperConstructor= superConstructor;
}
/**
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getImage()
*/
public Image getImage() {
return JavaPlugin.getImageDescriptorRegistry().get(
new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE)
);
}
/**
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString()
*/
public String getDisplayString() {
StringBuffer buf= new StringBuffer();
buf.append(fTypeNode.getName().getIdentifier());
buf.append('(');
if (fSuperConstructor != null) {
ITypeBinding[] paramTypes= fSuperConstructor.getParameterTypes();
for (int i= 0; i < paramTypes.length; i++) {
if (i > 0) {
buf.append(',');
}
buf.append(paramTypes[i].getName());
}
}
buf.append(')');
return CorrectionMessages.getFormattedString("ConstructorFromSuperclassProposal.description", buf.toString()); //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
*/
protected ASTRewrite getRewrite() throws CoreException {
ASTRewrite rewrite= new ASTRewrite(fTypeNode);
AST ast= fTypeNode.getAST();
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (!settings.createComments) {
settings= null;
}
MethodDeclaration newMethodDecl= createNewMethodDeclaration(ast, fSuperConstructor, rewrite, settings);
rewrite.markAsInserted(newMethodDecl);
fTypeNode.bodyDeclarations().add(0, newMethodDecl);
return rewrite;
}
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, CodeGenerationSettings commentSettings) throws CoreException {
String name= fTypeNode.getName().getIdentifier();
MethodDeclaration decl= ast.newMethodDeclaration();
decl.setConstructor(true);
decl.setName(ast.newSimpleName(name));
Block body= ast.newBlock();
decl.setBody(body);
String bodyStatement= ""; //$NON-NLS-1$
if (binding == null) {
decl.setModifiers(Modifier.PUBLIC);
} else {
decl.setModifiers(binding.getModifiers());
List parameters= decl.parameters();
ITypeBinding[] params= binding.getParameterTypes();
String[] paramNames= getArgumentNames(binding);
for (int i= 0; i < params.length; i++) {
ITypeBinding curr= params[i];
addImport(curr);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setType(ASTResolving.getTypeFromTypeBinding(ast, curr));
var.setName(ast.newSimpleName(paramNames[i]));
parameters.add(var);
}
List thrownExceptions= decl.thrownExceptions();
ITypeBinding[] excTypes= binding.getExceptionTypes();
for (int i= 0; i < excTypes.length; i++) {
ITypeBinding curr= excTypes[i];
addImport(curr);
thrownExceptions.add(ast.newSimpleName(curr.getName())); // can only be single type, no array
}
SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();
List arguments= invocation.arguments();
for (int i= 0; i < paramNames.length; i++) {
arguments.add(ast.newSimpleName(paramNames[i]));
}
bodyStatement= ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'));
}
String placeHolder= StubUtility.getMethodBodyContent(false, getCompilationUnit().getJavaProject(), name, name, bodyStatement);
if (placeHolder != null) {
ASTNode todoNode= rewrite.createPlaceholder(placeHolder, ASTRewrite.STATEMENT);
body.statements().add(todoNode);
}
if (commentSettings != null) {
String string= StubUtility.getMethodComment(getCompilationUnit(), name, decl, null);
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createPlaceholder(string, ASTRewrite.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private String[] getArgumentNames(IMethodBinding binding) {
int nParams= binding.getParameterTypes().length;
if (nParams > 0) {
try {
IMethod method= Binding2JavaModel.find(binding, getCompilationUnit().getJavaProject());
if (method != null) {
return method.getParameterNames();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
String[] names= new String[nParams];
for (int i= 0; i < names.length; i++) {
names[i]= "arg" + i; //$NON-NLS-1$
}
return names;
}
}
|
31,228 |
Bug 31228 "Sort members" and markers
| null |
resolved fixed
|
f5fa7dc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-10T19:22:22Z | 2003-02-07T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/SortMembersAction.java
|
/*******************************************************************************
* Copyright (c) 2003 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.SortMembersOperation;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* Sorts the members of a compilation unit with the sort order as specified in
* the Sort Order preference page.
* <p>
* The action will open the parent compilation unit in a Java editor. The result
* is unsaved, so the user can decide if the changes are acceptable.
* <p>
* The action is applicable to structured selections containing a single
* <code>ICompilationUnit</code> or top level <code>IType</code> in a
* compilation unit.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.1
*/
public class SortMembersAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
/**
* Creates a new <code>SortMembersAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public SortMembersAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("SortMembersAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("SortMembersAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("SortMembersAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.SORT_MEMBERS_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public SortMembersAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(checkEnabledEditor());
}
private boolean checkEnabledEditor() {
return fEditor != null && SelectionConverter.canOperateOn(fEditor);
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
boolean enabled= false;
try {
enabled= getSelectedCompilationUnit(selection) != null;
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
}
setEnabled(enabled);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
Shell shell= getShell();
try {
ICompilationUnit cu= getSelectedCompilationUnit(selection);
if (cu == null || !ElementValidator.check(cu, getShell(), getDialogTitle(), false)) {
return;
}
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(cu);
if (editor != null) {
run(shell, JavaModelUtil.toWorkingCopy(cu), editor);
}
} catch (CoreException e) {
ExceptionHandler.handle(e, shell, getDialogTitle(), null);
}
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(ITextSelection selection) {
Shell shell= getShell();
IJavaElement input= SelectionConverter.getInput(fEditor);
if (input instanceof ICompilationUnit && ElementValidator.check(input, getShell(), getDialogTitle(), true))
run(shell, (ICompilationUnit) input, fEditor);
else
MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("SortMembersAction.not_applicable")); //$NON-NLS-1$
}
//---- Helpers -------------------------------------------------------------------
private void run(Shell shell, ICompilationUnit cu, IEditorPart editor) {
SortMembersOperation op= new SortMembersOperation(cu, null);
try {
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
context.run(false, true, new WorkbenchRunnableAdapter(op));
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, shell, getDialogTitle(), null);
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
}
private ICompilationUnit getSelectedCompilationUnit(IStructuredSelection selection) throws JavaModelException {
if (selection.size() == 1) {
Object element= selection.getFirstElement();
if (element instanceof ICompilationUnit) {
return (ICompilationUnit) element;
} else if (element instanceof IType) {
IType type= (IType) element;
if (type.getParent() instanceof ICompilationUnit) { // only top level types
return type.getCompilationUnit();
}
}
}
return null;
}
private String getDialogTitle() {
return ActionMessages.getString("SortMembersAction.error.title"); //$NON-NLS-1$
}
}
|
31,252 |
Bug 31252 Change Method signature refactoring: Message is strangely located
|
20030206 1. When opening the refactoring on a method to modify the method signature, a label at the bottom of the dialog says 'Specify the new order...' This message is strangely located. The indent is confusing. I suggest that the StatusDialog is used, (where the message background is different, and that the message gets an 'Info' image.
|
resolved fixed
|
393531c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T10:05:11Z | 2003-02-07T12:13:20Z |
org.eclipse.jdt.ui/ui
| |
31,252 |
Bug 31252 Change Method signature refactoring: Message is strangely located
|
20030206 1. When opening the refactoring on a method to modify the method signature, a label at the bottom of the dialog says 'Specify the new order...' This message is strangely located. The indent is confusing. I suggest that the StatusDialog is used, (where the message background is different, and that the message gets an 'Info' image.
|
resolved fixed
|
393531c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T10:05:11Z | 2003-02-07T12:13:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringWizardDialog2.java
| |
31,215 |
Bug 31215 close project enabled on a closed project
|
20030206 create a non-java project in package explorer close it from the context menu open the context menu again - both 'open project' and 'close project' actions are enabled
|
verified fixed
|
c9ea9f2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T10:20:52Z | 2003-02-07T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/ProjectActionGroup.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.core.resources.ResourcesPlugin;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.CloseResourceAction;
import org.eclipse.ui.actions.OpenResourceAction;
import org.eclipse.jdt.ui.IContextMenuConstants;
/**
* Adds actions to open and close a project to the global menu bar.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class ProjectActionGroup extends ActionGroup {
private IWorkbenchSite fSite;
private OpenResourceAction fOpenAction;
private CloseResourceAction fCloseAction;
/**
* Creates a new <code>ProjectActionGroup</code>. The group requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param part the view part that owns this action group
*/
public ProjectActionGroup(IViewPart part) {
fSite = part.getSite();
Shell shell= fSite.getShell();
ISelectionProvider provider= fSite.getSelectionProvider();
ISelection selection= provider.getSelection();
fOpenAction= new OpenResourceAction(shell);
fCloseAction= new CloseResourceAction(shell);
if (selection instanceof IStructuredSelection) {
IStructuredSelection s= (IStructuredSelection)selection;
fOpenAction.selectionChanged(s);
fCloseAction.selectionChanged(s);
}
provider.addSelectionChangedListener(fOpenAction);
provider.addSelectionChangedListener(fCloseAction);
ResourcesPlugin.getWorkspace().addResourceChangeListener(fOpenAction);
}
/* (non-Javadoc)
* Method declared in ActionGroup
*/
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.CLOSE_PROJECT, fCloseAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.OPEN_PROJECT, fOpenAction);
}
/* (non-Javadoc)
* Method declared in ActionGroup
*/
public void fillContextMenu(IMenuManager menu) {
super.fillContextMenu(menu);
if (fOpenAction.isEnabled())
menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fOpenAction);
if (fCloseAction.isEnabled())
menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fCloseAction);
}
/*
* @see ActionGroup#dispose()
*/
public void dispose() {
ISelectionProvider provider= fSite.getSelectionProvider();
provider.removeSelectionChangedListener(fOpenAction);
provider.removeSelectionChangedListener(fCloseAction);
ResourcesPlugin.getWorkspace().removeResourceChangeListener(fOpenAction);
super.dispose();
}
}
|
31,241 |
Bug 31241 Unsufficient progress reporting when renaming a linked source folder
|
I20030206 - create a project - create a source folder ui and link it to the ui folder of org.eclipse.jdt.ui observe: you get lots of error messages due to missing imports - now rename the source folder to ui2 Observe: you get a progress bar in the application window. The progress gos to 95% really quick and then states there for 40 seconds. Furthermore no tasks are presented.
|
resolved fixed
|
d1b9f09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T10:42:51Z | 2003-02-07T12:13:20Z |
org.eclipse.jdt.ui/ui
| |
31,241 |
Bug 31241 Unsufficient progress reporting when renaming a linked source folder
|
I20030206 - create a project - create a source folder ui and link it to the ui folder of org.eclipse.jdt.ui observe: you get lots of error messages due to missing imports - now rename the source folder to ui2 Observe: you get a progress bar in the application window. The progress gos to 95% really quick and then states there for 40 seconds. Furthermore no tasks are presented.
|
resolved fixed
|
d1b9f09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T10:42:51Z | 2003-02-07T12:13:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/RefactoringStarter.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.