001    // GraphLab Project: http://graphlab.sharif.edu
002    // Copyright (C) 2008 Mathematical Science Department of Sharif University of Technology
003    // Distributed under the terms of the GNU General Public License (GPL): http://www.gnu.org/licenses/
004    package graphlab.ui.components.gmenu;
005    
006    import java.awt.event.InputEvent;
007    import java.awt.event.KeyEvent;
008    import java.util.HashMap;
009    
010    /**
011     * @author Rouzbeh Ebrahimi
012     */
013    public class KeyBoardShortCutProvider {
014        public static HashMap<String, KeyBoardShortCut> shortCuts = new HashMap<String, KeyBoardShortCut>();
015    
016        public static KeyBoardShortCut registerKeyBoardShortcut(String accelerator, String label, int index) {
017            if (label == null) return null;
018            int ind = index;
019            //int mod = extractModifiers(accelerator);
020            int mne = extractMnemonics(label, ind);
021            ind = Math.max(ind, 0);
022            boolean isAccel = true;
023            KeyBoardShortCut k;
024            if (accelerator == null) {
025                isAccel = false;
026                k = new KeyBoardShortCut(mne, ind, isAccel);
027    
028            } else {
029                int mod = extractModifiers(accelerator);
030                int keyEvent = extractKeyEvent(accelerator);
031                k = new KeyBoardShortCut(keyEvent, mod, ind, isAccel, mne);
032            }
033    
034            shortCuts.put(label, k);
035            return k;
036        }
037    
038        static int extractModifiers(String Acc) {
039            Acc = Acc.toLowerCase();
040            boolean isControl = Acc.indexOf("control") != -1;
041            boolean isShift = Acc.indexOf("shift") != -1;
042            boolean isAlt = Acc.indexOf("alt") != -1;
043            int control = (isControl ? InputEvent.CTRL_MASK : 0);
044            int shift = (isShift ? InputEvent.SHIFT_MASK : 0);
045            int alt = (isAlt ? InputEvent.ALT_MASK : 0);
046            return control + alt + shift;
047        }
048    
049        static int extractMnemonics(String priLabel, int index) {
050            return priLabel.charAt(index);
051        }
052    
053        //todo: provide the way that defining accelerator for keys like delete, insert, ... be possible, by iterating over integers and KeyEvent.getKeyText, or probably the reflection
054        static int extractKeyEvent(String accelerator) {
055            if (!accelerator.equals("+")) {
056                int i = accelerator.lastIndexOf('+') + 1;
057                return accelerator.charAt(i);
058            } else
059                return KeyEvent.VK_PLUS;
060        }
061    
062        static int extractindex(String index) {
063            if (index != null) {
064                return Integer.parseInt(index);
065            }
066            return 0;
067        }
068    }
069