-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathActions.py
546 lines (470 loc) · 17.8 KB
/
Actions.py
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
import mdlog
log = mdlog.getLogger(__name__)
import subprocess
import re
import string
import operator
from copy import copy
from listHelpers import dictReplace
from Window import Window, getFocusedWindow
from util import deepEmpty
from unicodedata import category
def strip_punctuation(word):
# taken from: http://stackoverflow.com/a/11066443
# by: Daenyth
return u"".join(char for char in word if not category(char).startswith('P'))
def runCmd(cmd):
log.info('cmd: [' + cmd + ']')
# TODO: why calling with shell?!
subprocess.call(cmd, shell=True)
def splitKeyString(keyStr):
"""Translate dragonfly style key descriptions
with numeric repeating into a key description
without repetition."""
# dragonfly uses comma sep keys, xdotool uses spaces
singles = keyStr.split(',')
keys = []
for s in singles:
if ':' in s:
key, count = s.split(':')
count = int(count)
else:
key, count = s, 1
keys.extend([key] * count)
return keys
def parseKeyString(keyStr):
"""Translate dragonfly style key descriptions
to xdotool's preferred versions"""
keys = [parseSingleKeystring(k) for k in splitKeyString(keyStr)]
return ' '.join(keys)
def parseSingleKeystring(keyStr):
xdo = []
modifiers = []
keys = keyStr.split('-')
keys = [k.strip() for k in keys]
if len(keys) > 1:
modifiers = keys[0]
del keys[0]
keys = ''.join(keys)
for modifier in modifiers:
if modifier == 'c':
xdo += ['ctrl']
elif modifier == 'a':
xdo += ['alt']
elif modifier == 's':
xdo += ['shift']
elif modifier == 'w':
xdo += ['Super_L']
else:
raise Exception('Unknown modifier: ' + modifier)
replacements = {
"left" : "Left", #
"right" : "Right",
"up" : "Up",
"down" : "Down",
"home" : "Home",
"end" : "End",
"pgup" : "Prior",
"pgdown" : "Next",
"enter" : "Return",
"backspace" : "BackSpace",
"delete" : "Delete",
"insert" : "Insert",
"backtick" : "grave",
"caret" : "asciicircum",
"dot" : "period",
"dquote" : "quotedbl",
"escape" : "Escape",
"exclamation" : "exclam",
"hash" : "numbersign",
"hyphen" : "minus",
"squote" : "apostrophe",
"tilde" : "asciitilde",
"langle" : "less",
"rangle" : "greater",
"lbrace" : "braceleft",
"rbrace" : "braceright",
"lbracket" : "bracketleft",
"rbracket" : "bracketright",
"lparen" : "parenleft",
"rparen" : "parenright",
"tab" : "Tab",
}
keys = dictReplace(keys, replacements)
keys = re.sub("f([0-9])+", "F\\1", keys)
xdo.append(keys)
return '+'.join(xdo)
class ActionList(object):
def __init__(self, lst=[]):
self.lst = []
def __add__(self, other):
if isinstance(other, ActionList):
self.lst.extend(other.lst)
else:
self.lst.append(other)
return self
def __mul__(self, other):
assert isinstance(other, Repeat)
return RepeatAction(self, other.count, other.extra)
def __call__(self, extras={}):
for f in self.lst:
f(extras)
class Action(object):
def __init__(self, data=None):
self.data = data
def __add__(self, other):
return ActionList() + self + other
def __mul__(self, other):
assert isinstance(other, Repeat)
return RepeatAction(self, other.count, other.extra)
def __eq__(self, other):
return type(self) == type(other) and self.data == other.data
class RepeatAction(Action):
def __init__(self, otherAction, count, countVar):
Action.__init__(self, (otherAction, count, countVar))
def __call__(self, extras={}):
extraCount = 0 if self.data[2] is None else extras[self.data[2]]
for i in range(self.data[1] + extraCount):
self.data[0](extras)
class Repeat(Action):
def __init__(self, count=0, extra=None):
self.count = count
self.extra = extra
class RepeatPreviousAction(Action):
# Logic in server
pass
class Mimic(Action):
# Logic in server
pass
class Noop(Action):
def __call__(self, extras={}):
pass
class Speak(Action):
def __call__(self, extras={}):
cmd = "echo '" + (self.data % extras) + "' | festival --tts"
runCmd(cmd)
class Key(Action):
def __init__(self, data, delay=12, style="press_once"):
Action.__init__(self, data)
self.delay = delay
self.style = style
def up(self, extras={}):
cmd = ("xdotool keyup --delay %d " % self.delay) + parseKeyString(self.data % extras)
runCmd(cmd)
def down(self, extras={}):
cmd = ("xdotool keydown --delay %d " % self.delay) + parseKeyString(self.data % extras)
runCmd(cmd)
def __call__(self, extras={}):
cmd = ("xdotool key --delay %d " % self.delay) + parseKeyString(self.data % extras)
runCmd(cmd)
class FormatState(object):
noformatting = {
# format state commands
ur"\cap" : ur"cap",
ur"\caps-on" : ur"caps on",
ur"\caps-off" : ur"caps off",
ur"\all-caps" : ur"all caps",
ur"\no-space" : ur"no space",
ur"\numeral" : ur"numeral",
# punctuation
ur".\period" : ur"period",
ur",\comma" : ur"comma",
ur"(\left-parenthesis" : ur"left parenthesis",
ur")\right-parenthesis" : ur"right parenthesis",
u"\dash" : ur"dash",
ur"\hyphen" : ur"hyphen",
ur".\point" : ur"point",
ur".\dot" : ur"dot",
ur"\space-bar" : ur"space bar",
ur"\new-line" : ur"new line",
ur"?\question-mark" : ur"question mark",
ur"!\exclamation-mark" : ur"exclamation mark",
ur"@\at-sign" : ur"at sign",
ur"#\number-sign" : ur"number sign",
ur"$\dollar-sign" : ur"dollar sign",
ur"%\percent-sign" : ur"percent sign",
ur"~\tilde" : ur"tilde",
ur"`\backquote" : ur"backquote",
ur"+\plus-sign" : ur"plus sign",
u"\x96\\minus-sign" : ur"minus sign",
ur"-\minus-sign" : ur"minus sign",
ur":\colon" : ur"colon",
ur";\semicolon" : ur"semicolon",
ur"*\asterisk" : ur"asterisk",
u"_\\underscore" : ur"underscore",
ur"|\vertical-bar" : ur"vertical bar",
ur"/\slash" : ur"slash",
ur"\backslash" : ur"backslash",
ur"<\less-than-sign" : ur"less than sign",
ur">\greater-than-sign" : ur"greater than sign",
ur"=\equals-sign" : ur"equals sign",
ur"[\left-square-bracket" : ur"left square bracket",
ur"]\right-square-bracket" : ur"right square bracket",
ur"{\left-curly-bracket" : ur"left curly bracket",
ur"}\right-curly-bracket" : ur"right curly bracket",
ur"&\ampersand" : ur"ampersand",
ur"\cap" : ur"cap",
ur"^\caret" : ur"caret",
}
formatting = {
ur".\period" : ur".",
ur",\comma" : ur",",
ur"(\left-parenthesis" : ur"(",
ur")\right-parenthesis" : ur")",
u"\x96\\dash" : ur"-",
ur"-\hyphen" : ur"-",
ur".\point" : ur".",
ur".\dot" : ur".",
ur"\space-bar" : ur" ",
ur"\new-line" : u"\n", # hit enter?
ur"?\question-mark" : ur"?",
ur"!\exclamation-mark" : ur"!",
ur"@\at-sign" : ur"@",
ur"#\number-sign" : ur"#",
ur"$\dollar-sign" : ur"$",
ur"%\percent-sign" : ur"%",
ur"~\tilde" : ur"~",
ur"`\backquote" : ur"`",
ur"+\plus-sign" : ur"+",
u"\x96\\minus-sign" : ur"-",
ur"-\minus-sign" : ur"-",
ur":\colon" : ur":",
ur";\semicolon" : ur";",
ur"*\asterisk" : ur"*",
u"_\\underscore" : ur"_",
ur"|\vertical-bar" : ur"|",
ur"/\slash" : ur"/",
ur"\backslash" : u"\\\\",
ur"<\less-than-sign" : ur"<",
ur">\greater-than-sign" : ur">",
ur"=\equals-sign" : ur"=",
ur"[\left-square-bracket" : ur"[",
ur"]\right-square-bracket" : ur"]",
ur"{\left-curly-bracket" : ur"{",
ur"}\right-curly-bracket" : ur"}",
ur"&\ampersand" : ur"&",
ur"^\caret" : ur"^",
}
numeralmap = {
"zero" : "0",
"one" : "1",
"two" : "2",
"to" : "2",
"too" : "2",
"three" : "3",
"four" : "4",
"five" : "5",
"six" : "6",
"seven" : "7",
"eight" : "8",
"nine" : "9",
}
def __init__(self, formatting=True, spaces=True):
self.no_space_once = False
self.cap_once = False
self.caps = False
self.do_formatting = formatting
self.spacesEnabled = spaces
self.next_numeral = False
self.next_literal = False
def format(self, s):
new = []
first = True
last = False
for idx, word in enumerate(s):
if idx == len(s) - 1:
last = True
# startswith is used so much because at some point in development
# all of the control words started being sent twice by Dragon,
# so originally you would get \cap but now for some reason you get \cap\cap
doFormatting = self.do_formatting and not self.next_literal and len(s) > 1
if word.startswith(ur"\cap") and doFormatting:
self.cap_once = True
elif word.startswith(ur"\caps-on") and doFormatting:
self.caps = True
elif word.startswith(ur"\caps-off") and doFormatting:
self.caps = False
elif word.startswith(ur"\no-space") and doFormatting:
self.no_space_once = True
elif word.startswith(ur"\numeral") and doFormatting:
self.next_numeral = True
elif word.startswith(ur"literal") and doFormatting:
self.next_literal = True
else:
# see explanation of startswith above
isCode = False
lookupValue = None
for f in (self.formatting.keys() + self.noformatting.keys()):
if word.startswith(f):
isCode = True
lookupValue = f
break
newWord = word
if isCode:
if self.do_formatting and not self.next_literal:
replacements = self.formatting
else:
replacements = self.noformatting
newWord = replacements[lookupValue]
log.info("Word before : [%s]" % newWord)
new.append(newWord)
#log.info('newWord: ' + newWord)
self.no_space_once = True
else:
if self.cap_once:
newWord = word.capitalize()
if self.caps:
newWord = word.upper()
if self.next_numeral:
if newWord not in string.digits:
newWord = self.numeralmap[newWord.lower()]
self.next_numeral = False
# dragonfly doesn't properly filter slashes when
# the written and spoken form of a word differ
# and the spoken form has spaces in it, e.g.
# xdotool -> "ex do tool"
# reported: https://github.com/t4ngo/dragonfly/issues/14
## original fix:
# newWord = newWord.rstrip("\\")
## new fix, not sure when this changed:
pronunciatonIdx = newWord.find("\\\\")
if pronunciatonIdx != -1:
newWord = newWord[:pronunciatonIdx]
if not self.no_space_once:
if not last and self.spacesEnabled:
newWord += u' '
self.no_space_once = False
prohibited = ["pronoun", "determiner", "non", "apostrophe-ess",
"apostrophe ess", "apostrophe", "number", "letter", "z"]
# apparently for the apostrophe s in Dragons, it gets
# translated to 's/z/z <-- only one dividing slash, and
# it sends it as a totally separate word, so we have to
# manually merge it with the preceeding word
delete_preceding_space = ["z"]
merge = False
for p in prohibited:
if newWord.find("\\" + p) != -1:
#log.info("Replacing [%s] with [%s]" % ("\\" + p, ""))
newWord = newWord.replace("\\" + p, "")
if p in delete_preceding_space:
#log.info("Requesting words be merged")
merge = True
#log.info("new so far: [%s]" % new)
if merge and len(new):
#log.info("Merging %s with %s" % (new[-1], newWord))
if new[-1].endswith(" "):
#log.info("Merge [%s] [%s] [%s]" % (new[-1], new[-1][:-1], newWord))
new[-1] = new[-1][:-1] + newWord
else:
new[-1] = new[-1] + newWord
else:
#log.info("Appending")
new.append(newWord)
log.info("new word entry: [%s]" % new[-1])
log.info("Word: [%s]" % newWord)
first = False
self.next_literal = False
return new
def typeKeys(letters):
if not letters:
log.debug("Tried to type empty string, ignoring.")
return
# we pass each character as a separate argument to xdotool,
# this prevents xdotool from interpreting double hyphens and
# hyphens followed by words as xdotool flags
arglist = []
for l in letters:
newletter = l
# single quotes have to be passed unquoted and escaped
# or the shell gets confused
if l == '\'':
newletter = "\\'"
else:
newletter = "'" + l + "'"
arglist.append(newletter)
letters = ' '.join(arglist)
cmd = ("xdotool type --clearmodifiers " + letters)
runCmd(cmd)
def lower(word):
if isinstance(word, unicode):
return unicode.lower(word)
elif isinstance(word, str):
return str.lower(word)
raise Exception("Unknown string type.")
def capitalize(word):
if isinstance(word, unicode):
return unicode.capitalize(word)
elif isinstance(word, str):
return str.capitalize(word)
raise Exception("Unknown string type.")
# TODO: multiple formatting options, caps stuff is different than
# punctuation
class Text(Action):
def __init__(self, data, lower=True):
Action.__init__(self, data)
self.lower = lower
def __call__(self, extras={}):
log.info("extras: [%s]" % extras)
for k, v in extras.items():
# TODO: this really should be applied deep not shallow
if type(v) == list and len(v) > 0 and type(v[0]) in (str, unicode):
log.info("madeitin")
extras[k] = "".join(self._format(v))
text = self._text(extras)
log.info("Text: [%s]" % text)
self._print(text)
def _format(self, words):
return FormatState().format(words)
def _print(self, words):
typeKeys(words)
def _text(self, extras):
words = (self.data % extras)
if self.lower:
words = [w.lower() for w in words]
return ''.join(words)
class Camel(Text):
def __init__(self, fmt, caps=False):
Text.__init__(self, fmt)
self.caps = capitalize if caps else lower
def _format(self, words):
return FormatState(formatting=False).format(words)
def _text(self, extras):
words = (self.data % extras).lower().split(' ')
words = [strip_punctuation(word) for word in words]
words = [w.lower() for w in words]
words = [self.caps(words[0])] + [w.capitalize() for w in words[1:]]
return ''.join(words)
class Underscore(Text):
def __init__(self, fmt, caps=False):
Text.__init__(self, fmt)
self.caps = capitalize if caps else lower
def _format(self, words):
return FormatState(formatting=False).format(words)
def _text(self, extras):
words = (self.data % extras).lower().split(' ')
words = [self.caps(w) for w in words]
words = [strip_punctuation(word) for word in words]
return '_'.join(words)
class Hyphen(Text):
def __init__(self, fmt, caps=False):
Text.__init__(self, fmt)
self.caps = capitalize if caps else lower
def _format(self, words):
return FormatState(formatting=False).format(words)
def _text(self, extras):
words = (self.data % extras).lower().split(' ')
words = [strip_punctuation(word) for word in words]
words = [self.caps(w) for w in words]
return '-'.join(words)
class click:
def __init__(self, keyStr):
self.keyStr = keyStr
def __call__(self, extras={}):
# TODO: pay attention to errors, exit status
cmd = "xdotool click " + str(self.keyStr)
# log.info("executing: " + cmd)
subprocess.call(cmd, shell=True)
def moveRelativeToWindow(x, y, windowId):
cmd = "xdotool mousemove --window %s %s %s" % (windowId, x, y)
# log.info("executing: " + cmd)
subprocess.call(cmd, shell=True)