aboutsummaryrefslogtreecommitdiffhomepage
path: root/examples/data/uzbl/scripts/plugins/keycmd.py
blob: 96e61b480425478182ee5940d8b6209de9b506e7 (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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import re

# Map these functions/variables in the plugins namespace to the uzbl object.
__export__ = ['clear_keycmd',]

# Regular expression compile cache.
_RE_CACHE = {}

# Hold the keylets.
UZBLS = {}

# Simple key names map.
_SIMPLEKEYS = {
  'Control': 'Ctrl',
  'ISO_Left_Tab': 'Shift-Tab',
  'space':'Space',
}


def keycmd_escape(keycmd):
    '''Prevent outgoing keycmd values from expanding inside the
    status_format.'''

    for char in ['\\', '@']:
        if char in keycmd:
            keycmd = keycmd.replace(char, '\\'+char)

    return keycmd


def get_regex(regex):
    '''Compiling regular expressions is a very time consuming so return a
    pre-compiled regex match object if possible.'''

    if regex not in _RE_CACHE:
        _RE_CACHE[regex] = re.compile(regex).match

    return _RE_CACHE[regex]


class Keylet(object):
    '''Small per-instance object that tracks all the keys held and characters
    typed.'''

    def __init__(self):
        self.cmd = ''
        self.cmd_s = ''
        self.held = []

        # to_string() string building cache.
        self._to_string = None

        self.modcmd = False
        self.wasmod = False

    def __repr__(self):
        return '<Keycmd(%r)>' % self.to_string()


    def to_string(self):
        '''Return a string representation of the keys held and pressed that
        have been recorded.'''

        if self._to_string is not None:
            # Return cached keycmd string.
            return self._to_string

        if not self.held:
            self._to_string = self.cmd + self.cmd_s

        else:
            self._to_string = ''.join(['<%s>' % key for key in self.held])
            if self.cmd or self.cmd_s:
                self._to_string += '%s%s' % (self.cmd, self.cmd_s)

        return self._to_string


    def match(self, regex):
        '''See if the keycmd string matches the given regex.'''

        return bool(get_regex(regex)(self.to_string()))


def make_simple(key):
    '''Make some obscure names for some keys friendlier.'''

    # Remove left-right discrimination.
    if key.endswith('_L') or key.endswith('_R'):
        key = key[:-2]

    if key in _SIMPLEKEYS:
        key = _SIMPLEKEYS[key]

    return key


def add_instance(uzbl, *args):
    '''Create the Keylet object for this uzbl instance.'''

    UZBLS[uzbl] = Keylet()


def del_instance(uzbl, *args):
    '''Delete the Keylet object for this uzbl instance.'''

    if uzbl in UZBLS:
        del UZBLS[uzbl]


def get_keylet(uzbl):
    '''Return the corresponding keylet for this uzbl instance.'''

    # Startup events are not correctly captured and sent over the uzbl socket
    # yet so this line is needed because the INSTANCE_START event is lost.
    if uzbl not in UZBLS:
        add_instance(uzbl)

    keylet = UZBLS[uzbl]
    keylet._to_string = None
    return keylet


def clear_keycmd(uzbl):
    '''Clear the keycmd for this uzbl instance.'''

    k = get_keylet(uzbl)
    if not k:
        return

    k.cmd = k.cmd_s = ''
    k._to_string = None

    if k.modcmd:
        k.wasmod = True

    k.modcmd = False
    config = uzbl.get_config()
    if 'keycmd' not in config or config['keycmd'] != '':
        config['keycmd'] = ''

    uzbl.event('KEYCMD_CLEAR')


def update_event(uzbl, keylet):
    '''Raise keycmd/modcmd update events.'''

    config = uzbl.get_config()

    if keylet.modcmd:
        keycmd = keylet.to_string()
        uzbl.event('MODCMD_UPDATE', keylet)
        if keycmd != keylet.to_string():
            return

        if 'modcmd_updates' in config and config['modcmd_updates'] != '1':
            return

    elif 'keycmd_events' not in config or config['keycmd_events'] == '1':
        keycmd = keylet.cmd + keylet.cmd_s
        uzbl.event('KEYCMD_UPDATE', keylet)
        if keycmd != (keylet.cmd + keylet.cmd_s):
            return

    uzbl.set('keycmd', keycmd_escape(keycmd))


def key_press(uzbl, key):
    '''Handle KEY_PRESS events. Things done by this function include:

    1. Ignore all shift key presses (shift can be detected by capital chars)
    2. Re-enable modcmd var if the user presses another key with at least one
       modkey still held from the previous modcmd (I.e. <Ctrl>+t, clear &
       <Ctrl>+o without having to re-press <Ctrl>)
    3. In non-modcmd mode:
         a. BackSpace deletes the last character in the keycmd.
         b. Return raises a KEYCMD_EXEC event then clears the keycmd.
         c. Escape clears the keycmd.
    4. If keycmd and held keys are both empty/null and a modkey was pressed
       set modcmd mode.
    5. If in modcmd mode only mod keys are added to the held keys list.
    6. Keycmd is updated and events raised if anything is changed.'''

    if key.startswith('Shift_'):
        return

    if len(key) > 1:
        key = make_simple(key)

    k = get_keylet(uzbl)
    if not k:
        return

    print k.held, k.modcmd, k.wasmod, k.cmd, k.cmd_s
    cmdmod = False
    if k.held and k.wasmod:
        k.modcmd = True
        k.wasmod = False
        cmdmod = True

    if (k.cmd or k.cmd_s) and key == 'Space':
        k.cmd += ' '
        cmdmod = True

    elif not k.modcmd and key == 'BackSpace':
        if k.cmd:
            k.cmd = k.cmd[:-1]
            if not k.cmd:
                clear_keycmd(uzbl)

            else:
                cmdmod = True

    elif not k.modcmd and key == 'Left':
        if k.cmd:
            k.cmd_s = k.cmd[-1] + k.cmd_s
            k.cmd = k.cmd[:-1]
            cmdmod = True

    elif not k.modcmd and key == 'Right':
        if k.cmd_s:
            k.cmd = k.cmd + k.cmd_s[0]
            k.cmd_s = k.cmd_s[1:]
            cmdmod = True

    elif not k.modcmd and key == 'Return':
        if k.cmd:
            uzbl.event('KEYCMD_EXEC', k)

        clear_keycmd(uzbl)

    elif not k.modcmd and key == 'Escape':
        clear_keycmd(uzbl)

    elif not k.modcmd and key == 'Ctrl':
           k.held.append(key)

    elif not k.modcmd and k.held and len(key) == 1:
        if key == 'w':
            cmdmod = True
            k.cmd = ' '.join(k.cmd.split(' ')[:-1])
        elif key == 'a':
            k.cmd_s = k.cmd + k.cmd_s
            k.cmd = ''
        elif key == 'e':
            k.cmd = k.cmd + k.cmd_s
            k.cmd_s = ''

    elif not k.held and not k.cmd and len(key) > 1:
        k.modcmd = True
        k.held.append(key)
        cmdmod = True

    elif k.modcmd:
        cmdmod = True
        if len(key) > 1:
            if key == 'Shift-Tab' and 'Tab' in k.held:
                k.held.remove('Tab')

            if key not in k.held:
                k.held.append(key)
                k.held.sort()

        else:
            k.cmd += key

    else:
        config = uzbl.get_config()
        if 'keycmd_events' not in config or config['keycmd_events'] == '1':
            if len(key) == 1:
                cmdmod = True
                k.cmd += key

        elif k.cmd or k.cmd_s:
            cmdmod = True
            k.cmd = k.cmd_s = ''

    if cmdmod:
        update_event(uzbl, k)


def key_release(uzbl, key):
    '''Respond to KEY_RELEASE event. Things done by this function include:

    1. Remove the key from the keylet held list.
    2. If the key removed was a mod key and it was in a mod-command then
       raise a MODCMD_EXEC event then clear the keycmd.
    3. Stop trying to restore mod-command status with wasmod if both the
       keycmd and held list are empty/null.
    4. Update the keycmd uzbl variable if anything changed.'''

    if len(key) > 1:
        key = make_simple(key)

    k = get_keylet(uzbl)
    if not k:
        return

    cmdmod = False
    if key in ['Shift', 'Tab'] and 'Shift-Tab' in k.held:
        key = 'Shift-Tab'

    elif key in ['Shift', 'Alt'] and 'Meta' in k.held:
        key = 'Meta'

    if key in k.held:
        if k.modcmd:
            uzbl.event('MODCMD_EXEC', k)

        k.held.remove(key)
        clear_keycmd(uzbl)

    if not k.held and not k.cmd and k.wasmod:
        k.wasmod = False

    if cmdmod:
       update_event(uzbl, k)


def config_changed(uzbl, key, value):
    '''Check for external keycmd updates and update the keylet accordingly.'''

    if key == 'keycmd':
        k = get_keylet(uzbl)
        if value != k.cmd + k.cmd_s:
            k.cmd = value
            k.cmd_s = ''


def init(uzbl):
    '''Connect handlers to uzbl events.'''

    connects = {'INSTANCE_START': add_instance,
      'INSTANCE_EXIT': del_instance,
      'KEY_PRESS': key_press,
      'KEY_RELEASE': key_release,
      'CONFIG_CHANGED': config_changed}

    uzbl.connect_dict(connects)