呼……我花了很多时间来弄清楚我必须做些什么才能让它发挥作用。
第一步:getId() 对我来说是错误的方法,setActionDefinitionId() 是正确的方法。我创建了一个嵌套类,如下所示:
public final class UpdateTabsAction extends Action
{
public UpdateTabsAction()
{
setText("Update tabs");
setToolTipText("Parses document and updates tabs to reflect textual changes");
setImageDescriptor(PlatformUI.getWorkbench()
.getSharedImages()
.getImageDescriptor(IDE.SharedImages.IMG_OBJS_TASK_TSK));
setActionDefinitionId("com.portal.agenda.editors.updatetabs");
}
@Override
public void run()
{
ARTEditor artEditor = (ARTEditor)activeEditorPart.getSite().getPage().getActiveEditor();
artEditor.parseDocument();
artEditor.updateTabs();
}
}
第二步 必须向处理程序服务注册该操作。我决定重写MultiPageEditorActionBarContributor 的方法setActivePage,因为它传递了一个有效的EditorPart 实例,如果它被选中,它是对我的文本编辑器的引用:
// Required to avoid multiple registering of the action
private IHandlerActivation iHandlerActivation;
@Override
public void setActivePage(IEditorPart part)
{
if (part != null && iHandlerActivation == null)
{
IHandlerService hService = ((IHandlerService)part.getSite().getService(IHandlerService.class));
iHandlerActivation = hService.activateHandler(updateTabsAction.getActionDefinitionId(),
new ActionHandler(updateTabsAction));
}
if (activeEditorPart == part)
return;
activeEditorPart = part;
// ...skipped...
}
第三步:我将此操作映射到 plugin.xml 中的命令扩展点。除此之外,我还创建了一个上下文和绑定:
<extension
point="org.eclipse.ui.commands">
<category
id="com.portal.agenda.editors.category"
name="ARTEditor">
</category>
<command
categoryId="com.portal.agenda.editors.category"
description="Parse document and update tabs to reflect textual changes"
id="com.portal.agenda.editors.updatetabs"
name="Update tabs">
</command>
</extension>
<extension
point="org.eclipse.ui.contexts">
<context
id="com.portal.agenda.editors.context"
name="%context.name"
parentId="org.eclipse.ui.textEditorScope">
</context>
</extension>
<extension
point="org.eclipse.ui.bindings">
<key
commandId="com.portal.agenda.editors.updatetabs"
contextId="com.portal.agenda.editors.context"
schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
sequence="F5">
</key>
</extension>
第四步:我在StructuredTextEditor 中添加了FocusListener,因此只有在编辑器处于活动状态时才会激活上下文:
private void initKeyBindingContext()
{
final IContextService cService = (IContextService)getSite().getService(IContextService.class);
textEditor.getTextViewer().getTextWidget().addFocusListener(new FocusListener()
{
IContextActivation currentContext = null;
public void focusGained(FocusEvent e)
{
if (currentContext == null)
currentContext = cService.activateContext("com.portal.agenda.editors.context");
}
public void focusLost(FocusEvent e)
{
if (currentContext != null)
{
cService.deactivateContext(currentContext);
currentContext = null;
}
}
});
}