Eclipse TextEditorAction 如何知道当前文件在哪个项目中?

How can an Eclipse TextEditorAction know what project the current file is in?

我正在为一个有点复杂的 Eclipse 插件开发一个继承的代码库,该插件用于以自定义规范语言查看和编辑文件。

使用什么语言并不重要,但它与 CORBA IDL 和 XML XSD 在功能上有相似之处。在一个模块中,我可以 "import" 另一个模块,并将要使用的前缀与对那些导入组件的引用相关联,以防止名称冲突。

该插件定义了一个 "OpenDeclarationAction",它应该像 JDT 中的类似操作一样工作。当在对组件的引用上执行时,它将调出定义该组件的模块,并将光标放在组件的定义上。

我注意到这个插件有一个错误,如果工作区中有两个不同的项目有两个同名的文件,在这种自定义语言中,当我执行 "OpenDeclarationAction" 时,它只会打开在索引工作区时首先找到的模块,而不是首选与原始模块位于同一项目中的模块。

看components的内部索引时,发现并没有显示每个模块和组件来自哪个项目,所以我觉得解决这个问题很容易,因为当动作执行时,我可以比较当前项目与索引中条目的项目,只有匹配时才使用它。

然而,我意识到在我的自定义 TextEditorAction 中,它是从我的自定义 "org.eclipse.ui.editors.text.TextEditor" 子 class 实例化的,尽管我使用的 "index search" 函数可以接受 "project" 参数,我无法从 TextEditorAction 内部找到了解当前项目的方法。

例如,这是我的 "TextEditor" subclass 的摘录,我在其中创建了 TextEditorAction subclass (OpenDeclarationAction):

    @Override
protected void createActions() {

    super.createActions();
    IAction action = null;
    ResourceBundle bundle = ResourceBundle.getBundle(YangEditorMessages.getBundleName());

    action = new TextOperationAction(bundle, "ContentFormat_", this, ISourceViewer.FORMAT); //$NON-NLS-1$
    action.setActionDefinitionId(IYangEditorActionDefinitionIds.FORMAT);
    setAction("FormatDocument", action); //$NON-NLS-1$

    action = getAction(ITextEditorActionConstants.CONTENT_ASSIST_CONTEXT_INFORMATION);

    action = new OpenDeclarationAction(bundle, "OpenDeclaration_", this); //$NON-NLS-1$
    action.setActionDefinitionId(IYangEditorActionDefinitionIds.OPEN_DECLARATION);
    setAction("OpenDeclaration", action); //$NON-NLS-1$
    markAsStateDependentAction("OpenDeclaration", true); //$NON-NLS-1$
    markAsSelectionDependentAction("OpenDeclaration", true); //$NON-NLS-1$

这是我的一些 OpenDeclarationAction class:

public class OpenDeclarationAction extends TextEditorAction {

public OpenDeclarationAction(ResourceBundle bundle, String prefix, ITextEditor editor) {
    super(bundle, prefix, editor);
}

@Override
public void run() {
    YangEditor editor = (YangEditor) getTextEditor();

    try {
        ISelection selection = editor.getSelectionProvider().getSelection();
        Module module = YangParserUtil.parseYangFile(editor.getDocument().get().toCharArray());
        ASTNode node = module.getNodeAtPosition(((ITextSelection) selection).getOffset());

我已经研究了发送到 OpenDeclarationAction class 的所有参数,包括它们的所有 "get" 方法,以查看是否存在任何可能导致当前项目的调用链.这似乎是一个死胡同。如果该项目可用,我想一定有一些 "reverse" 数据结构可以从我拥有的其他数据中为我提供项目。

我知道这样的事情是可能的,因为我在两个不同的项目中用相同的 Java classes 试验了相同的情况。 Eclipse 总是将我发送到与参考相同的项目中的 class。

我应该如何设置才能满足我的要求?

ITextEditor.getEditorInput() may contain a descendant of IEditorInput which has IFile or URI 信息。鉴于这些,您可以通过调用 IFile.getProject() 或解析 URI 来派生 IProject。