-
Notifications
You must be signed in to change notification settings - Fork 18
/
_repeat.py
executable file
·2468 lines (2205 loc) · 90.6 KB
/
_repeat.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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# This file is a command-module for Dragonfly.
# (c) Copyright 2008 by Christo Butcher
# (c) Copyright 2015 by James Stout
# Licensed under the LGPL, see <http://www.gnu.org/licenses/>
#
"""This contains all commands which may be spoken continuously or repeated.
This is heavily modified from _multiedit.py, found here:
https://github.com/t4ngo/dragonfly-modules/blob/master/command-modules/_multiedit.py
"""
import os.path
import re
import socket
import sys
import threading
import time
import webbrowser
from collections import OrderedDict
from concurrent import futures
import gaze_ocr
import gaze_ocr.dragonfly
import head_scroll
import screen_ocr
import win32clipboard
import yappi
from gaze_ocr import eye_tracking
from odictliteral import odict
from six import string_types
from six.moves import BaseHTTPServer
from six.moves import queue
from dragonfly import (
ActionBase,
Alternative,
AppContext,
Choice,
Compound,
CompoundRule,
Config,
CursorPosition,
DictList,
DictListRef,
Dictation,
DynStrActionBase,
Empty,
FocusWindow,
Function,
Grammar,
IntegerRef,
Key,
List,
ListRef,
Literal,
MappingRule,
Mimic,
Mouse,
Optional,
Pause,
Repeat,
Repetition,
RuleRef,
RuleWrap,
Text,
TextQuery,
get_accessibility_controller,
get_engine,
)
from dragonfly.actions.action_base import ActionSeries
from dragonfly.grammar.context import LogicAndContext, LogicOrContext
import dragonfly.log
from selenium.webdriver.common.by import By
import _dragonfly_local as local
import _dragonfly_utils as utils
import _linux_utils as linux
import _text_utils as text
import _webdriver_utils as webdriver
tracker = eye_tracking.EyeTracker.get_connected_instance(local.DLL_DIRECTORY,
mouse=gaze_ocr.dragonfly.Mouse(),
keyboard=gaze_ocr.dragonfly.Keyboard(),
windows=gaze_ocr.dragonfly.Windows())
if local.OCR_READER == "fast" or local.OCR_READER == "winrt":
ocr_reader = screen_ocr.Reader.create_fast_reader(radius=150)
elif local.OCR_READER == "quality":
ocr_reader = screen_ocr.Reader.create_quality_reader(radius=150)
gaze_ocr_controller = gaze_ocr.Controller(ocr_reader,
tracker,
mouse=gaze_ocr.dragonfly.Mouse(),
keyboard=gaze_ocr.dragonfly.Keyboard(),
save_data_directory=local.SAVE_OCR_DATA_DIR)
scroller = head_scroll.Scroller(tracker, gaze_ocr.dragonfly.Mouse())
# Load local hooks if defined.
try:
import _dragonfly_local_hooks as local_hooks
def run_local_hook(name, *args, **kwargs):
"""Function to run local hook if defined."""
try:
hook = getattr(local_hooks, name)
return hook(*args, **kwargs)
except AttributeError:
pass
except:
print("Local hooks not loaded.")
def run_local_hook(name, *args, **kwargs):
pass
# Make sure dragonfly errors show up in NatLink messages.
dragonfly.log.setup_log()
# Load _repeat.txt.
config = Config("repeat")
namespace = config.load()
#-------------------------------------------------------------------------------
# Common maps and lists.
# symbols_map = {
# "plus": "+",
# "plus twice": "++",
# "minus": "-",
# ",": ",",
# "colon": ":",
# "equals": "=",
# "equals twice": "==",
# "not equals": "!=",
# "plus equals": "+=",
# "greater than": ">",
# "less than": "<",
# "greater equals": ">=",
# "less equals": "<=",
# "dot": ".",
# "leap": "(",
# "reap": ")",
# "lake": "{",
# "rake": "}",
# "lobe": "[",
# "robe": "]",
# "luke": "<",
# "luke twice": "<<",
# "ruke": ">",
# "ruke twice": ">>",
# "quote": "\"",
# "dash": "-",
# "semi": ";",
# "bang": "!",
# "percent": "%",
# "star": "*",
# "backslash": "\\",
# "slash": "/",
# "tilde": "~",
# "backtick": "`",
# "underscore": "_",
# "single quote": "'",
# "dollar": "$",
# "carrot": "^",
# "arrow": "->",
# "fat arrow": "=>",
# "colon twice": "::",
# "amper": "&",
# "amper twice": "&&",
# "pipe": "|",
# "pipe twice": "||",
# "hash": "#",
# "at sign": "@",
# "question": "?",
# }
# symbols_map = {
# "plus [sign]": "+",
# "plus [sign] twice": "++",
# "minus|hyphen|dash": "-",
# ",": ",",
# "colon": ":",
# "equals [sign]": "=",
# "equals [sign] twice": "==",
# "not equals": "!=",
# "plus equals": "+=",
# "greater than|ruke|close angle": ">",
# "less than|luke|open angle": "<",
# "(greater than|ruke|close angle) twice": ">>",
# "(less than|luke|open angle) twice": "<<",
# "greater equals": ">=",
# "less equals": "<=",
# "dot|period": ".",
# "leap|open paren": "(",
# "reap|close paren": ")",
# "lake|open brace": "{",
# "rake|close brace": "}",
# "lobe|open bracket": "[",
# "robe|close bracket": "]",
# "quote|open quote|close quote": "\"",
# "semi|semicolon": ";",
# "bang|exclamation mark": "!",
# "percent [sign]": "%",
# "star|asterisk": "*",
# "backslash": "\\",
# "slash": "/",
# "tilde": "~",
# "backtick": "`",
# "underscore": "_",
# "single quote|apostrophe": "'",
# "dollar [sign]": "$",
# "caret": "^",
# "arrow": "->",
# "fat arrow": "=>",
# "colon twice": "::",
# "amper|ampersand": "&",
# "(amper|ampersand) twice": "&&",
# "pipe": "|",
# "pipe twice": "||",
# "hash|number sign": "#",
# "at sign": "@",
# "question [mark]": "?",
# }
# Common names for symbols and combinations of symbols.
symbols_map = {
"plus": "+",
"plus sign": "+",
"plus twice": "++",
"plus sign twice": "++",
"minus": "-",
"minus twice": "--",
"hyphen": "-",
"dash": "-",
",": ",",
"colon": ":",
"equals": "=",
"equals sign": "=",
"equals twice": "==",
"equals sign twice": "==",
"not equals": "!=",
"plus equals": "+=",
"minus equals": "-=",
"greater than": ">",
"ruke": ">",
"close angle": ">",
"less than": "<",
"luke": "<",
"open angle": "<",
"greater than twice": ">>",
"ruke twice": ">>",
"close angle twice": ">>",
"less than twice": "<<",
"luke twice": "<<",
"open angle twice": "<<",
"greater equals": ">=",
"less equals": "<=",
"dot": ".",
"period": ".",
"leap": "(",
"open paren": "(",
"reap": ")",
"close paren": ")",
"lake": "{",
"open brace": "{",
"rake": "}",
"close brace": "}",
"lobe": "[",
"open bracket": "[",
"robe": "]",
"close bracket": "]",
"quote": "\"",
"open quote": "\"",
"close quote": "\"",
"semi": ";",
"semicolon": ";",
"bang": "!",
"exclamation mark": "!",
"percent": "%",
"percent sign": "%",
"star": "*",
"asterisk": "*",
"backslash": "\\",
"slash": "/",
"tilde": "~",
"backtick": "`",
"underscore": "_",
"underscore twice": "__",
"dunder": "__",
"single quote": "'",
"apostrophe": "'",
"dollar": "$",
"dollar sign": "$",
"caret": "^",
"arrow": "->",
"fat arrow": "=>",
"colon twice": "::",
"amper": "&",
"ampersand": "&",
"amper twice": "&&",
"ampersand twice": "&&",
"pipe": "|",
"pipe twice": "||",
"hash": "#",
"number sign": "#",
"at sign": "@",
"question": "?",
"question mark": "?",
}
# Individual symbols which can be typed without any modifier keys.
symbol_keys_map = {
"minus|dash": "-",
",": ",",
"equals": "=",
"dot|period": ".",
"semi": ";",
"backslash": "\\",
"slash": "/",
"backtick": "`",
"single quote": "'",
}
# Numbers and numeric formatting symbols.
numbers_map = {
"zero": "0",
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
"point": ".",
"minus": "-",
"slash": "/",
"colon": ":",
",": ",",
}
# Single-syllable names for letters.
quick_letters_map = {
"arch": "a",
"brov": "b",
"chair": "c",
"dell": "d",
"etch": "e",
"fomp": "f",
"goof": "g",
"hark": "h",
"ice": "i",
"jinks": "j",
"koop": "k",
"lug": "l",
"mowsh": "m",
"nerb": "n",
"ork": "o",
"pooch": "p",
"quash": "q",
"rosh": "r",
"souk": "s",
"teek": "t",
"unks": "u",
"verge": "v",
"womp": "w",
"trex": "x",
"yang": "y",
"zooch": "z",
}
# Disabled for efficiency.
# long_letters_map = {
# "alpha": "a",
# "bravo": "b",
# "charlie": "c",
# "delta": "d",
# "echo": "e",
# "foxtrot": "f",
# "golf": "g",
# "hotel": "h",
# "india": "i",
# "juliet": "j",
# "kilo": "k",
# "lima": "l",
# "mike": "m",
# "november": "n",
# "oscar": "o",
# "poppa": "p",
# "quebec": "q",
# "romeo": "r",
# "sierra": "s",
# "tango": "t",
# "uniform": "u",
# "victor": "v",
# "whiskey": "w",
# "x-ray": "x",
# "yankee": "y",
# "zulu": "z",
# "dot": ".",
# }
# Common variable prefixes.
prefixes = [
"num",
"min",
]
# Common variable suffixes.
suffixes = [
"bytes",
]
# All supported letter names.
letters_map = utils.combine_maps(quick_letters_map)
# Letters, numbers, and symbol combinations.
chars_map = utils.combine_maps(letters_map, numbers_map, symbols_map)
# Load commonly misrecognized words saved to a file.
# TODO: Revisit.
saved_words = []
try:
with open(text.WORDS_PATH) as file:
for line in file:
word = line.strip()
if len(word) > 2 and word not in letters_map:
saved_words.append(line.strip())
except:
print("Unable to open: " + text.WORDS_PATH)
# Keys that can be interleaved with dictation and repeated.
dictation_key_action_map = {
"enter|slap": Key("enter"),
"space|spooce|spacebar": Key("space"),
"tab-key": Key("tab"),
}
# Actions that can be interleaved with dictation but not repeated.
nonrepeatable_dictation_action_map = utils.combine_maps(
utils.text_map_to_action_map(utils.combine_maps(letters_map, symbols_map)),
{
"number <numeral>": Text(u"%(numeral)s"),
"upper <letter>": Function(lambda letter: Text(letter.upper()).execute()),
})
# Actions that can be interleaved with dictation.
dictation_action_map = utils.combine_maps(dictation_key_action_map,
nonrepeatable_dictation_action_map)
# Key names that can be spoken with or without modifiers and can be repeated.
standalone_key_action_map = utils.combine_maps(
dictation_key_action_map,
{
"up": Key("up"),
"down": Key("down"),
"left": Key("left"),
"right": Key("right"),
"page up": Key("pgup"),
"page down": Key("pgdown"),
"apps key": Key("apps"),
"escape": Key("escape"),
"backspace": Key("backspace"),
"delete key": Key("del"),
"home key": Key("home"),
"end key": Key("end"),
})
# Key names that can be spoken with modifiers keys.
full_key_action_map = utils.combine_maps(
standalone_key_action_map,
utils.text_map_to_key_action_map(utils.combine_maps(letters_map, numbers_map, symbol_keys_map)),
{
"home": Key("home"),
"end": Key("end"),
"tab": Key("tab"),
"delete": Key("del"),
})
# Actions that can be repeated by prefixing with a number modifier.
repeatable_action_map = utils.combine_maps(
standalone_key_action_map,
{
"after": Key("c-right"),
"before": Key("c-left"),
"afters": Key("shift:down, c-right, shift:up"),
"befores": Key("shift:down, c-left, shift:up"),
"ahead": Key("a-f"),
"behind": Key("a-b"),
"aheads": Key("shift:down, a-f, shift:up"),
"behinds": Key("shift:down, a-b, shift:up"),
"rights": Key("shift:down, right, shift:up"),
"lefts": Key("shift:down, left, shift:up"),
"kill": Key("c-k"),
"screen up": Key("pgup"),
"screen down": Key("pgdown"),
"cancel": Key("escape"),
})
accessibility = get_accessibility_controller()
accessibility_commands = odict[
"go before <text_position_query>": Function(lambda text_position_query: accessibility.move_cursor(
text_position_query, CursorPosition.BEFORE)),
"go after <text_position_query>": Function(lambda text_position_query: accessibility.move_cursor(
text_position_query, CursorPosition.AFTER)),
# Note that the delete command is declared first so that it has higher
# priority than the selection variant.
"words <text_query> delete": Function(lambda text_query: accessibility.replace_text(text_query, "")),
"words <text_query>": Function(accessibility.select_text),
"replace <text_query> with <replacement>": Function(accessibility.replace_text),
]
#-------------------------------------------------------------------------------
# Action maps to be used in rules.
def start_cpu_profiling():
yappi.set_clock_type("cpu")
yappi.start()
def start_wall_profiling():
yappi.set_clock_type("wall")
yappi.start()
def stop_profiling():
yappi.stop()
yappi.get_func_stats().print_all()
yappi.get_thread_stats().print_all()
has_argv = hasattr(sys, "argv")
if not has_argv:
sys.argv = [""]
profile_path = os.path.join(local.HOME, "yappi_{}.callgrind.out".format(time.time()))
yappi.get_func_stats().save(profile_path, "callgrind")
yappi.clear_stats()
# Actions of commonly used text navigation and mousing commands. These can be
# used anywhere except after commands which include arbitrary dictation.
# TODO: Better solution for holding shift during a single command. Think about whether this could enable a simpler grammar for other modifiers.
command_action_map = utils.combine_maps(
# These work like the built-in commands and are available for any
# application that supports IAccessible2. A "my" prefix is used to avoid
# overwriting similarly-phrased commands built into Dragon, because in some
# applications only those will work. These are primarily present to test
# functionality; to add these commands to a specific application, just merge
# in the map without a prefix.
OrderedDict([("my " + k, v) for k, v in accessibility_commands.items()]),
nonrepeatable_dictation_action_map,
odict[
# Semantic names for common keypresses.
"delete": Key("del"),
"paste": Key("c-v"),
"copy": Key("c-c"),
"cut": Key("c-x"),
"all select": Key("c-a"),
"go home|[go] west": Key("home"),
"go end|[go] east": Key("end"),
"go top|[go] north": Key("c-home"),
"go bottom|[go] south": Key("c-end"),
"save": Key("c-s"),
"(window|win) new": Key("c-n"),
"(window|win) close": Key("c-w"),
"(window|win) restore": Key("w-down"),
"(window|win) (maximize|max)": Key("w-up"),
"(window|win) snap left": Key("w-left"),
"(window|win) snap right": Key("w-right"),
"find": Key("c-f"),
"this bold": Key("c-b"),
"this italics": Key("c-i"),
# Globally-available Windows commands.
"volume [<n>] up": Key("volumeup/5:%(n)d"),
"volume [<n>] down": Key("volumedown/5:%(n)d"),
"volume (mute|unmute)": Key("volumemute"),
"track next": Key("tracknext"),
"track preev": Key("trackprev"),
"track (pause|play)": Key("playpause"),
"windows search": Key("w-s"),
"windows run": Key("w-r"),
"windows desktop": Key("w-d"),
"windows explorer": Key("w-e"),
# Dragon commands.
"dragon hide": Mimic(*"switch DragonBar to tray icon mode".split()),
"dragon show": Mimic(*"open DragonBar".split()),
# Notepad text editing.
"here edit": utils.RunApp("notepad"),
"all edit": Key("c-a, c-x") + utils.RunApp("notepad") + Key("c-v"),
"this edit": Key("c-x") + utils.RunApp("notepad") + Key("c-v"),
# Control keys.
"shift hold": Key("shift:down"),
"shift release": Key("shift:up"),
"control hold": Key("ctrl:down"),
"control release": Key("ctrl:up"),
"(meta|alt) hold": Key("alt:down"),
"(meta|alt) release": Key("alt:up"),
"all release": Key("shift:up, ctrl:up, alt:up"),
# Scrolling and clicking.
"here (touch|click) [left]": Mouse("left"),
"here (touch|click) right": Mouse("right"),
"here (touch|click) middle": Mouse("middle"),
"here (touch|click) [left] twice": Mouse("left:2"),
"here (touch|click) hold": Mouse("left:down"),
"here (touch|click) release": Mouse("left:up"),
"(I\\pronoun|eye) move": Function(tracker.move_to_gaze_point),
"(I\\pronoun|eye) (touch|click) [left]": Function(tracker.move_to_gaze_point) + Mouse("left"),
"(I\\pronoun|eye) (touch|click) right": Function(tracker.move_to_gaze_point) + Mouse("right"),
"(I\\pronoun|eye) (touch|click) middle": Function(tracker.move_to_gaze_point) + Mouse("middle"),
"(I\\pronoun|eye) (touch|click) [left] twice": Function(tracker.move_to_gaze_point) + Mouse("left:2"),
"(I\\pronoun|eye) (touch|click) hold": Function(tracker.move_to_gaze_point) + Mouse("left:down"),
"(I\\pronoun|eye) (touch|click) release": Function(tracker.move_to_gaze_point) + Mouse("left:up"),
"(I\\pronoun|eye) control (touch|click)": Function(tracker.move_to_gaze_point) + Key("ctrl:down") + Mouse("left") + Key("ctrl:up"),
# Webdriver control (used for Chrome but can be started and stopped from anywhere).
"webdriver open": Function(webdriver.create_driver),
"webdriver close": Function(webdriver.quit_driver),
# No-op for Google/Siri commands.
"((hey|OK) google|hey Siri) <text>": Function(lambda text: None),
# Profiling.
"dragonfly CPU profiling start": Function(start_cpu_profiling),
"dragonfly wall [time] profiling start": Function(start_wall_profiling),
"dragonfly [(CPU|wall [time])] profiling stop": Function(stop_profiling),
])
def reset_scroller():
scroller.stop()
scroller.start()
terminal_command_action_map = odict[
# Scrolling and clicking.
"(I\\pronoun|eye) connect": Function(tracker.connect),
"(I\\pronoun|eye) disconnect": Function(tracker.disconnect),
"(I\\pronoun|eye) print position": Function(tracker.print_gaze_point),
"scroll up": Function(lambda: tracker.move_to_gaze_point((0, 40))) + Mouse("wheelup:7"),
"scroll up half": Function(lambda: tracker.move_to_gaze_point((0, 40))) + Mouse("wheelup:4"),
"scroll down": Function(lambda: tracker.move_to_gaze_point((0, -40))) + Mouse("wheeldown:7"),
"scroll down half": Function(lambda: tracker.move_to_gaze_point((0, -40))) + Mouse("wheeldown:4"),
"scroll left": Function(lambda: tracker.move_to_gaze_point((40, 0))) + Mouse("wheelleft:7"),
"scroll right": Function(lambda: tracker.move_to_gaze_point((-40, 0))) + Mouse("wheelright:7"),
"scroll start": Function(lambda: scroller.start()),
"[scroll] stop": Function(lambda: scroller.stop()),
"scroll reset": Function(lambda: reset_scroller()),
"<text> move": gaze_ocr.dragonfly.MoveCursorToWordAction(gaze_ocr_controller, "%(text)s"),
"<text> (touch|click) [left]": gaze_ocr.dragonfly.MoveCursorToWordAction(gaze_ocr_controller, "%(text)s") + Mouse("left"),
"<text> (touch|click) right": gaze_ocr.dragonfly.MoveCursorToWordAction(gaze_ocr_controller, "%(text)s") + Mouse("right"),
"<text> (touch|click) middle": gaze_ocr.dragonfly.MoveCursorToWordAction(gaze_ocr_controller, "%(text)s") + Mouse("middle"),
"<text> (touch|click) [left] twice": gaze_ocr.dragonfly.MoveCursorToWordAction(gaze_ocr_controller, "%(text)s") + Mouse("left:2"),
"<text> (touch|click) hold": gaze_ocr.dragonfly.MoveCursorToWordAction(gaze_ocr_controller, "%(text)s") + Mouse("left:down"),
"<text> (touch|click) release": gaze_ocr.dragonfly.MoveCursorToWordAction(gaze_ocr_controller, "%(text)s") + Mouse("left:up"),
"<text> control (touch|click)": gaze_ocr.dragonfly.MoveCursorToWordAction(gaze_ocr_controller, "%(text)s") + Key("ctrl:down") + Mouse("left") + Key("ctrl:up"),
# OCR-based commands.
"go before <text>": gaze_ocr.dragonfly.MoveTextCursorAction(gaze_ocr_controller, "%(text)s", "before"),
"go after <text>": gaze_ocr.dragonfly.MoveTextCursorAction(gaze_ocr_controller, "%(text)s", "after"),
# Note that the delete commands are declared first so that they have higher
# priority than the selection variants.
"words before <text> delete": Key("shift:down") + gaze_ocr.dragonfly.MoveTextCursorAction(gaze_ocr_controller, "%(text)s", "before") + Key("shift:up") + Key("backspace"),
"words after <text> delete": Key("shift:down") + gaze_ocr.dragonfly.MoveTextCursorAction(gaze_ocr_controller, "%(text)s", "after") + Key("shift:up") + Key("backspace"),
"words <text> [through <text2>] delete": gaze_ocr.dragonfly.SelectTextAction(gaze_ocr_controller, "%(text)s", "%(text2)s", for_deletion=True) + Key("backspace"),
"words before <text>": Key("shift:down") + gaze_ocr.dragonfly.MoveTextCursorAction(gaze_ocr_controller, "%(text)s", "before") + Key("shift:up"),
"words after <text>": Key("shift:down") + gaze_ocr.dragonfly.MoveTextCursorAction(gaze_ocr_controller, "%(text)s", "after") + Key("shift:up"),
"words <text> [through <text2>]": gaze_ocr.dragonfly.SelectTextAction(gaze_ocr_controller, "%(text)s", "%(text2)s"),
"replace <text> with <replacement>": gaze_ocr.dragonfly.SelectTextAction(gaze_ocr_controller, "%(text)s", "%(text2)s") + Text("%(replacement)s"),
# Full-text dictation commands.
"speak <text>": Text(u"%(text)s"),
"sentence <text>": utils.capitalize_text_action("%(text)s"),
"mimic <text>": Mimic(extra="text"),
]
# Here we prepare the action map of formatting functions from the config file.
# Retrieve text-formatting functions from this module's config file. Each of
# these functions must have a name that starts with "format_".
format_functions = {}
if namespace:
for name, function in namespace.items():
if name.startswith("format_") and callable(function):
spoken_form = function.__doc__.strip()
# We wrap generation of the Function action in a function so
# that its *function* variable will be local. Otherwise it
# would change during the next iteration of the namespace loop.
def wrap_function(function):
def _function(dictation):
formatted_text = function(dictation)
Text(formatted_text).execute()
return Function(_function)
action = wrap_function(function)
format_functions[spoken_form] = action
#-------------------------------------------------------------------------------
# Simple elements that may be referred to within a rule.
symbols_dict_list = DictList("symbols_dict_list", symbols_map)
symbol_element = DictListRef(None, symbols_dict_list)
# symbol_element = RuleWrap(None, Choice(None, symbols_map))
numbers_dict_list = DictList("numbers_dict_list", numbers_map)
number_element = DictListRef(None, numbers_dict_list)
# number_element = RuleWrap(None, Choice(None, numbers_map))
letters_dict_list = DictList("letters_dict_list", letters_map)
letter_element = DictListRef(None, letters_dict_list)
# letter_element = RuleWrap(None, Choice(None, letters_map))
chars_dict_list = DictList("chars_dict_list", chars_map)
char_element = DictListRef(None, chars_dict_list)
# char_element = RuleWrap(None, Choice(None, chars_map))
saved_word_list = List("saved_word_list", saved_words)
# Lists which will be populated later via RPC.
context_phrase_list = List("context_phrase_list", [])
prefix_list = List("prefix_list", prefixes)
suffix_list = List("suffix_list", suffixes)
# Either arbitrary or custom dictation.
mixed_dictation = RuleWrap(None, utils.JoinedSequence(" ", [
Optional(ListRef(None, prefix_list)),
Alternative([
Dictation(),
letter_element,
ListRef(None, saved_word_list),
]),
Optional(ListRef(None, suffix_list)),
]))
# Same as above, except no arbitrary dictation allowed and context phrases are
# included.
custom_dictation = RuleWrap(None, utils.JoinedSequence(" ", [
Optional(ListRef(None, prefix_list)),
Alternative([
letter_element,
ListRef(None, context_phrase_list),
ListRef(None, saved_word_list),
]),
Optional(ListRef(None, suffix_list)),
]))
# A sequence of either short letters or long letters.
letters_element = RuleWrap(None, utils.JoinedRepetition(
"", letter_element, min=1, max=10))
# A sequence of numbers.
numbers_element = RuleWrap(None, utils.JoinedRepetition(
"", number_element, min=1, max=10))
# A sequence of characters.
chars_element = RuleWrap(None, utils.JoinedRepetition(
"", char_element, min=1, max=5))
# Simple element map corresponding to command action maps from earlier.
command_element_map = {
"n": (IntegerRef(None, 1, 21), 1),
# Include IntegerRef to automatically convert spoken numbers to numeric format.
"text": RuleWrap(None, Alternative([
Dictation(),
IntegerRef(None, 1, 10)
])),
"text2": RuleWrap(None, Alternative([
Dictation(),
IntegerRef(None, 1, 10)
])),
"numeral": number_element,
"letter": letter_element,
"char": char_element,
"custom_text": RuleWrap(None, Alternative([
Dictation(),
chars_element,
ListRef(None, prefix_list),
ListRef(None, suffix_list),
ListRef(None, saved_word_list),
])),
# TODO Figure out why we can't reuse custom_text element.
"custom_text2": RuleWrap(None, Alternative([
Dictation(),
chars_element,
ListRef(None, prefix_list),
ListRef(None, suffix_list),
ListRef(None, saved_word_list),
])),
"replacement": Dictation(),
"text_query": Compound(
spec=("[[([<start_phrase>] <start_relative_position> <start_relative_phrase>|<start_phrase>)] <through>] "
"([<end_phrase>] <end_relative_position> <end_relative_phrase>|<end_phrase>)"),
extras=[Dictation("start_phrase", default=""),
Alternative([Literal("before"), Literal("after")], name="start_relative_position"),
Dictation("start_relative_phrase", default=""),
Literal("through", "through", value=True, default=False),
Dictation("end_phrase", default=""),
Alternative([Literal("before"), Literal("after")], name="end_relative_position"),
Dictation("end_relative_phrase", default="")],
value_func=lambda node, extras: TextQuery(
start_phrase=str(extras["start_phrase"]),
start_relative_position=CursorPosition[extras["start_relative_position"].upper()] if "start_relative_position" in extras else None,
start_relative_phrase=str(extras["start_relative_phrase"]),
through=extras["through"],
end_phrase=str(extras["end_phrase"]),
end_relative_position=CursorPosition[extras["end_relative_position"].upper()] if "end_relative_position" in extras else None,
end_relative_phrase=str(extras["end_relative_phrase"]))),
"text_position_query": Compound(
spec="<phrase> [<relative_position> <relative_phrase>]",
extras=[Dictation("phrase", default=""),
Alternative([Literal("before"), Literal("after")], name="relative_position"),
Dictation("relative_phrase", default="")],
value_func=lambda node, extras: TextQuery(
end_phrase=str(extras["phrase"]),
end_relative_position=CursorPosition[extras["relative_position"].upper()] if "relative_position" in extras else None,
end_relative_phrase=str(extras["relative_phrase"]))),
}
#-------------------------------------------------------------------------------
# Rules which we will refer to within other rules.
# Rule for formatting mixed_dictation elements.
format_rule = utils.create_rule(
"FormatRule",
format_functions,
{"dictation": mixed_dictation}
)
# Rule for formatting symbols.
symbol_format_rule = utils.create_rule(
"SymbolFormatRule",
{
"padded <symbol>": Text(u" %(symbol)s "),
},
{
"symbol": symbol_element,
}
)
# Rule for formatting pure dictation elements.
pure_format_rule = utils.create_rule(
"PureFormatRule",
dict([("pure (" + k + ")", v)
for (k, v) in format_functions.items()]),
{"dictation": Dictation()}
)
# Rule for formatting custom_dictation elements.
custom_format_rule = utils.create_rule(
"CustomFormatRule",
dict([("my (" + k + ")", v)
for (k, v) in format_functions.items()]),
{"dictation": custom_dictation}
)
# Rule for printing a sequence of characters.
character_rule = utils.create_rule(
"CharacterRule",
{
"<chars> short": Text(u"%(chars)s"),
"number <numerals>": Text(u"%(numerals)s"),
"letter <letters>": Text(u"%(letters)s"),
"upper letter <letters>": Function(lambda letters: Text(letters.upper()).execute()),
},
{
"numerals": numbers_element,
"letters": letters_element,
"chars": chars_element,
}
)
# Rule for spelling a word letter by letter and formatting it.
# Disabled for efficiency.
# spell_format_rule = utils.create_rule(
# "SpellFormatRule",
# dict([("spell (" + k + ")", v)
# for (k, v) in format_functions.items()]),
# {"dictation": letters_element}
# )
#-------------------------------------------------------------------------------
# Elements that are composed of rules. Note that the value of these elements are
# actions which will have to be triggered manually.
# Element matching dictation and commands allowed at the end of an utterance.
# For efficiency, this should not contain any repeating elements. For accuracy,
# few custom commands should be included to avoid clashes with dictation
# elements.
dictation_element = RuleWrap(None, Alternative([
RuleRef(rule=format_rule),
RuleRef(rule=symbol_format_rule),
RuleRef(rule=pure_format_rule),
# Disabled for efficiency.
# RuleRef(rule=custom_format_rule),
RuleRef(rule=utils.create_rule("DictationActionRule",
dictation_action_map,
command_element_map)),
]))
### Final commands that can be used once after everything else. These change the
### application context so it is important that nothing else gets run after
### them.
# Ordered list of pinned taskbar items. Sublists refer to windows within a specific application.
windows = [
"explorer",
["dragonbar", "dragon [messages]", "dragonpad"],
"[home] chrome",
"[home] terminal",
"[home] emacs",
]
json_windows = utils.load_json("windows.json")
if json_windows:
windows = json_windows
windows_suffix = "(win|window)"
windows_mapping = {}
for i, window in enumerate(windows):
if isinstance(window, string_types):
window = [window]
for j, words in enumerate(window):
windows_mapping["(" + words + ") " + windows_suffix] = Key("win:down, %d:%d/20, win:up" % (i + 1, j + 1))
final_action_map = utils.combine_maps(windows_mapping, {
"[work] (terminal|shell) win": FocusWindow(executable="nxclient.bin", title=" - Terminal"),
"[work] emacs win": FocusWindow(executable="nxclient.bin", title=" - Emacs editor"),
"[work] studio win": FocusWindow(executable="nxclient.bin", title=" - Android Studio"),
"[<n>] swap": utils.SwitchWindows("%(n)d"),
})
final_element_map = {
"n": (IntegerRef(None, 1, 20), 1)
}
final_rule = utils.create_rule("FinalRule",
final_action_map,
final_element_map)
#-------------------------------------------------------------------------------
# System for benchmarking other commands.
class CommandBenchmark:
def __init__(self):
self.remaining_count = 0
def start(self, command, repeat_count):
if self.remaining_count > 0:
print("Benchmark already running!")
return
self.repeat_count = repeat_count
self.remaining_count = repeat_count
self.command = command
self.start_time = time.time()
Mimic(*self.command.split()).execute()
def record_and_replay_recognition(self):
if self.remaining_count == 0:
print("Benchmark not running!")
return
self.remaining_count -= 1
if self.remaining_count == 0:
print("Average response for command %s: %.10f" % (self.command, (time.time() - self.start_time) / self.repeat_count))
else:
Mimic(*self.command.split()).execute()
def is_active(self):
return self.remaining_count > 0
def reset_benchmark():
global command_benchmark
command_benchmark = CommandBenchmark()
reset_benchmark()
#---------------------------------------------------------------------------
# Here we define the top-level rule which the user can say.
# This is the rule that actually handles recognitions.
# When a recognition occurs, its _process_recognition()
# method will be called. It receives information about the
# recognition in the "extras" argument: the sequence of
# actions and the number of times to repeat them.
class RepeatRule(CompoundRule):
def __init__(self, name, command, repeatable_command, terminal_command):
# Here we define this rule's spoken-form and special elements. Note that
# nested_repetitions is the only one that contains Repetitions, and it
# is not itself repeated. This is for performance purposes. We also
# include a special escape command "terminal <dictation>" in case
# recognition problems occur with repeated dictation commands.
spec = ("[<sequence>] "
"[<nested_repetitions>] "
"([<dictation_sequence>] [terminal <dictation>] | <terminal_command>) "
"[<n> times] "
"[<final_command>]")
repeated_command = Compound(spec="[<n>] <repeatable_command>",
extras=[IntegerRef("n", 1, 21, default=1),
utils.renamed_element("repeatable_command", repeatable_command)],