1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.g2d.participant;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.List;
18 import org.simantics.g2d.canvas.impl.AbstractCanvasParticipant;
19 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
20 import org.simantics.scenegraph.g2d.events.KeyEvent;
21 import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;
22 import org.simantics.scenegraph.g2d.events.KeyEvent.KeyPressedEvent;
23 import org.simantics.scenegraph.g2d.events.command.CommandEvent;
24 import org.simantics.scenegraph.g2d.events.command.CommandKeyBinding;
25 import org.simantics.scenegraph.g2d.events.command.Commands;
28 * Converts key presses to commands.
29 * Do not use this in eclipse environment, use XXXTODO instead which
30 * converts eclipse commands into g2d commands.
32 * CommandKeyBinding.DEFAULT_BINDINGS
34 * @See {@link CommandKeyBinding} command bindings
35 * @See {@link Commands} commands
36 * @author Toni Kalajainen
38 public class KeyToCommand extends AbstractCanvasParticipant {
40 @Dependency KeyUtil keyUtil;
41 List<CommandKeyBinding> binds = new ArrayList<CommandKeyBinding>();
43 public KeyToCommand(CommandKeyBinding... binds) {
45 for (CommandKeyBinding b : binds)
49 public KeyToCommand(Collection<CommandKeyBinding> binds) {
51 this.binds.addAll(binds);
54 public void addBinding(CommandKeyBinding binding) {
55 if (!this.binds.contains(binding))
56 this.binds.add(binding);
59 @EventHandler(priority = Integer.MIN_VALUE)
60 public boolean handleKeyEvent(KeyEvent e) {
61 //System.out.println("keytocommand " + e);
62 boolean pressed = (e instanceof KeyPressedEvent);
64 for (CommandKeyBinding ckb : binds) {
65 int keyCode = ckb.keyCode[0];
66 boolean _down = keyCode>0;
67 if (_down != pressed) continue;
68 if (!_down) keyCode = -keyCode;
69 if (e.keyCode != keyCode) continue;
70 for (int i=1; i<ckb.keyCode.length; i++) {
71 int code = ckb.keyCode[i];
72 boolean down = code>0;
73 if (!down) code = -code;
74 if (keyUtil.isKeyPressed(code) ^ down)
77 CommandEvent ce = new CommandEvent(getContext(), e.time, ckb.command);
78 getContext().getEventQueue().queueFirst(ce);