Get project in Eclipse plugin without having an open editor - eclipse-plugin

In a Eclipse plugin it's easy to get the current project(IProject) if there's an editor opened, you just need to use this snippet:
IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
IFileEditorInput input = (IFileEditorInput)editor.getEditorInput();
IFile file = input.getFile();
IProject project = file.getProject();
But, is there a way to get the project if I don't have any kind of file opened in the editor?, i.e: imagine that you have a plugin that adds an option when you right click a project, and if you click this option a dialog window is launched, how can I print the project name in this dialog?

For menu items and the like which use a 'command' with a 'handler' you can use code in the handler which is something like:
public class CommandHandler extends AbstractHandler
{
#Override
public Object execute(ExecutionEvent event) throws ExecutionException
{
ISelection sel = HandlerUtil.getCurrentSelection(event);
if (sel instanceof IStructuredSelection)
{
Object selected = ((IStructuredSelection)sel).getFirstElement();
IResource resource = (IResource)Platform.getAdapterManager().getAdapter(selected, IResource.class);
if (resource != null)
{
IProject project = resource.getProject();
...
}
}
return null;
}
}

What do you mean by "The current project"? Getting a specific project will always require some way of uniquely identifying that specific project.
If by current project you mean that the project is open, then that's not a good criterion for uniqueness (in the general case), since multiple projects can be open at the same time.
A guarantee of uniquely defining a project is by getting a reference to a resource contained by that project. For example, this can be done through the editor input, as you state, or trough a selection, as greg pointed out.
If you have the project's name, then you can use IWorkspaceRoot#getProject(String), but I assume that's not the case. Still, for completeness:
ResourcesPlugin.getWorkspace().getRoot().getProject("MyProject");
You could also get a list of all projects, and iterate over that list to check for a property that you know the project has (or the projects have). See the example below. Of course, this again doesn't guarantee uniqueness in the general case, since there can be multiple projects that satisfy the criteria. That's why I used Lists in the example.
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
List<IProject> openProjects = new ArrayList<>();
List<IProject> myNatureProjects = new ArrayList<>();
for(IProject project : projects)
{
if(project.isOpen())
openProjects.add(project);
if(project.hasNature("MyNatureId")
myNatureProjects.add(project);
}

Related

Null pointer when adding action listeners in IntelliJ GUI form

I'm using an IntelliJ GUI form to create a toolwindow as part of an IntelliJ plugin. This is some code in the class bound to the form:
private JButton checkNifi;
NifiToolWindow(ToolWindow toolWindow) {
checkNifi.addActionListener(e -> toolWindow.hide(null));
}
I understand that when this action listener is added the button is still null and this is the issue, however even if I do checkNifi = new JButton("Some text");, the null pointer instead gets thrown on this line.
I should add I also have a ToolWindowFactory class which looks like this:
#Override
public void createToolWindowContent(#NotNull Project project, #NotNull com.intellij.openapi.wm.ToolWindow toolWindow) {
NifiToolWindow nifiToolWindow = new NifiToolWindow(toolWindow);
ContentFactory contentFactory = new ContentFactoryImpl();
Content content = contentFactory.createContent(nifiToolWindow.getContent(), "", false);
toolWindow.getContentManager().addContent(content);
}
This is taken from the example here https://github.com/JetBrains/intellij-sdk-docs/tree/master/code_samples/tool_window/src/myToolWindow
Any help or ideas would be great.
I found the solution, I had create custom box ticked in the gui designer, but an empty createGuiComponents() method. Therefore it was null.

How can I retrieve the contents a multi page editor plugin when selecting "Run as" in Eclipse Plugin Development?

An eclipse plugin is needed to allow users to input a script and run that script through the IDE. For this I've implemented an eclipse plugin, using the multi-page editor template. I added the extension org.eclipse.debug.ui.launchShortcuts and provided a reference to my implementation of the interface org.eclipse.debug.ui.ILaunchShortcut. This interface requires to provide an implementation of these methods:
public void launch(final ISelection selection, final String mode);
public void launch(final IEditorPart editor, final String mode);
When the user - e.g. me - right clicks the file from the project explorer, selects "run as" and selects the launcher I provided, then the implementation of this launch method is hit. The first method - i.e. the ISelection version - is hit when selecting the file from the project explorer. The second method - i.e. the IEditorPart version - is hit when right clicking the editor zone and selecting the launcher through the "run as" option from the context menu.
I now need to find out how I can retrieve the contents of that editor page. In the first method I believe I could retrieve the filename with the below code:
IFile file = (IFile) ((IStructuredSelection) selection).getFirstElement();
String path = file.getFullPath().makeAbsolute().toString();
However, the that path is relevant with respect to the root of the project. I don't know how to retrieve the path of the root of the project.
The implementation of the second method is more problematic given I don't know how to find the path based on the IEditorPart.
I hope you can help. Many thanks
If you are asking how to get the file that the editor is current editing you can use something like:
IPath filepath = null;
IEditorInput input = editor.getEditorInput();
IFile file = input.getAdapter(IFile.class);
if (file != null) {
filepath = file.getFullPath();
}
if (filepath == null) {
ILocationProvider locationProvider = input.getAdapter(ILocationProvider.class);
if (locationProvider != null) {
filepath = locationProvider.getPath(input);
}
}
which tries to get the IFile frpm the editor directly and if that fails tries for a location provider.

Display ViewPart in eclipse

I am currently developing an eclipse plugin which displays DOT-Graphs. For this purpose I make use of this plugin. However, I have no idea how to actually display the graph which I built. I want to display it in the middle of the eclipse window as an Editor.
To get this done I created a custom Editor class which needs some code in its createPartControl(Composite) code in order to make use of the DotGraphView which is provided by the plugin.
The question is, how can I display this DotGraphView?
The code of my Editor looks like this:
#Override
public void createPartControl(Composite container) {
DotImport importer = new DotImport(TEST_GRAPH);
Graph graph = importer.newGraphInstance();
DotGraphView dotGraphView = new DotGraphView();
dotGraphView.setGraph(graph);
// add dotGraphView as a child to container and display it
// What todo here?
}
To use the graph in your own custom view, check out the implementation of ZestFxUiView, the superclass of DotGraphView. You could probably subclass ZestFxUiView and call setGraph with your graph object.

Xtext DSL embedded editor in a dialog

I am new to xtext, and i have created a DSL using xtext and i have generated the artifacts, which has generated the editor which has many features like content assist and syntax coloring now the problem is i want to embed the editor inside a dialog.
For achieving this im using EmbeddedEditor, i am able to get the embedded editor and place it in the dialog, but the embedded editor is not displaying the contents of the file.
The file C:/Eclipse_Work/workspace/runtime_workspace/apa/ex.mydsl contains:
import com.ex.test;
entity{
element a;
}
The code in the createcontrol() of dialog is :
IEditedResourceProvider resourceProvider=new IEditedResourceProvider() {
#Override
public XtextResource createResource() {
try {
Resource resource = resourceSet.createResource(URI.createURI("C:/Eclipse_Work/workspace/runtime_workspace/apa/ex.mydsl"));
XtextResource resource2=(XtextResource)resource;
return (XtextResource) resource;
} catch (Exception e) {
return null;
}
}
};
MyDslActivator activator = MyDslActivator.getInstance();
Injector injector = activator
.getInjector(MyDslActivator.COM_APAMA_STUDIO_QUERY_EXT_MYDSL);
#SuppressWarnings("restriction")
EmbeddedEditorFactory factory = injector.getInstance(EmbeddedEditorFactory.class);
EmbeddedEditor handle= factory.newEditor(resourceProvider).withParent(
composite);
EmbeddedEditorModelAccess partialEditor= handle.createPartialEditor();
handle.getViewer().getControl().setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 2, 0));
When i run the project the dialog opens with a editor area but it is not displaying the code present in ex.mydsl, the editor is empty.
Please tell me how to show the code in the embedded editor
You have to specify the editor's initial contents as the editablePart parameter of createPartialEditor(String prefix, String editablePart, String suffix, boolean insertLineBreaks). To obtain your XtextResource's contents as text, save it to a ByteArrayOutputStream, then convert it to a string using toString.

