org.eclipse.ui.viewActions

插件为工作台中已经存在的视图添加行为是很常见的。这是通过 org.eclipse.ui.viewActions 扩展点来完成的。此扩展点允许插件为现有视图的本地下拉菜单和本地工具栏添加菜单项、子菜单和工具栏条目。

您可能已经注意到,每当选择了自述文件时,就会启用导航器视图的本地工具栏中的项。此项也会出现在视图的本地下拉菜单中。这些操作出现的原因是自述文件工具使用 viewActions 扩展来添加它们。

下面是相关的 plugin.xml 添加项。

<extension
    point = "org.eclipse.ui.viewActions">
        <viewContribution 
            id="org.eclipse.ui.examples.readmetool.vc1" 
            targetID="org.eclipse.ui.views.ResourceNavigator">
                <action id="org.eclipse.ui.examples.readmetool.va1"
                    label="&amp;Readme View Extension"
                    menubarPath="additions"
                    toolbarPath="additions" 
                    icon="icons/basic/obj16/editor.gif" 
                    tooltip="Run Readme View Extension" 
                    helpContextId="org.eclipse.ui.examples.readmetool.view_action_context"
                    class="org.eclipse.ui.examples.readmetool.ViewActionDelegate"
                    enablesFor="1">
                    <selection class="org.eclipse.core.resources.IFile" name="*.readme"/>
                </action>
        </viewContribution>
</extension>

指定了具有唯一标识的视图添加项。在 targetID 中指定了我们正在将操作添加至的视图。正在为资源导航器视图的菜单添加操作。指定标号以及新操作的菜单栏和工具栏位置。(有关菜单和工具栏位置的完整讨论,参见菜单和工具栏路径)。

还要指定启用操作应该采用的条件。可以看到当有一个选择的类型为 IFile, 其名称的文件扩展名中具有“.readme”时,将启用此操作。的确,那刚好是当您单击资源导航器周围时所发生的情况。

plugin.xml 中的信息全部都是填充相应菜单和工具栏所需的。在从菜单或工具栏中实际选择操作之前,将不会运行任何插件代码。在 plugin.xml 中指定的实现类必须实现 IViewActionDelegate 接口。

在此示例中,自述文件插件提供了 ViewActionDelegate 来实现操作。如果您浏览此类,则将看到它包含用于处理选择更改、调用操作以及记住为哪些视图创建了该类的方法。

操作本身只启动一个对话框,它声明执行了视图操作。

public void run(org.eclipse.jface.action.IAction action) {
    MessageDialog.openInformation(view.getSite().getShell(),
        "Readme Editor", 
        "View Action executed");
}

尽管此操作很简单,但是我们可以想象通过使用选择和更多功能对话框如何使此操作执行更有意义的任务。