aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/vaadin/terminal/gwt/client/ui/ShortcutActionHandler.java
blob: 934fcaa8b79acdec8d9a52e5ce2f3b9fc3c6c0fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/* 
@VaadinApache2LicenseForJavaFiles@
 */

package com.vaadin.terminal.gwt.client.ui;

import java.util.ArrayList;
import java.util.Iterator;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.KeyboardListenerCollection;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.ui.richtextarea.VRichTextArea;

/**
 * A helper class to implement keyboard shorcut handling. Keeps a list of owners
 * actions and fires actions to server. User class needs to delegate keyboard
 * events to handleKeyboardEvents function.
 * 
 * @author Vaadin Ltd
 */
public class ShortcutActionHandler {

    /**
     * An interface implemented by those users (most often {@link Container}s,
     * but HasWidgets at least) of this helper class that want to support
     * special components like {@link VRichTextArea} that don't properly
     * propagate key down events. Those components can build support for
     * shortcut actions by traversing the closest
     * {@link ShortcutActionHandlerOwner} from the component hierarchy an
     * passing keydown events to {@link ShortcutActionHandler}.
     */
    public interface ShortcutActionHandlerOwner extends HasWidgets {

        /**
         * Returns the ShortCutActionHandler currently used or null if there is
         * currently no shortcutactionhandler
         */
        ShortcutActionHandler getShortcutActionHandler();
    }

    /**
     * A focusable {@link Paintable} implementing this interface will be
     * notified before shortcut actions are handled if it will be the target of
     * the action (most commonly means it is the focused component during the
     * keyboard combination is triggered by the user).
     */
    public interface BeforeShortcutActionListener extends Paintable {
        /**
         * This method is called by ShortcutActionHandler before firing the
         * shortcut if the Paintable is currently focused (aka the target of the
         * shortcut action). Eg. a field can update its possibly changed value
         * to the server before shortcut action is fired.
         * 
         * @param e
         *            the event that triggered the shortcut action
         */
        public void onBeforeShortcutAction(Event e);
    }

    private final ArrayList<ShortcutAction> actions = new ArrayList<ShortcutAction>();
    private ApplicationConnection client;
    private String paintableId;

    /**
     * 
     * @param pid
     *            Paintable id
     * @param c
     *            reference to application connections
     */
    public ShortcutActionHandler(String pid, ApplicationConnection c) {
        paintableId = pid;
        client = c;
    }

    /**
     * Updates list of actions this handler listens to.
     * 
     * @param c
     *            UIDL snippet containing actions
     */
    public void updateActionMap(UIDL c) {
        actions.clear();
        final Iterator<?> it = c.getChildIterator();
        while (it.hasNext()) {
            final UIDL action = (UIDL) it.next();

            int[] modifiers = null;
            if (action.hasAttribute("mk")) {
                modifiers = action.getIntArrayAttribute("mk");
            }

            final ShortcutKeyCombination kc = new ShortcutKeyCombination(
                    action.getIntAttribute("kc"), modifiers);
            final String key = action.getStringAttribute("key");
            final String caption = action.getStringAttribute("caption");
            actions.add(new ShortcutAction(key, kc, caption));
        }
    }

    public void handleKeyboardEvent(final Event event, Paintable target) {
        final int modifiers = KeyboardListenerCollection
                .getKeyboardModifiers(event);
        final char keyCode = (char) DOM.eventGetKeyCode(event);
        final ShortcutKeyCombination kc = new ShortcutKeyCombination(keyCode,
                modifiers);
        final Iterator<ShortcutAction> it = actions.iterator();
        while (it.hasNext()) {
            final ShortcutAction a = it.next();
            if (a.getShortcutCombination().equals(kc)) {
                fireAction(event, a, target);
                break;
            }
        }

    }

    public void handleKeyboardEvent(final Event event) {
        handleKeyboardEvent(event, null);
    }

