RCP:解决Navigator快捷键不生效的问题

简介: 自己扩展CNF之后,导航栏的删除、复制、黏贴等快捷键失效了,在网上搜索了半天,结果最终不如自己看源码。 本篇文章的主要目的不止于解决快捷键失效,更在于如何处理类似的问题,如何利用debug快速定位。这种解决问题的思路能帮助我们更加理解他人的代码,快速熟悉一套陌生的框架。

自己扩展CNF之后,导航栏的删除、复制、黏贴等快捷键失效了,在网上搜索了半天,结果最终不如自己看源码。

本篇文章的主要目的不止于解决快捷键失效,更在于如何处理类似的问题,如何利用debug快速定位。这种解决问题的思路能帮助我们更加理解他人的代码,快速熟悉一套陌生的框架。

 

1、理解问题的本质,为什么按键不生效?

在解决快捷键失效问题之前,我们需要理解快捷键是如何生效的。

为了更直观的理解,请使用debug模式打开一个新的Eclipse IDE,然后,对org.eclipse.jdt.internal.ui.refactoring.reorg.CopyToClipboardAction这个类的run方法加上断点。在新的EclipseIDE的Package Explorer上选中一个节点,按CTRL+C

在DEBUG视图中显示如下图所示:

 

我们过一眼这些类名和方法名,如果你是个有经验的程序员,那么,你应当能敏感的发现WorkbenchKeyboard就是是你需要的那个类。

