summaryrefslogtreecommitdiff
path: root/keyboardpython/key.py
blob: 0b6c36edcee44986f586e72468027bfea8e6b57f (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
ESC = '\x1b'
Erase = '\x7f'
Backspace = '\b'
Alert = '\a'
Tab = '\t'
vTab = '\v'
NL = '\n'
CR = '\r'

def _assert_type(thing,_type):
    ''' if thing is not of type _type raise an exception '''
    if type(thing) is not _type:
        raise(TypeError,
                "%s is of %s, should be of %s" % (str(thing),type(thing),_type)
            )

class KeyCombination:
    ''' multiple keyboard keys pressed in unison '''

    def __init__(self,*keys):
        for k in keys:
            assert isinstance(k,Key)
        self.keys = list(set(keys))
        self.keys.sort(key=lambda x: x.name)

    def __str__(self):
        keys = self.keys
        if not self.keys: return ''
        to_print = keys.pop(0).name
        while keys:
            to_print += ' %s' % keys.pop(0).name
        return to_print

    def __eq__(self,other):
        if not isinstance(other,KeyCombination): return False
        return str(self) == str(other)

    def __ne__(self,other):
        return not self.__eq__(self,other)

    def __hash__(self):
        return hash(str(self))

    def contains_key(self,key):
        if key in self.keys: return True
        return False

    def add_key(self,_key):
        assert isinstance(_key,Key)
        if self.contains_key(_key): return
        self.keys.append(_key)
        self.keys.sort(key=lambda x: x.name)

    def remove_key(self,key):
        assert isinstance(_key,Key)
        if key in self.keys:
            key_index = self.keys.index(key)
            self.keys.pop(key_index)

    def add_keyCombination(self,key_comb):
        assert isinstance(key_comb,KeyCombination)
        for _key in key_comb.keys:
            self.keys.append(_key)
        self.keys.sort(key=lambda x: x.name)

    def diff(self,key_comb):
        assert isinstance(key_comb,KeyCombination)
        to_return = KeyCombination()
        for _key in key_comb.keys:
            if not self.contains_key(_key):
                to_return.keys.append(_key)
        to_return.keys.sort(key=lambda x: x.name)
        return to_return

class Key:
    ''' a keyboard keypress object '''

    def __init__(self,name):
        _assert_type(name,str)
        self.name = name

    def __eq__(self,other):
        if not isinstance(other,Key): return False
        return str(self) == str(other)

    def __ne__(self,other):
        return not self.__eq__(self,other)

    def __hash__(self):
        return hash(str(self))

    def __str__(self):
        return self.name

ALT = Key('Alt')
CTRL = Key('Control')

_special_chars = {
        ' ': Key('Space'),
        ESC : Key('Escape'),
        Erase : Key('Erase'),
        NL: Key('Enter'),
        Tab: Key('Tab'),
        CR: Key('CR'),
        vTab: Key('vTab'),
        Alert: Key('Alert'),
        Backspace: Key('Backspace'),
    }
_escape_brace_codes = {
        'A': Key('Up'),
        'B': Key('Down'),
        'D': Key('Left'),
        'C': Key('Right'),
        '3~': Key('Del'),
        '2~': Key('Insert'),
        '5~': Key('PageUp'),
        '6~': Key('PageDown'),
        '15~': Key('F5'),
        '17~': Key('F6'),
        '18~': Key('F7'),
        '19~': Key('F8'),
        '20~': Key('F9'),
        '21~': Key('F10'),
        '23~': Key('F11'),
        '24~': Key('F12'),
    }
_escape_O_codes = {
        'F': Key('End'),
        'H': Key('Home'),
        'P': Key('F1'),
        'Q': Key('F2'),
        'R': Key('F3'),
        'S': Key('F4'),
    }

def _is_alt(code):
    ''' is this the code of a combination modified by Alt? '''
    _assert_type(code,str)
    if len(code) == 2 and code[0] == ESC:
        return True
    return False

def _is_ctrl_alpha(code):
    ''' is this the code of a combination modified by Ctrl? '''
    import sys, termios
    _assert_type(code,str)
    fd = sys.stdin.fileno()
    cc = termios.tcgetattr(fd)[-1]
    if code in cc: return False
    elif code in _special_chars.keys(): return False
    elif code < '\x20': return True
    else: return False

def _get_ctrl_alpha(code):
    ''' get alphabetic key modified by Ctrl '''
    _assert_type(code,str)
    letter = chr(ord(code) + 0x40)
    alpha_key = Key(letter)
    return KeyCombination(alpha_key,CTRL)

def parse_code(code):
    ''' get Key object from code '''
    _assert_type(code,str)
    to_return = KeyCombination()
    _code = list(code)
    while _code:
        char = _code.pop(0)
        if char == ESC:
            if not _code:
                key = _special_chars[ESC]
                to_return.add_key(key)
            elif _code[0] == '[':
                import re
                _code.pop(0)
                code_str = ''.join(_code)
                for c in _escape_brace_codes.keys():
                    match = re.search('^%s' % c,code_str)
                    if match:
                        key = _escape_brace_codes[match.string]
                        to_return.add_key(key)
                        len_match = len(match.string)
                        _code = _code[len_match:]
                        break
                    #TODO HACK - remove
                    else:
                        alt_code_str = re.sub(';3~','~',code_str)
                        match = re.search('^%s' % c,alt_code_str)
                        if match:
                            key = _escape_brace_codes[match.string]
                            to_return.add_key(key)
                            to_return.add_key(ALT)
                            len_match = len(match.string)
                            _code = _code[len_match+2:]
                            break
            elif _code[0] == 'O':
                _code.pop(0)
                char = _code.pop(0)
                # TODO HACK - remove
                if len(_code) > 1 and char == '1':
                    # alt F1 - alt F4, alt Del and alt Insert
                    key = _escape_O_codes[_code[3]]
                    to_return.add_key(key)
                    to_return.add_key(ALT)
                    _code = _code[4:]
                else:
                    key = _escape_O_codes[char]
                    to_return.add_key(key)
            else:
                to_return.add_key(ALT)
        elif char.isalnum():
            to_return.add_key(Key(char))
        elif _is_ctrl_alpha(char):
            key_comb =  _get_ctrl_alpha(char)
            to_return.add_keyCombination(key_comb)
        elif char in _special_chars.keys():
            key = _special_chars[char]
            to_return.add_key(key)
        else:
            to_return.add_key(Key(char))
    return to_return