How to get the project when right-click on a project/file/others in an eclipse-plugin - eclipse-plugin

I'm write a simple eclipse plugin, but have a problem: When user right-click on a node(maybe a project, a file, a java compilation unit, or others), I want to get the project it belongs.
The sample code is:
public class MyAction implements IObjectActionDelegate {
private IProject project;
public void selectionChanged(IAction action, ISelection selection) {
this.project = getSelectedProject(selection);
}
public static IProject getSelectedProject(Object obj) throws Exception {
if (obj == null) {
return null;
}
if (obj instanceof IResource) {
return ((IResource) obj).getProject();
} else if (obj instanceof IStructuredSelection) {
return getSelectedProject(((IStructuredSelection) obj).getFirstElement());
}
return null;
}
}
It works at most of time, but sometimes, for example, I right-clicked on a java file, the selection will be a ICompilationUnit. Although I can add one more if in the getSelectedProject, but I don't think it's a good idea.
Is there a way to get the project of selected objects nomatter what have been selected? I don't want to add them one by one.

ICompilationUnit extends IAdaptable (see http://publib.boulder.ibm.com/infocenter/rsmhelp/v7r0m0/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/ICompilationUnit.html)
You can try and use the IAdaptable interface like that:
if (obj instanceof IAdaptable) {
IResource res = (IResource)(((IAdaptable)obj).getAdapter(IResource.class));
if (res != null) {
return res.getProject();
}
}

There are no way to convert an ICompilationUnit, IPackage, or whatever, to an IResource as there are most often no corresponding resource! E.g. for the .class elements in the navigator, the element corresponds to an entry in a JAR file or in a dependency plug-in from the target platform.

it up answer don't work, may it should be:
if (obj instanceof IStructuredSelection) {
IStructuredSelection selection1 = (IStructuredSelection)obj;
Object element = selection1.getFirstElement();
IProject project = null;
if (element instanceof IProject) {
project = (IProject) element;
} else if (element instanceof IAdaptable) {
project = (IProject) ((IAdaptable) element).getAdapter(IProject.class);
}
if (project != null) {
return project;
}
}

Related

How does WorldEdit handle brushes?

I'm trying to find out how the Bukkit version of WorldEdit handles brushes. I've been looking at the source code on GitHub, but I couldn't find anythig useful. I've tried to recreate the effect, but I can only get it to work when I'm in interaction reach of the target block.
This is about as close as it gets in the source code:
} else if (action == Action.RIGHT_CLICK_AIR) {
if (we.handleRightClick(player)) {
event.setCancelled(true);
}
}
(WorldEdit/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditListener.java, line 143-147)
There are some other parts of code that get very close. I've also looked in /worldedit-core, but nothing there either.
Could someone help me here?
Edit: This is how I try to do it:
public static void onRightClick (PlayerInteractEvent event) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Location location = event.getClickedBlock().getLocation();
if (event.getItem() != null) {
if (event.getItem().getItemMeta().equals(ItemManager.wand.getItemMeta())) {
Player player = event.getPlayer();
player.getWorld().doStuff(location);
}
}
}
}
Edit #2: what I'm most curious about is: How does WE select the location to apply the brush if you are outside of interaction reach?
I needed to use BlockIterators for this. The final code looks like this:
public class BoomWandEvent implements Listener {
#EventHandler
public static void onRightClick (PlayerInteractEvent event) {
Player player = event.getPlayer();
if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) {
if (player.getInventory().getItemInMainHand().equals(ItemManager.explosionWand)) {
Location eyePos = player.getEyeLocation();
BlockIterator raytracer = new BlockIterator(eyePos, 0.0D, player.getClientViewDistance() * 16);
while (raytracer.hasNext()) {
Location location = raytracer.next().getLocation();
if (player.getWorld().getBlockAt(location).getType() != Material.AIR && player.getWorld().getBlockAt(location).getType() != Material.CAVE_AIR && player.getWorld().getBlockAt(location).getType() != Material.VOID_AIR) {
player.getWorld().createExplosion(location, 4f);
return;
}
}
}
}
}
}
Thanks to Rogue for helping!

Override the dependencies added during running a project as an Eclipse Application

