Checking the state of menu items inside handlers - eclipse

How to check pro-grammatically whether command contributed as menu item(s) is/are checked/unchecked(If of CHECK BOX type), selected or unselected(if of type RADIO button) inside handlers "execute" method.
See snap shot here https://docs.google.com/file/d/0B3pxBGD-v-ycWVFaeElnSGdyTE0/edit .

Check out this blog: http://eclipsesource.com/blogs/2009/01/15/toggling-a-command-contribution/
So, first of all ensure that your command has appropriate style:
<extension point="org.eclipse.ui.menus">
<menuContribution locationURI="...">
<command commandId="org.eclipse.example.command.toggle"
style="toggle" />
</menuContribution>
</extension>
Then, you can check the state like this:
ICommandService service =(ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
Command command = service.getCommand("org.eclipse.example.command.toggle");
State state = command.getState("org.eclipse.example.command.toggleState");
System.out.println(state.getValue());
//state.setValue(!(Boolean) state.getValue());
Also, consider taking a look at org.eclipse.ui.handlers.HandlerUtil, it might be sometime helpful.
Hope this helps.

I got solution,
Added this code in handler execute method method
public Object execute(ExecutionEvent event) throws ExecutionException {
Event selEvent = (Event) event.getTrigger();
MenuItem item = (MenuItem) selEvent.widget;
System.Out.Println(item.getSelection());
return null;
}

Related

Eclipse RCP: Conditionally enabling/disabling perspective in Perspectie Switcher

The Open Perspective View shows a list of perspectives to which a user can switch. My custom perspective is there, too. Can I have it not listed or greyed out, if a certain condition bis not met?
The second best alternative that comes to my mind is to have it listed, but the actual switch is not carried out, if b == false.
The best way for me was to use the extension point org.eclipse.ui.activities, as greg-449 suggested, and add a propertyTester. In order to hide perspective related UI elements and not every UI element from the same plugin, one can use isEqualityPattern="true".
<extension point="org.eclipse.ui.activities">
<activity
description="Remove some UI Elements"
id="com.my.plugin.ui.hideUI"
name="HideUI">
<enabledWhen>
<test
forcePluginActivation="false"
property="com.my.plugin.ui.PlanningPropertyTester">
</test>
</enabledWhen>
</activity>
<activityPatternBinding
activityId="com.btc.edm.hidePlanning"
isEqualityPattern="true"
pattern="com.my.plugin.ui/id.of.the.perspective.to.hide">
</activityPatternBinding>
</extension>
<extension
point="org.eclipse.core.expressions.propertyTesters">
<propertyTester
class="com.my.plugin.ui.MyPropertyTester"
id="com.my.plugin.ui.propertyTester"
namespace="com.my.plugin.ui"
properties="MyPropertyTester"
type="java.lang.Object">
</propertyTester>
</extension>
It is important to have a fully qualified name for type.
The MyPropertyTester class extends org.eclipse.core.expressions.PropertyTester and overrides the test method.
public class MyPropertyTester extends PropertyTester {
#Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
if (goodWeather()) {
return true;
return false;
}
}

Eclipse RCP Can't Contribute to Main Toolbar

My RCP app has the coolbar visible by setting configurer.setShowCoolBar(true) in WorkbenchWindowAdvisor#preWindowOpen. But when I contribute a toolbar to the main toolbar, it never shows up. Here's my contribution code:
<extension point="org.eclipse.ui.menus">
<menuContribution
allPopups="true"
locationURI="toolbar:org.eclipse.ui.main.toolbar">
<toolbar id="toolbar.perspectivesDynamic">
<dynamic
class="my.package.PerspectiveSwitcherToolbar"
id="perspectiveSwitcherToolbar">
</dynamic>
</toolbar>
</menuContribution>
</extension>
And the ContributionItem class:
public class PerspectiveSwitcherToolbar extends ContributionItem {
...
#Override
public void fill(final ToolBar parent, int index) {
//Does not get called
}
#Override
public void fill(CoolBar parent, int index) {
//Does not get called
}
...
}
I'm using this code for adding a custom perspective switcher. It's rather old, but I see examples everywhere on the Internet adding a toolbar like this to the main toolbar, so I'm missing something elsewher, I assume
I think that is bug 392457: <toolbar><dynamic></toolbar> doesn't work at the moment. You can work around it by using a <control> and managing the contents yourself.

Update Eclipse menu radio state from code

In the command handler for a radio state menu item, I prompt the user if they want to continue. If they choose no, I need to reset the selected menu item back to the previous value.
I am using HandlerUtil.updateRadioState(event.getCommand(), oldScope) but the menu stays with the new value.
Any suggestions?
Command Handler
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
if (HandlerUtil.matchesRadioState(event))
return null;
String scope = event.getParameter(RadioState.PARAMETER_ID);
if (MessageDialog.openConfirm(HandlerUtil.getActiveShell(event), "Confirm restart",
"Switching source of Motors requires a restart. Continue?")) {
int connection = MotorDbPreferencesPage.DATABASE_ACCESS_LOCAL;
if ("Cloud".compareToIgnoreCase(scope) == 0) {
connection = MotorDbPreferencesPage.DATABASE_ACCESS_CLOUD;
}
Activator.getDefault().getPreferenceStore().setValue(MotorDbPreferencesPage.DATABASE_ACCESS, connection);
PlatformUI.getWorkbench().restart();
} else {
String oldScope = "Local";
// switch it back to the way it was before the user selected it
if ("Local".compareToIgnoreCase(scope) == 0) {
oldScope = "Cloud";
}
HandlerUtil.updateRadioState(event.getCommand(), oldScope);
}
return null;
}
Command definition in plugin.xml
<command
id="com.client.eclipse.connection"
name="Connection">
<commandParameter
id="org.eclipse.ui.commands.radioStateParameter"
name="State"
optional="false">
</commandParameter>
<state
class="org.eclipse.ui.handlers.RadioState:Cloud"
id="org.eclipse.ui.commands.radioState">
</state>
</command>
And the menu definition from plugin.xml
<menu
label="Connection">
<command
commandId="com.client.eclipse.connection"
label="Local"
style="radio">
<parameter
name="org.eclipse.ui.commands.radioStateParameter"
value="Local">
</parameter>
</command>
<command
commandId="com.client.eclipse.connection"
label="Cloud"
style="radio">
<parameter
name="org.eclipse.ui.commands.radioStateParameter"
value="Cloud">
</parameter>
</command>
</menu>
It's your responsability to call
HandlerUtil.updateRadioState(event.getCommand(), scope);
to make the GUI displays the new state. Without calling it, the radio state won't change.
It means that in the case of user is aborting, don't call this method at all.

