Eclipse 编辑器:当部分获得 active/inactive 时自动切换上下文

Eclipse Editor: automatically switch context when parts get active/inactive

我正在开发自己的 eclipse 编辑器,需要在不同的上下文之间切换以进行键绑定。目前,我正在部分激活时手动执行上下文 activation/deactivation。

本页 https://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Fguide%2Fworkbench_advext_contexts.htm 说:

If you are activating a more specific Context within your part (either View or Editor) you can use the part site service locator to active your Context. The part's IContextService will take care of activating and deactivating the Context as your part is activated or deactivated. It will also dispose the Context when the part is disposed.

看来这正是我想要的。但是页面并没有说如何。谁能给我提示文中提到的'part site service locator'是什么以及如何使用它?

我会解释文本,以便您应该使用与您的(编辑)部分相对应的站点服务定位器。在以下示例中,part 引用您的编辑器。通过从部件的站点获取上下文服务,您可以获得该特定部件的子上下文服务,您可以在其中激活专门的编辑器上下文。

IContextService contextService = part.getSite().getService( IContextService.class );
contextService.activateContext( "your.editor.context.id" );

在深入了解 Eclipse 代码后,这是我对自己问题的回答。

首先,只需调用

IContextService contextService = part.getSite().getService( IContextService.class );
contextService.activateContext( "your.editor.context.id" );

init 之后的任何地方(你得到 PartSite 的地方),就像@Rüdiger Herrmann 在他的回答中提到的那样。

并且(这是我的发现)没有其他事情需要做。 Eclipse 将在部分激活/停用时自动 activate/deactivate 上下文,正如我参考的文本中所述。另外,当part site被销毁时,所有context也会被销毁。

如果您对如何操作感兴趣,请继续深入挖掘。

Activate/Deactivate

当我们调用getSite().getService(IContextService.class)时,我们得到的是SlaveContextService的一个实例。 当我们对其调用 activateContext(String contextId) 时,我们的请求将自动转换为具有默认表达式 ActivePartExpression.

的请求

从它的名字我们可以很容易地猜到这个表达式将检查一个部分是否处于活动状态并进行一些更改。它所做的更改可以在 ContextService.UpdateExpression.changed 中看到。这是代码(ContextService:124-128)

if (result != EvaluationResult.FALSE) {
    runExternalCode(() -> contextService.activateContext(contextId));
} else if (cached != null) {
    runExternalCode(() -> contextService.deactivateContext(contextId));
}

每当 Eclipse 上下文发生变化时(activate/deactivate 部分将触发上下文变化),UpdateExpression.changed 将被调用并检查目标部分是否仍然处于活动状态,然后 activate/deactivate 相应的上下文。

处置

SlaveContextService.dispose中,所有通过它注册的上下文都将在服务处理时处理。