How to use IStructuredSelection get multi selected projects? - java

I try to develop news eclipse tool (eclipse plugin), so I want to get multi selected projects from workspace. I try getFirstElement(), but it`s only get first selected projects.
Thank you very much
Here is some codes:
public Object execute(ExecutionEvent event) throws ExecutionException {
part = HandlerUtil.getActivePart(event);
window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
selection = HandlerUtil.getActiveMenuSelection(event);
if (selection instanceof IStructuredSelection) {
IStructuredSelection structured = (IStructuredSelection)selection;
IJavaProject project = null;
Object elem = structured.getFirstElement();
if (elem instanceof IJavaProject) {
project = (IJavaProject)elem;
} else if (elem instanceof IProject) {
project = (IJavaProject)JavaCore.create((IProject)elem);
}
if (project != null) {
}
}
return null;
}

As its name suggests IStructuredSelection.getFirstElement() only gives you the first selection.
To get all the selections use any of the iterator(), toArray() or toList() methods.
For example:
IStructuredSelection structured = (IStructuredSelection)selection;
for (Object elem : structured.toList()) {
IJavaProject project = null;
if (elem instanceof IJavaProject) {
project = (IJavaProject)elem;
} else if (elem instanceof IProject) {
project = (IJavaProject)JavaCore.create((IProject)elem);
}
if (project != null) {
... your code
}
}

Related

How can i conditionally prevent a user from navigating to a different view/part in eclipse E4 RCP application?

I am trying to prevent a user from going to a different view/part in a perspective of eclipse E4 application.When i am trying to navigate to the same perspective and view,I am facing a stackOverflow exception due to recursively calling the showPart method by the framework.
NavigationHelper.showPerspective(CommonConstants.PERSPECTIVE1, getEclipseContext());
NavigationHelper.showPart(CommonConstants.VIEW1, getEclipseContext());
NavigationHelper.showPart(CommonConstants.VIEW2, getEclipseContext());
My showPart method lokks like this,
public static boolean showPart(String partId, IEclipseContext eclipseContext) {
logger.debug("showPart::STARTED::" + partId);
if (null == eclipseContext) {
eclipseContext = getEclipseContext();
}
if (Model.getInstance().hasDataChanged()) {
if (partId.equalsIgnoreCase(CommonConstants.VIEW1)
|| partId.equalsIgnoreCase(CommonConstants.VIEW2)) {
isNavigationSuccessful = true;
} else {
isNavigationSuccessful = false;
Navigation.showWarning();
}
}
if (isNavigationSuccessful) {
findPartAndActivate(partId, eclipseContext, true);
}
logger.debug("isNavigationSuccessful = " + isNavigationSuccessful);
logger.debug("showPart::END::" + partId);
return isNavigationSuccessful;
}
The findPartAndActivate looks like this
private static boolean findPartAndActivate(String partId, IEclipseContext eclipseContext, boolean giveFocus) {
MTrimmedWindow applicationWindow = ((MTrimmedWindow) ((MApplication) eclipseContext.get(MApplication.class))
.getChildren().get(0));
IEclipseContext currentContext = applicationWindow.getContext();
EPartService partService = currentContext.get(EPartService.class);
EModelService modelService = currentContext.get(EModelService.class);
MPart part = (MPart) modelService.find(partId, eclipseContext.get(MApplication.class).getChildren().get(0));
partService.activate(part, giveFocus);
return true;
}
The partDeactivated is invoked,once a user leaves from a part/View
public void partDeactivated(#Active MPart part) {
if (partInstance.getElementId() != part.getElementId()) {
return;
}
if (transactionButton != null && !transactionButton.isDisposed() && transactionButton.isEnabled()
&& isTransactionCompleted && NavigationHelper.getEditableViewInstance() != null && !partDeactivateFlag) {
doTransaction();
partDeactivateFlag = true;
}
if (Navigation.isPerspective()) {
if (EModel.getInstance().hasDataChanged()/*&& !Model.getInstance().isSwitchFlag()*/) {
System.out.println("Changes");
//Model.getInstance().setSwitchFlag(true);
//partDeactivateFlag = true;
NavigationHelper.showPerspective(CommonConstants.PERSPECTIVE1, getEclipseContext());
NavigationHelper.showPart(CommonConstants.VIEW1, getEclipseContext());
NavigationHelper.showPart(CommonConstants.VIEW2, getEclipseContext());
}
}
viewDeactivated();
}
};
java.lang.StackOverflowError : null
org.eclipse.e4.ui.workbench.modeling.ElementMatcher.select(ElementMatcher.java:71)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:182)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:317)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:271)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:271)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:271)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:251)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElementsRecursive(ModelServiceImpl.java:271)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElements(ModelServiceImpl.java:428)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElements(ModelServiceImpl.java:409)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.findElements(ModelServiceImpl.java:414)
org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.find(ModelServiceImpl.java:448)
This is the StackOverflow trace..
How can I solve this..?
Well the stack trace shows this is an error in your code. You are running NavigationHelper.showPart in a part deactivated listener, but your code is causing another part deactivate event which calls the deactivate listener again which calls showPart again and so on.
You can't try to show a different part in the the part deactivate listener directly.
One possibility is to use Display.asyncExec in the part deactivate listener to run the showPart after the deactivate event has completed.

How to select a specific node in a TreeViewer?

I built a treeviewer for a specific project, but now I need to select a specific item/node in this treeviewer.
To build the treeviewer, I did this:
viewer = new TreeViewer(composite);
viewer.getTree().setLayoutData(gridData);
viewer.setContentProvider(new FileTreeContentProvider());
viewer.setLabelProvider(new FileTreeLabelProvider());
viewer.setInput(ResourcesPlugin.getWorkspace().getRoot().getProject(folderName.getText()));
viewer.expandAll();
Until here, everything is ok, but now, I don't know how to use listeners to do something when I select a specific item in my tree. Any idea? Thanks.
Edit: I got it!
viewer.addSelectionChangedListener(
new ISelectionChangedListener(){
public void selectionChanged(SelectionChangedEvent event) {
if(event.getSelection() instanceof IStructuredSelection) {
IStructuredSelection selection = (IStructuredSelection)event.getSelection();
Object o = selection.getFirstElement();
if (o instanceof IFile){
IFile file = (IFile)o;
}else {
//what ?
}
}
}
}
);
This is an excellent first step but there is even a better way which is more in the heart and soul of Eclipse.
Your code is listening to local changes but you want to make your code extendable so that other plugins in Eclipse are also notified when someone selects something in your viewer.
Eclipse 4 API
For this to happen you inject ESelectionService into your part and then forward the selection to the workbench by using the listener you already provided.
#Inject
private ESelectionService selectionService;
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
// set the selection to the service
selectionService.setSelection(
selection.size() == 1 ? selection.getFirstElement() : selection.toArray());
Then, to catch your own selection:
#Inject
void setSelection(#Optional #Named(IServiceConstants.ACTIVE_SELECTION) IFile pFile) {
if (pFile == null) {
//what ?
} else {
// magic!
}
}
Eclipse 3 API
For this to happen you have to register your viewer with the selection framework. Add this in the createPartControl method of the part where you have added your viewer:
getSite().setSelectionProvider(viewer);
Then, to catch your own selection:
getSite().getPage().addPostSelectionListener(this); // Implement ISelectionListener
References: https://wiki.eclipse.org/E4/EAS/Selection

How to get selected project from Navigator view in Eclipse?

I'm using to get the selected project from Project Explorer an ISelection that focuses the Project Explorer window:
IProject project = null;
ISelectionService selectionService=PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
ISelection selection = selectionService.getSelection("org.eclipse.jdt.ui.ProjectExplorer");
if(selection instanceof IStructuredSelection) {
Object element = ((IStructuredSelection)selection).getFirstElement();
if (element instanceof IResource) {
project= ((IResource)element).getProject();
}
else if (element instanceof IPackageFragmentRoot) {
IJavaProject jProject = ((IPackageFragmentRoot)element).getJavaProject();
project = jProject.getProject();
}
else if (element instanceof IJavaElement) {
IJavaProject jProject= ((IJavaElement)element).getJavaProject();
project = jProject.getProject();
}
I need to focus the selection on Navigator, I tried org.eclipse.jdt.internal.ui.Navigator in getSelection method but it didn't worked....
How to get the selected project from Navigator view ?
The id for the Navigator view is:
org.eclipse.ui.views.ResourceNavigator
For the Project Explorer view it is
org.eclipse.ui.navigator.ProjectExplorer

Instance Of Selected java file is always returning null -- eclipse plugin development

I want to get the instance of the Selected java file into eclipse.
When I googled, I got the below code.
IWorkbenchWindow window = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
if (window != null) {
IStructuredSelection selection = (IStructuredSelection) window
.getSelectionService().getSelection();
if (selection instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) selection;
Object obj = ssel.getFirstElement();
IFile file = (IFile) Platform.getAdapterManager().getAdapter(obj, IFile.class);
if (file == null) {
if (obj instanceof IAdaptable) {
file = (IFile) ((IAdaptable) obj).getAdapter(IFile.class);
}
}
if (file != null) {
// do something
}
}
}
But this code is always returning null for file. Kindly help.
It has got the correct values till obj. But it cannot make IFile object.

Get projects to be build in eclipse

In the eclipse toolbar when you mouse over the build button it comes up with a tooltip
saying which projects are currently selected to be build. Is there any way to get that information in my eclipse plugin? I thought about implementing something with ISelectionListener to keep tracking which projects are selected but there is no reason to do that if I can get them from the same place the build button is taking them.
Ok the answer to this question was to create my own ISelectionListener.
#Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
Object[] allselections= null;
selectedProjects.clear();
// TODO Auto-generated method stub
if(selection instanceof IStructuredSelection) {
allselections = ((IStructuredSelection)selection).toArray();
for(Object element: allselections){
if (element instanceof IResource) {
selectedProjects.add(((IResource)element).getProject());
} else if (element instanceof IAdaptable) {
IResource resource = null;
IAdaptable a = (IAdaptable)element;
resource = (IResource)a.getAdapter(IResource.class);
selectedProjects.add(resource.getProject());
}
}
}
};

Categories

Resources