Visibility of toolbar items in Eclipse 4 model

I have a simple e4 RPC application, based on e4 model. I have two parts in PartSachContainer - left one and right one.
And I need a certain toolbar item to be visible when one part is active, and another item to be visible when another part is active.
I tried to use CoreExpression for this, but to no avail. I can't understand what do I need to write in the expression itself.
My config is as follows:
First part is defined as
ID: simple1.part.leftpart
Label: LeftPart
ClassURI: bundleclass://Simple1/simple1.parts.LeftPart
The second part is defined as
ID: simple1.part.rightpart
Label: RightPart
ClassURI: bundleclass://Simple1/simple1.parts.RightPart
The ToolBar Contribution is defined as
<toolBarContributions xmi:id="_gqB4gNaWEeO3iqh7a9kwnw" elementId="simple1.toolbarcontribution.0" parentId="simple1.toolbar.0">
<children xsi:type="menu:HandledToolItem" xmi:id="_PtGaINaSEeO3iqh7a9kwnw" elementId="simple1.handledtoolitem.leftpitem" iconURI="platform:/plugin/Simple1/icons/sample.png" command="_vFvtcNaREeO3iqh7a9kwnw">
<visibleWhen xsi:type="ui:CoreExpression" xmi:id="_z_87oNanEeO3iqh7a9kwnw" coreExpressionId="Simple1.RightPartActive"/>
</children>
</toolBarContributions>
When I set Visible-When Expression to I can see the toolbar item.
But when I try to use CoreExpression (and I tried various combinations) I never see the toolbar item.
This is what I start with:
<definition id="Simple1.RightPartActive">
<with variable="activePartId">
<equals
value="simple1.part.rightpart">
</equals>
</with>
</definition>
No luck.
How should I define the CoreExpression to see the toolbar item?
And here's to the real problem:
This right part should really be an editor (in e3 terms) - the same implementaion class for multiple various instances of editable data. So, I will use the runtime-generated unique IDs for this parts (the parts themleves would be created from PartDescription).
So how should I address these parts with generated IDs in CoreExpression?
UPDATE
Ok, I did some debugging and found out that there is a method
public EvaluationResult evaluate(IEvaluationContext context)
of the class
org.eclipse.core.internal.expressions.WithExpression
that is being called.
The very first line :
Object variable= context.getVariable(fVariable);
calls method of the class EclipseContext
public Object getVariable(String name) {
if (IEclipseContext.class.getName().equals(name)) {
return eclipseContext;
}
Object obj = eclipseContext.getActive(name);
return obj == null ? IEvaluationContext.UNDEFINED_VARIABLE : obj;
}
where
public Object getActive(final String name) {
return getActiveLeaf().get(name);
}
and
public IEclipseContext getActiveLeaf() {
IEclipseContext activeContext = this;
IEclipseContext child = getActiveChild();
while (child != null) {
activeContext = child;
child = child.getActiveChild();
}
return activeContext;
}
and [b]activeChild[/b] is always null.
And I don't see anything in EclipseContext which would be something like "activePartId" or anything close to it.
So why is it so??
How can we even use the CoreExpressions??
This looks like Eclipse bug 400217, which is saying that this does not currently work.
Since you're in e4 why not handle it the e4 way ?
Subscribe to the UIEvents.UILifeCycle.ACTIVATE event.
if (newActivePart == LeftPart)
<set 'toBeRendered' to true for LeftPart's items and false for RightPart's items
same for Right part...

