目的:在command的处理函数中获取触发当前command时被选中的条目。
方法:使用HandlerUtil工具类获取。
代码示例:
public Object execute(ExecutionEvent event) throws ExecutionException {
// 获取需要导出的线路。
ISelection selection = HandlerUtil.getCurrentSelection(event);
System.out.println(selection);
PowerLineInfo pl = (PowerLineInfo)((IStructuredSelection)selection).getFirstElement();
System.out.println((pl).getPowerLineName());
原理解析:
查看HandlerUtil.GetCurrentSelection函数,可发现其实现为:
public static ISelection getCurrentSelection(ExecutionEvent event) {
Object o = getVariable(event, ISources.ACTIVE_CURRENT_SELECTION_NAME);
if (o instanceof ISelection) {
return (ISelection) o;
}
return null;
}
其中:
org.eclipse.ui.ISources.ACTIVE_CURRENT_SELECTION_NAME 值为 "selection"
其为RCP框架内置的一个变量,由框架维护其值的变化。
再看getVariable的函数实现:
/**
* Extract the variable.
*
* @param event
* The execution event that contains the application context
* @param name
* The variable name to extract.
* @return The object from the application context, or <code>null</code>
* if it could not be found.
*/
public static Object getVariable(ExecutionEvent event, String name) {
if (event.getApplicationContext() instanceof IEvaluationContext) {
Object var = ((IEvaluationContext) event.getApplicationContext())
.getVariable(name);
return var == IEvaluationContext.UNDEFINED_VARIABLE ? null : var;
}
return null;
}
从中可得知HandlerUtil获取当前选择的处理思路:
通过event获取当前执行上下文环境,然后在此上下文环境中检索selection状态值。
从以上分析可知,如果想使用HandlerUtil工具类获取当前选择项,事件的触发源容器必须将自身注册为selectionProvider。
到此产生了一个问题:假如Selection提供者无法将自身注册为selectionProvider,或者Selection处理函数不是event处理函数,即没法使用HandlerUtil的工具函数,那么该如何获取selection呢?
解决思路可借鉴HandlerUtil的设计,即使用状态来传递selection。
为了能使用状态,我们需要先自定义一个SourceProvider类,由其来保管需要传递的状态,并在状态改变时通过监听机制通知各监听者。
选择项的提供者在产生选择项时,通过RCP框架获取到对应的状态管理SourceProvider类实例,然后将选择项交给此SourceProvider,由其进行后续操作。
对前述选择项感兴趣的其他类可将自身(需要实现ISourceProviderListener接口)注册到前面定义SourceProvider类示例,然后在sourceChanged函数中处理接收到的选择项。
后面的这个分析有点问题,至少对于前面假设的情况而言是绕了弯路的,其实在前述假设的情况下,Selection提供者可以将自己定义为事件分发者,对Selection感兴趣者可将自身作为监听者注册到Selection提供者,也能达到交流Selection的目的,而且效率更高。
参考资料:
1、eclipse rcp:how to pass selection into handler
2、RCP 自定义用于visible/enable when表达式的变量
3、Eclipse Commands Advanced - Tutorial