我们看看executeCommand方法,关键代码标记上了红色。

    final boolean executeCommand(final Binding binding, final Event trigger)
            throws CommandException {
        final ParameterizedCommand parameterizedCommand = binding
                .getParameterizedCommand();

        if (DEBUG) {
            Tracing.printTrace("KEYS", //$NON-NLS-1$
                    "WorkbenchKeyboard.executeCommand(commandId = '" //$NON-NLS-1$
                            + parameterizedCommand.getId() + "', parameters = " //$NON-NLS-1$
                            + parameterizedCommand.getParameterMap() + ')');
        }

        // Reset the key binding state (close window, clear status line, etc.)
        resetState(false);

        // Dispatch to the handler.
        final IHandlerService handlerService = (IHandlerService) workbench
                .getService(IHandlerService.class);
        final Command command = parameterizedCommand.getCommand();
        final boolean commandDefined = command.isDefined();
        final boolean commandHandled = command.isHandled();
        command.setEnabled(handlerService.getCurrentState());
        final boolean commandEnabled = command.isEnabled();

        if (DEBUG && DEBUG_VERBOSE) {
            if (!commandDefined) {
                Tracing.printTrace("KEYS", "    not defined"); //$NON-NLS-1$ //$NON-NLS-2$
            } else if (!commandHandled) {
                Tracing.printTrace("KEYS", "    not handled"); //$NON-NLS-1$ //$NON-NLS-2$
            } else if (!commandEnabled) {
                Tracing.printTrace("KEYS", "    not enabled"); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }

        try {
            handlerService.executeCommand(parameterizedCommand, trigger);
        } catch (final NotDefinedException e) {
            // The command is not defined. Forwarded to the IExecutionListener.
        } catch (final NotEnabledException e) {
            // The command is not enabled. Forwarded to the IExecutionListener.
        } catch (final NotHandledException e) {
            // There is no handler. Forwarded to the IExecutionListener.
        }

        /*
         * Now that the command has executed (and had the opportunity to use the
         * remembered state of the dialog), it is safe to delete that
         * information.
         */
        if (keyAssistDialog != null) {
            keyAssistDialog.clearRememberedState();
        }

        return (commandDefined && commandHandled);
    }

 

我们发现了binding这个对象。binding的注释如下:

org.eclipse.jface.bindings.Binding



A binding is a link between user input and the triggering of a particular command. The most common example of a binding is a keyboard shortcut, but there are also mouse and gesture bindings. 
View Code

看第一段,就能明白,binding是用来做按键和command绑定的,command是最终的执行。

在debug模式下把鼠标放在binding对象上按F2,如下图所示:

 

相信你已经看到了关键部分,ActionHandler(CopyToClipAction);

是的,只要这里出现了ActionHandler和你的事件,就说明,绑定成功了。反之,则没有。

 

2、如何建立绑定关系?

通过上面的debug追溯过程,我们发现绑定服务源自org.eclipse.ui.internal.keys.WorkbenchKeyboard.isPartialMatch方法。代码如下:

    /**
     * Determines whether the key sequence partially matches on of the active
     * key bindings.
     * 
     * @param keySequence
     *            The key sequence to check for a partial match; must never be
     *            <code>null</code>.
     * @return <code>true</code> if there is a partial match;
     *         <code>false</code> otherwise.
     */
    private boolean isPartialMatch(KeySequence keySequence) {
        return getBindingService().isPartialMatch(keySequence);
    }

 

getBindingService()方法返回一个IBindingService对象,注释如下,关键部分红色粗体字标注:

Provides services related to the binding architecture (e.g., keyboard shortcuts) within the workbench. This service can be used to access the currently active bindings, as well as the current state of the binding architecture. 

This service can be acquired from your service locator: 

     IBindingService service = (IBindingService) getSite().getService(IBindingService.class);
 
This service is available globally. 

getSite()指的是workbenchPart.getSite(),返回的是org.eclipse.ui.IWorkbenchPartSite对象。它是视图、编辑器(工作区部件)和工作区的原生接口,用于它们之间的交互协同。

你可以在任何地方得到它。

所以,你只需要使用它来注册你需要绑定的command,即可。

常用command譬如"org.eclipse.ui.edit.delete","org.eclipse.ui.edit.copy"

 

3、更加推荐的方式

很多人为导航器提供了ActionProvider,在默认情况下复制、删除、黏贴等action都会被正确的触发。

如果不行,则需要理解以下几个对象:

a、org.eclipse.jface.action.Action.getActionDefinitionId()

用于匹配commandId,该ID如果和注册了快捷键的commandId匹配,该action的run会被调用。

 

b、org.eclipse.ui.internal.handlers.IActionCommandMappingService

如果你使用了TextActionHandler之类的工具,你会发现上述内容失效了。

这是因为TextActionHandler对CopyAction等做了多一层封装,这时,你需要使用该类,对actionId和commandId多一次处理。

用于actionId和commandId的绑定,可以通过getSite().getService(IActionCommandMappingService.class)获取

我们可以看以下代码,org.eclipse.ui.SubActionBars.setGlobalActionHandler(String actionID, IAction handler),关键部分已标注红色:

    public void setGlobalActionHandler(String actionID, IAction handler) {
        if (actionID == null) {
            /*
             * Bug 124061. It used to be invalid to pass null as an action id,
             * but some people still did it. Handle this case by trapping the
             * exception and logging it.
             */
            WorkbenchPlugin
                    .log("Cannot set the global action handler for a null action id"); //$NON-NLS-1$
            return;
        }
        
        if (handler instanceof CommandLegacyActionWrapper) {
            // this is a registration of a fake action for an already
            // registered handler
            WorkbenchPlugin
                    .log("Cannot feed a CommandLegacyActionWrapper back into the system"); //$NON-NLS-1$
            return;
        }
        
        if (handler instanceof CommandAction) {
            // we unfortunately had to allow these out into the wild, but they
            // still must not feed back into the system
            return;
        }
        
        if (handler != null) {
            // Update the action handlers.
            if (actionHandlers == null) {
                actionHandlers = new HashMap(11);
            }
            actionHandlers.put(actionID, handler);

            // Add a mapping from this action id to the command id.
            if (serviceLocator != null) {
                String commandId = null;
                final IActionCommandMappingService mappingService = (IActionCommandMappingService) serviceLocator
                        .getService(IActionCommandMappingService.class);
                if (mappingService != null) {
                    commandId = mappingService.getCommandId(actionID);
                }
                if (commandId == null) {
                    commandId = handler.getActionDefinitionId();
                }

                // Update the handler activations.
                final IHandlerService service = (IHandlerService) serviceLocator
                        .getService(IHandlerService.class);
                Map activationsByActionId = null;
                if (activationsByActionIdByServiceLocator == null) {
                    activationsByActionIdByServiceLocator = new WeakHashMap();
                    activationsByActionId = new HashMap();
                    activationsByActionIdByServiceLocator.put(serviceLocator,
                            activationsByActionId);
                } else {
                    activationsByActionId = (Map) activationsByActionIdByServiceLocator
                            .get(serviceLocator);
                    if (activationsByActionId == null) {
                        activationsByActionId = new HashMap();
                        activationsByActionIdByServiceLocator.put(
                                serviceLocator, activationsByActionId);
                    } else if (activationsByActionId.containsKey(actionID)) {
                        final Object value = activationsByActionId
                                .remove(actionID);
                        if (value instanceof IHandlerActivation) {
                            final IHandlerActivation activation = (IHandlerActivation) value;
                            actionIdByCommandId.remove(activation.getCommandId());
                            if (service != null) {
                                service.deactivateHandler(activation);
                            }
                            activation.getHandler().dispose();
                        }
                    } else if (commandId != null
                            && actionIdByCommandId.containsKey(commandId)) {
                        final Object value = activationsByActionId
                                .remove(actionIdByCommandId.remove(commandId));
                        if (value instanceof IHandlerActivation) {
                            final IHandlerActivation activation = (IHandlerActivation) value;
                            if (service != null) {
                                service.deactivateHandler(activation);
                            }
                            activation.getHandler().dispose();
                        }
                    }
                }

                if (commandId != null) {
                    actionIdByCommandId.put(commandId, actionID);
                    // Register this as a handler with the given definition id.
                    // the expression gives the setGlobalActionHandler() a
                    // priority.
                    final IHandler actionHandler = new ActionHandler(handler);
                    Expression handlerExpression = EXPRESSION;
                    //XXX add new API in next release to avoid down-casting (bug 137091)
                    if (this instanceof EditorActionBars) {
                        handlerExpression = ((EditorActionBars)this).getHandlerExpression();
                    }
                    if (service != null) {
                        final IHandlerActivation activation = service
                                .activateHandler(commandId, actionHandler,
                                        handlerExpression);
                        activationsByActionId.put(actionID, activation);
                    }
                }
            }

        } else {
            if (actionHandlers != null) {
                actionHandlers.remove(actionID);
            }

            // Remove the handler activation.
            if (serviceLocator != null) {
                final IHandlerService service = (IHandlerService) serviceLocator
                        .getService(IHandlerService.class);
                if (activationsByActionIdByServiceLocator != null) {
                    final Map activationsByActionId = (Map) activationsByActionIdByServiceLocator
                            .get(serviceLocator);
                    if ((activationsByActionId != null)
                            && (activationsByActionId.containsKey(actionID))) {
                        final Object value = activationsByActionId
                                .remove(actionID);
                        if (value instanceof IHandlerActivation) {
                            final IHandlerActivation activation = (IHandlerActivation) value;
                            actionIdByCommandId.remove(activation.getCommandId());
                            service.deactivateHandler(activation);
                            activation.getHandler().dispose();
                        }
                    }
                }
            }
        }
        actionHandlersChanged = true;
    }

可以看到,commandId的来源,一是从IActionCommandMappingService,再是从action的getActionDefinitionId()。

如果都不行,再是其他处理(暂不表)。

该方式代码示例如下:

IActionCommandMappingService acms = (IActionCommandMappingService) getViewSite()
                .getWorkbenchWindow().getService(
                        IActionCommandMappingService.class);
        String deleteId = acms.getCommandId("delete");
        if (deleteId == null)
            acms.map("delete", "org.eclipse.ui.edit.delete");

 

目录
相关文章
|
C++
VS Code识别编辑规范,ESlint规则,VS Code保存去掉自动加分号、逗号、双引号
书写规范是非常重要的,除了统一,还要简洁。 1、VS Code识别编辑规范 在项目根目录新建.editorconfig文件,加入设置:
1572 0
|
安全 芯片 Windows
U盘插上后显示为空?其实数据没丢,可以这样恢复
U盘变空并不等于数据丢失!本文详解U盘插入提示“格式化”、显示为空等常见问题的原因,教你如何在不格式化的前提下恢复数据,修复异常,并避免再次发生。内容涵盖逻辑错误识别、恢复软件使用步骤及U盘是否还能继续使用的判断方法,助你轻松应对U盘故障。
|
人工智能 固态存储 IDE
Android Studio 2025 超详细安装图解:从零到汉化一步到位
Android Studio 2025(Narwhal)是谷歌推出的最新安卓开发IDE,界面更现代,支持AI辅助编码、Jetpack Compose升级、多设备模拟器,构建速度更快,适配折叠屏等新形态设备,全面提升开发效率。
5353 2
|
安全 编译器 C++
constexpr、const和 #define 的比较
本文比较了 `constexpr`、`const` 和 `#define` 在 C++ 中定义常量和函数的优缺点。`constexpr` 用于编译期求值,提供更高的性能和类型安全性;`const` 保证变量在运行期间不可修改,增强代码可靠性;`#define` 用于宏定义,适用于简单的常量和跨平台兼容性。选择时应根据具体需求和代码上下文决定。
|
运维 负载均衡 监控
确保网络设计中的冗余和高可用性
【8月更文挑战第24天】
2327 0
|
监控 安全 搜索推荐
深度解析:国有企业数字化转型的背景、现状与思路
本文从国有企业在数字化大潮中的使命担当说起,对国有企业数字化转型现状进行思考,提出国企数字化转型思考框架及实现路径,并进一步对国有企业数字化典型场景及价值回报进行分析,提供典型国有企业数字化转型具体案例,供读者思考和实操参考。
|
机器学习/深度学习 传感器 安全
基于云的强化学习在汽车控制功能开发中的应用
摘要 汽车控制功能变得越来越复杂,其开发也越来越精细,这导致在开发过程中强烈需要自动化解决方案。在这里,强化学习为功能开发提供了巨大的潜力,可以以自动化的方式生成优化的控制功能。尽管它成功地部署在各种控制任务中,但在汽车行业中仍然缺乏基于强化学习的功能开发标准工具解决方案。为了解决这一差距,我们提出了一个灵活的框架,将传统的开发过程与开源的强化学习库相结合。它具有相关车辆部件的模块化物理模型、与微观交通模拟的协同模拟以生成真实场景,并实现分布式和并行训练。我们在一项可行性研究中证明了我们提出的方法的有效性,该研究旨在学习城市交通场景中电动汽车自动纵向控制的控制函数。进化的控制策略产生了一个平滑
819 0
|
消息中间件 数据可视化 API
Windows 下安装 RabbitMQ 服务器及基本配置
Windows 下安装 RabbitMQ 服务器及基本配置
1074 0
Windows 下安装 RabbitMQ 服务器及基本配置
|
机器学习/深度学习 计算机视觉 Python
用Python写一份独特的元宵节祝福
首先是点阵字的概念:点阵字体是把每一个字符都分成 n * n 个点,然后用每个点的虚实来表示字符的轮廓。点阵字体也叫位图字体,其中每个字形都以一组二维像素信息表示。
510 0
|
Android开发
【Android 应用开发】Android 上实现非root的 Traceroute -- 非Root权限下移植可执行二进制文件 脚本文件(二)
【Android 应用开发】Android 上实现非root的 Traceroute -- 非Root权限下移植可执行二进制文件 脚本文件(二)
557 0
【Android 应用开发】Android 上实现非root的 Traceroute -- 非Root权限下移植可执行二进制文件 脚本文件(二)