Eclipse: Within a plug-in, how to access another plug-ins preference store?

I have an Eclipse plug-in with a checkbox in the plug-in's preference page.
This checkbox is used for enabling and disabling an editor, which is being launched from this plug-in.
However, the problem is, I would also like to be able to enable and disable this 'editor-launch' from another plug-in, by having actions which change the value of the checkbox in the above mentioned preference page.
Here's the problem, how do I access that local preference store from another plug-in?
I've tried things like..
View myView = (View) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView("ViewID");
But this 'myView' always seems to be null.. And also, what would I do with the view since it's the Plug-in I want.
Platform.getBundle('bundleName')...
Same here, want the Plugin, not the bundle corresponding to is.
No matter what I try nothing seems to work.
Does anyone have any ideas?
There are two ways of doing this:
Please refer to http://www.vogella.com/tutorials/EclipsePreferences/article.html#preferences_pluginaccess
Using .getPluginPreferences(). For example, there is a plugin class "com.xxx.TestPlugin" which extends org.eclipse.ui.plugin.AbstractUIPlugin.Plugin, in order to get access to the preferences of TestPlugin. The plugin code could be below:
public class TestPlugin extends AbstractUIPlugin {
private static TestPlugin plugin;
public static final String PREF_TEST = "test_preference";
/**
* The constructor.
*/
public TestPlugin() {
plugin = this;
}
/**
* This method is called upon plug-in activation
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/**
* This method is called when the plug-in is stopped
*/
public void stop(BundleContext context) throws Exception {
super.stop(context);
plugin = null;
}
/**
* Returns the shared instance.
*/
public static TestPlugin getDefault() {
return plugin;
}
}
To access the preference of TestPlugin, the code could be:
TestPlugin.getDefault().getPluginPreferences().getDefaultBoolean(TestPlugin.PREF_TEST);
Or have a look at this answer: Writing Eclipse plugin to modify Editor Preferences
This thread recommend the use of a Service tracker:
ServiceTracker tracker = new ServiceTracker(ToolkitPlugin.getDefault().getBundle().getBundleContext(),
IProxyService.class.getName(), null);
tracker.open();
proxyService = (IProxyService) tracker.getService();
proxyService.addProxyChangeListener(this);
This may work.
Prefs stores are found per plugin. This is one way to get a prefs store for the plugin whose activator class is ActivatorA.
IPreferenceStore store = ActivatorA.getDefault().getPreferenceStore();
If you want another plugin to refer to the same store, perhaps you could expose some api on ActivatorA for it to get there, e.g.
public IPreferenceStore getSharedPrefs() {
return ActivatorA.getDefault().getPreferenceStore();
}
The second plugin would find the shared store by doing this
IPreferenceStore sharedPrefs = ActivatorA.getSharedPrefs();
Good luck.