在挖掘 Eclipse 代码之后,这是我对自己问题的回答。
首先,调用就足够了
IContextService contextService = part.getSite().getService( IContextService.class );
contextService.activateContext( "your.editor.context.id" );
init 之后的任何地方(你会得到PartSite),就像@Rüdiger Herrmann 在他的回答中提到的那样。
并且(这是我的发现)不需要做任何其他事情。
当部件被激活/停用时,Eclipse 将自动激活/停用上下文,正如我参考的文本中所述。另外,当部分站点被释放时,所有上下文都会被释放。
如果你对如何做感兴趣,这里有更多的挖掘。
激活/停用
当我们调用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 上下文发生变化(激活/停用部分会触发上下文变化),UpdateExpression.changed 将被调用并检查目标部分是否仍然处于活动状态,然后相应地激活/停用上下文。
处置
在SlaveContextService.dispose 中,通过它注册的所有上下文都将在服务释放时被释放。