    private void fireAction(final Event event, final ShortcutAction a,
            Paintable target) {
        final Element et = DOM.eventGetTarget(event);
        if (target == null) {
            Widget w = Util.findWidget(et, null);
            while (w != null && !(w instanceof Paintable)) {
                w = w.getParent();
            }
            target = (Paintable) w;
        }
        final Paintable finalTarget = target;

        event.preventDefault();

        /*
         * The target component might have unpublished changes, try to
         * synchronize them before firing shortcut action.
         */
        if (finalTarget instanceof BeforeShortcutActionListener) {
            ((BeforeShortcutActionListener) finalTarget)
                    .onBeforeShortcutAction(event);
        } else {
            shakeTarget(et);
            Scheduler.get().scheduleDeferred(new Command() {
                public void execute() {
                    shakeTarget(et);
                }
            });
        }

        Scheduler.get().scheduleDeferred(new Command() {
            public void execute() {
                if (finalTarget != null) {
                    client.updateVariable(paintableId, "actiontarget",
                            finalTarget, false);
                }
                client.updateVariable(paintableId, "action", a.getKey(), true);
            }
        });
    }

    /**
     * We try to fire value change in the component the key combination was
     * typed. Eg. textfield may contain newly typed text that is expected to be
     * sent to server. This is done by removing focus and then returning it
     * immediately back to target element.
     * <p>
     * This is practically a hack and should be replaced with an interface
     * {@link BeforeShortcutActionListener} via widgets could be notified when
     * they should fire value change. Big task for TextFields, DateFields and
     * various selects.
     * 
     * <p>
     * TODO separate opera impl with generator
     */
    private static void shakeTarget(final Element e) {
        blur(e);
        if (BrowserInfo.get().isOpera()) {
            // will mess up with focus and blur event if the focus is not
            // deferred. Will cause a small flickering, so not doing it for all
            // browsers.
            Scheduler.get().scheduleDeferred(new Command() {
                public void execute() {
                    focus(e);
                }
            });
        } else {
            focus(e);
        }
    }

    private static native void blur(Element e)
    /*-{
        if(e.blur) {
            e.blur();
       }
    }-*/;

    private static native void focus(Element e)
    /*-{
        if(e.blur) {
            e.focus();
       }
    }-*/;

}

class ShortcutKeyCombination {

    public static final int SHIFT = 16;
    public static final int CTRL = 17;
    public static final int ALT = 18;
    public static final int META = 91;

    char keyCode = 0;
    private int modifiersMask;

    public ShortcutKeyCombination() {
    }

    ShortcutKeyCombination(char kc, int modifierMask) {
        keyCode = kc;
        modifiersMask = modifierMask;
    }

    ShortcutKeyCombination(int kc, int[] modifiers) {
        keyCode = (char) kc;

        modifiersMask = 0;
        if (modifiers != null) {
            for (int i = 0; i < modifiers.length; i++) {
                switch (modifiers[i]) {
                case ALT:
                    modifiersMask = modifiersMask
                            | KeyboardListener.MODIFIER_ALT;
                    break;
                case CTRL:
                    modifiersMask = modifiersMask
                            | KeyboardListener.MODIFIER_CTRL;
                    break;
                case SHIFT:
                    modifiersMask = modifiersMask
                            | KeyboardListener.MODIFIER_SHIFT;
                    break;
                case META:
                    modifiersMask = modifiersMask
                            | KeyboardListener.MODIFIER_META;
                    break;
                default:
                    break;
                }
            }
        }
    }

    public boolean equals(ShortcutKeyCombination other) {
        if (keyCode == other.keyCode && modifiersMask == other.modifiersMask) {
            return true;
        }
        return false;
    }
}

class ShortcutAction {

    private final ShortcutKeyCombination sc;
    private final String caption;
    private final String key;

    public ShortcutAction(String key, ShortcutKeyCombination sc, String caption) {
        this.sc = sc;
        this.key = key;
        this.caption = caption;
    }

    public ShortcutKeyCombination getShortcutCombination() {
        return sc;
    }

    public String getCaption() {
        return caption;
    }

    public String getKey() {
        return key;
    }

}