Removing popUpMenus from CNF (Common Navigator Framework) in Eclipse

I have been partially successful at removing almost all the popUp menus from the Commons Navigator Framework simply by configuring the plugin.xml file.
There are 2 menus that refuse to go:
group.edit and
group.reorganize.
My plugin.xml config looks like this:
<extension
point="org.eclipse.ui.navigator.viewer">
<viewer
viewerId="org.eclipse.ui.example.navigator.view">
<popupMenu allowsPlatformContributions="false">
<insertionPoint
name="group.edit" />
<insertionPoint
name="group.reorganize" />
</popupMenu>
</viewer>
<viewerContentBinding
viewerId="org.eclipse.ui.thermo.navigator.view">
<includes>
<contentExtension
pattern="org.eclipse.ui.navigator.resourceContent"/>
</includes>
</viewerContentBinding>
</extension>
Setting the allowsPlatformContribution to false DOES stop contributions to be added to the context menu except for group.edit and group.reorganize... this is starting to look like a bug to me.
The obvious solution is to remove the insertion points from my <popUpMenu> but without them the application throws an exception:
Throwable: java.lang.IllegalArgumentException: Group not found: group.edit
java.lang.IllegalArgumentException: Group not found: group.edit
at org.eclipse.jface.action.ContributionManager.addToGroup(ContributionManager.java:131)
at org.eclipse.jface.action.ContributionManager.appendToGroup(ContributionManager.java:138)
at org.eclipse.ui.internal.navigator.resources.actions.EditActionGroup.fillContextMenu(EditActionGroup.java:74)
at org.eclipse.ui.internal.navigator.resources.actions.EditActionProvider.fillContextMenu(EditActionProvider.java:50)
at org.eclipse.ui.navigator.NavigatorActionService.addCommonActionProviderMenu(NavigatorActionService.java:205)
at org.eclipse.ui.navigator.NavigatorActionService.fillContextMenu(NavigatorActionService.java:172)
at org.eclipse.ui.internal.navigator.CommonNavigatorManager.fillContextMenu(CommonNavigatorManager.java:258)
at org.eclipse.ui.internal.navigator.CommonNavigatorManager$4.menuAboutToShow(CommonNavigatorManager.java:273)
at org.eclipse.jface.action.MenuManager.fireAboutToShow(MenuManager.java:335)
at org.eclipse.jface.action.MenuManager.handleAboutToShow(MenuManager.java:463)
at org.eclipse.jface.action.MenuManager.access$1(MenuManager.java:459)
at org.eclipse.jface.action.MenuManager$2.menuShown(MenuManager.java:485)
It throws the same exception for the reorganize group.
I succeeded in removing the "group.edit" actions (Copy/Paste) and I've done it that way, using the Common Navigator extension points :
<extension
point="org.eclipse.ui.navigator.viewer">
<viewerActionBinding
viewerId="org.eclipse.ui.navigator.ProjectExplorer">
<includes>
<actionExtension
pattern="my.app.client.actions.MyAppEditActionExtension">
</actionExtension>
</includes>
</viewerActionBinding>
</extension>
<extension
point="org.eclipse.ui.navigator.navigatorContent">
<actionProvider
class="my.app.client.workshop.MyPasteActionProvider"
id="my.app.client.actions.MyAppEditActionExtension"
overrides="org.eclipse.ui.navigator.resources.actions.EditActions"
priority="highest">
<enablement>
<!-- A hack to allways be enabled -->
<not>
<systemTest
property="MyApp"
value="WONT-EVER-BE-SET">
</systemTest>
</not>
</enablement>
</actionProvider>
</extension>
And, with addition of "org.eclipse.ui.navigator.resources" in my plugin dependencies, I implemented "MyPasteActionProvider" like this :
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.ui.internal.navigator.resources.actions.EditActionProvider;
/**
* Create the Edit actions (Cut/Copy/Paste)
* and register then globally in the workbench using EditActionProvider.
* <p/>
* Then, removes the Copy/Paste contributions in the pop-up menu.
*/
public class MyPasteActionProvider extends EditActionProvider {
public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu);
// remove Copy/Paste contributions
IContributionItem copyItemRemoved = menu.remove("org.eclipse.ui.CopyAction");
IContributionItem pasteItemRemoved = menu.remove("org.eclipse.ui.PasteAction");
}
}
Well, that's a "discouraged access" but I was getting myself discouraged ;-)
JM.D
Generally you should be using the Command Framework with any recent version of Eclipse (3.3 or higher), this replaces the mechanism for providing popup menus in the Common Navigator.
This thread suggests to remove the things that are causing the menu items to appear in the first place:
They are probably in action sets, so if you can identify the action set that's causing the offensive contribution, you can do something like this in your WorkbenchAdvisor:
ActionSetRegistry reg = WorkbenchPlugin.getDefault()
.getActionSetRegistry();
IActionSetDescriptor[] actionSets = reg.getActionSets();
String[] removeActionSets = new String[] {
"org.eclipse.ui.cheatsheets.actionSet",
"org.eclipse.ui.edit.text.actionSet.annotationNavigation",
"org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo",
"org.eclipse.ui.WorkingSetActionSet",
"org.eclipse.update.ui.softwareUpdates", };
for (int i = 0; i < actionSets.length; i++)
{
boolean found = false;
for (int j = 0; j < removeActionSets.length; j++)
{
if (removeActionSets[j].equals(actionSets[i].getId()))
found = true;
}
if (!found)
continue;
IExtension ext = actionSets[i].getConfigurationElement()
.getDeclaringExtension();
reg.removeExtension(ext, new Object[] { actionSets[i] });
}
The closest bug I have found is the 145233: Make more obvious way to specify input (for RCP apps), with a similar hack.
Bug 143430 (CommonNavigator requires initialInput to be Adaptable) is a more general one, and would indicate that then CNF has been improved with eclipse3.5 (Galileo).
So do you also have this issue with 3.5 and a custom CNF class?
As mentioned in the article "Eclipse CNF: Navigator Content Extensions", CNF has evolved with eclipse3.5, and this article seems to have some tree with true custom contextual menu entries.