I am trying to write a custom launch configuration while running a plugin project as an eclipse application. I have to run the plugin with limited dependencies. Is it possible to override methods in org.eclipse.pde.launching.EclipseApplicationLaunchConfiguration ? If yes then how do I do it ?
You can't easily override the methods in EclipseApplicationLaunchConfiguration. That would require writing a new launch configuration - probably by using the org.eclipse.debug.core.launchConfigurationTypes extension point to define a new launch type.
EclipseApplicationLaunchConfiguration always uses the settings from the current entry in the 'Eclipse Application' section of the 'Run Configurations'. You can always edit the run configuration to change the dependencies or create another run configuration with different dependencies.
To write a custom configuration file
Extend the class org.eclipse.jdt.junit.launcher.JUnitLaunchShortcut
Override the method createLaunchConfiguration
Invoking super.createLaunchConfiguration(element) will return a ILaunchConfigurationWorkingCopy
Use the copy and set your own attributes that have to be modified
Attributes can be found in IPDELauncherConstants
Eclipse by default runs all the projects found in the workspace. This behavior can be modified by using the configuration created and overriding it with custom configuration.
public class LaunchShortcut extends JUnitLaunchShortcut {
class PluginModelNameBuffer {
private List<String> nameList;
PluginModelNameBuffer() {
super();
this.nameList = new ArrayList<>();
}
void add(final IPluginModelBase model) {
this.nameList.add(getPluginName(model));
}
private String getPluginName(final IPluginModelBase model) {
IPluginBase base = model.getPluginBase();
String id = base.getId();
StringBuilder buffer = new StringBuilder(id);
ModelEntry entry = PluginRegistry.findEntry(id);
if ((entry != null) && (entry.getActiveModels().length > 1)) {
buffer.append('*');
buffer.append(model.getPluginBase().getVersion());
}
return buffer.toString();
}
#Override
public String toString() {
Collections.sort(this.nameList);
StringBuilder result = new StringBuilder();
for (String name : this.nameList) {
if (result.length() > 0) {
result.append(',');
}
result.append(name);
}
if (result.length() == 0) {
return null;
}
return result.toString();
}
}
#Override
protected ILaunchConfigurationWorkingCopy createLaunchConfiguration(final IJavaElement element)
throws CoreException {
ILaunchConfigurationWorkingCopy configuration = super.createLaunchConfiguration(element);
configuration.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, "memory");
configuration.setAttribute(IPDELauncherConstants.USE_PRODUCT, false);
configuration.setAttribute(IPDELauncherConstants.USE_DEFAULT, false);
configuration.setAttribute(IPDELauncherConstants.AUTOMATIC_ADD, false);
addDependencies(configuration);
return configuration;
}
#SuppressWarnings("restriction")
private void addDependencies(final ILaunchConfigurationWorkingCopy configuration) throws CoreException {
PluginModelNameBuffer wBuffer = new PluginModelNameBuffer();
PluginModelNameBuffer tBuffer = new PluginModelNameBuffer();
Set<IPluginModelBase> addedModels = new HashSet<>();
String projectName = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "");
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
IPluginModelBase model = PluginRegistry.findModel(project);
wBuffer.add(model);
addedModels.add(model);
IPluginModelBase[] externalModels = PluginRegistry.getExternalModels();
for (IPluginModelBase externalModel : externalModels) {
String id = externalModel.getPluginBase().getId();
if (id != null) {
switch (id) {
case "org.eclipse.ui.ide.application":
case "org.eclipse.equinox.ds":
case "org.eclipse.equinox.event":
tBuffer.add(externalModel);
addedModels.add(externalModel);
break;
default:
break;
}
}
}
TreeSet<String> checkedWorkspace = new TreeSet<>();
IPluginModelBase[] workspaceModels = PluginRegistry.getWorkspaceModels();
for (IPluginModelBase workspaceModel : workspaceModels) {
checkedWorkspace.add(workspaceModel.getPluginBase().getId());
}
EclipsePluginValidationOperation eclipsePluginValidationOperation = new EclipsePluginValidationOperation(
configuration);
eclipsePluginValidationOperation.run(null);
while (eclipsePluginValidationOperation.hasErrors()) {
Set<String> additionalIds = DependencyManager.getDependencies(addedModels.toArray(), true, null);
if (additionalIds.isEmpty()) {
break;
}
additionalIds.stream().map(PluginRegistry::findEntry).filter(Objects::nonNull).map(ModelEntry::getModel)
.forEach(addedModels::add);
for (String id : additionalIds) {
IPluginModelBase plugin = findPlugin(id);
if (checkedWorkspace.contains(plugin.getPluginBase().getId())
&& (!plugin.getPluginBase().getId().endsWith("tests"))) {
wBuffer.add(plugin);
} else {
tBuffer.add(plugin);
}
}
eclipsePluginValidationOperation.run(null);
}
configuration.setAttribute(IPDELauncherConstants.SELECTED_WORKSPACE_PLUGINS, wBuffer.toString());
configuration.setAttribute(IPDELauncherConstants.SELECTED_TARGET_PLUGINS, tBuffer.toString());
}
protected IPluginModelBase findPlugin(final String id) {
ModelEntry entry = PluginRegistry.findEntry(id);
if (entry != null) {
return entry.getModel();
}
return null;
}
}

Disable "Answers" but not "Crashlytics"

When installing "Crashlytics" in my Android App, it automatically installs "Answers". I only want to install "Crashlytics" and want to have "Answers" disabled. Does anyone know how to do that?
build.gradle
dependencies {
compile('com.crashlytics.sdk.android:crashlytics:2.5.5#aar') {
transitive = true;
}
Thanks!
Mike from Fabric and Crashlytics here.
As you saw, Crashlytics by default includes Answers. If you don't want Answers enabled on your app, then you want to invoke CrashlyticsCore() when building your app instead of Crashlytics.
For example, have these as your imports:
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.core.CrashlyticsCore;
import io.fabric.sdk.android.Fabric;
Then when you initialize Fabric, use:
Fabric.with(this, new CrashlyticsCore());
and that will initialize only the crash reporting side of things.
I think it is not possible at the moment, because Crashlytics is making an Answers instance:
public Crashlytics build() {
if(this.coreBuilder != null) {
if(this.core != null) {
throw new IllegalStateException("Must not use Deprecated methods delay(), disabled(), listener(), pinningInfoProvider() with core()");
}
this.core = this.coreBuilder.build();
}
if(this.answers == null) {
this.answers = new Answers();
}
if(this.beta == null) {
this.beta = new Beta();
}
if(this.core == null) {
this.core = new CrashlyticsCore();
}
return new Crashlytics(this.answers, this.beta, this.core);
}
Crashlytics(Answers answers, Beta beta, CrashlyticsCore core) is not public, so we cannot instanciate this. Also the answers field is final, so you cannot override it. I think there is now way to let the user decide if they want to use answers.
Hey Fabric/Google, you should make a programmatically way to opt out for a session, to give the programmer the option to let the user decide if they want to be counted in some way.
EDIT
My solution is to to use a wraper for all needed funtioncs and init, feel free to use it:
public class AnalyticsWrapper {
static AnalyticsWrapper instance;
public static void initialize(Context context, boolean optOut) {
if (instance != null) throw new IllegalStateException("AnalyticsWrapper must only be initialized once");
instance = new AnalyticsWrapper(context.getApplicationContext(), optOut);
}
public static AnalyticsWrapper getInstance() {
if (instance == null) throw new IllegalStateException("AnalyticsWrapper must be initialized before");
return instance;
}
final boolean optOut;
private AnalyticsWrapper(Context context, boolean optOut) {
this.optOut = optOut;
initFabric(context);
}
public boolean isOptOut() {
return optOut;
}
private void initFabric(Context context) {
if (!optOut) {
if (!BuildConfig.DEBUG) {
Timber.plant(new CrashlyticsLogExceptionTree());
Timber.plant(new CrashlyticsLogTree(Log.INFO));
}
Crashlytics crashlyticsKit = new Crashlytics.Builder().core(
new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG)
.build())
.build();
Fabric fabric = new Fabric.Builder(context).kits(crashlyticsKit)
.debuggable(BuildConfig.DEBUG)
.build();
Fabric.with(fabric);
}
}
public void crashlyticsSetString(String key, String value) {
if (!optOut) {
Crashlytics.setString(key, value);
}
}
public void logException(Throwable throwable) {
if (!optOut) {
Crashlytics.logException(throwable);
}
}
public void logEvent(CustomEvent event) {
if (!optOut) {
Answers.getInstance()
.logCustom(event);
}
}
}

Using StyledCellLabelProvider in a TableViewer killed my tooltips

I have a TableViewer in my Eclipse plugin.
When I was just using a regular label provider, my tooltips worked beautifully:
However, when I switched to have my LabelProvider implement IStyledLabelProvider, my tooltips went haywire:
Here is the code creating the StyledString
#Override
public StyledString getStyledText(final Object element) {
if( !(element instanceof MyInterface<?>) ) {
return null;
}
final String elemText = getColumnText(element, this.columnIndex);
final StyledString styledString = new StyledString(elemText == null ? "" : elemText);
if( !(element instanceof MyObject) ) {
return styledString;
}
final MyObject settingElement = (MyObject) element;
// grayed out text
if( settingElement.shouldBeGray() ) {
styledString.setStyle(0, elemText.length(), AdaptabilityStyles.GRAY_STYLER;
} else if( !settingElement.shouldBeBlue() ) {
styledString.setStyle(0, elemText.length(), AdaptabilityStyles.BLUE_STYLER);
}
return styledString;
}
And getTooltTipText()
#Override
public String getToolTipText(final Object element) {
return getColumnText(element, this.columnIndex);
}
What am I doing wrong?
As I was writing this question, I wanted to reference a bug report that I am familiar with that is related to tooltips. I looked at the bug report again and came across the following line:
For now, I simply try this :
ColumnViewerToolTipSupport.enableFor(commonViewer)
I wasn't calling that method when I created my viewer. When I tried that, my tooltips came back (though slightly different than they were before.

Eclipse Plugin Development : How to change file attributes of selected files?

I am trying to create an eclipse plugin to change the selected files to read only. Created popup menu sample plugin project which when executed shows a message "New Action was executed"
I am stuck at next step.
How to get list of files selected, and change file attributes ?
I don't have the time to test the following properly, but it is probably a good starting point:
public class SetFileToROHandler extends AbstractHandler implements IHandler {
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
final ISelection s = HandlerUtil.getCurrentSelectionChecked(event);
if (!(s instanceof IStructuredSelection))
return null;
final IStructuredSelection ss = (IStructuredSelection) s;
for (final Object o : ss.toArray()) {
if (!(o instanceof IFile)) {
continue;
}
IFile f = (IFile) o;
f.setReadOnly(true);
}
return null;
}
}