forked from wolfmanstout/dragonfly-commands
/
_dragonfly_utils.py
executable file
·214 lines (163 loc) · 6.51 KB
/
_dragonfly_utils.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
#!/usr/bin/env python
# (c) Copyright 2015 by James Stout
# Licensed under the LGPL, see <http://www.gnu.org/licenses/>
"""Various utility functions for working with dragonfly.
It requires the presence of dragonfly_local.py in the core subdirectory to define
the following variables:
HOME: Path to your home directory.
DLL_DIRECTORY: Path to directory containing DLLs used in this module. Missing
DLLs will be ignored.
CHROME_DRIVER_PATH: Path to chrome driver executable.
"""
import json
import os
import os.path
import tempfile
from dragonfly import (
ActionBase,
DynStrActionBase,
Key,
MappingRule,
Repetition,
Sequence,
StartApp,
Text,
WaitWindow,
)
from dragonfly.windows.window import Window
import _dragonfly_local as local
#-------------------------------------------------------------------------------
# Utility functions and classes for manipulating grammars and their components.
# To make creating rules a bit easier, we define a few new types:
# Action map: Mapping from command spec (string) to action.
# Element map: Mapping from element name to either element or tuple of element
# and default value. The preset element names will be overwritten
# when used.
#
# The advantage to this separation is we can easily bind a single element to
# different names to be used in multiple rules, and we can easily create rules
# on the fly without defining a new class.
def combine_maps(*maps):
"""Merge the contents of multiple maps, giving precedence to later maps."""
result = {}
for map in maps:
if map:
result.update(map)
return result
def text_map_to_action_map(text_map):
"""Converts string values in a map to text actions."""
return dict((k, Text(v.replace("%", "%%")))
for (k, v) in text_map.iteritems())
class JoinedRepetition(Repetition):
"""Like Repetition, except the results are joined with the given delimiter
instead of returned as a list.
"""
def __init__(self, delimiter, *args, **kwargs):
Repetition.__init__(self, *args, **kwargs)
self.delimiter = delimiter
def value(self, node):
return self.delimiter.join(Repetition.value(self, node))
class JoinedSequence(Sequence):
"""Like Sequence, except the results are joined with the given delimiter instead
of returned as a list.
"""
def __init__(self, delimiter, *args, **kwargs):
Sequence.__init__(self, *args, **kwargs)
self.delimiter = delimiter
def value(self, node):
return self.delimiter.join(str(v)
for v in Sequence.value(self, node)
if v)
class ElementWrapper(Sequence):
"""Identity function on element, useful for renaming."""
def __init__(self, name, child):
Sequence.__init__(self, (child, ), name)
def value(self, node):
return Sequence.value(self, node)[0]
def element_map_to_extras(element_map):
"""Converts an element map to a standard named element list that may be used in
MappingRule.
"""
return [ElementWrapper(name, element[0] if isinstance(element, tuple) else element)
for (name, element) in element_map.items()]
def element_map_to_defaults(element_map):
"""Converts an element map to a map of element names to default values."""
return dict([(name, element[1])
for (name, element) in element_map.items()
if isinstance(element, tuple)])
def create_rule(name, action_map, element_map, exported=False, context=None):
"""Creates a rule with the given name, binding the given element map to the
action map.
"""
return MappingRule(name,
action_map,
element_map_to_extras(element_map),
element_map_to_defaults(element_map),
exported,
context=context)
def combine_contexts(context1, context2):
"""Combine two contexts using "&", treating None as equivalent to a context that
matches everything.
"""
if not context1:
return context2
if not context2:
return context1
return context1 & context2
class RunApp(ActionBase):
"""Starts an app and waits for it to be the foreground app."""
def __init__(self, *args):
super(RunApp, self).__init__()
self.args = args
def _execute(self, data=None):
StartApp(*self.args).execute()
WaitWindow(None, os.path.basename(self.args[0]), 3).execute()
class RunEmacs(ActionBase):
"""Runs Emacs on a temporary file with the given suffix."""
def __init__(self, suffix):
super(RunEmacs, self).__init__()
self.suffix = suffix
def _execute(self, data=None):
cygwin_tmp = local.CYGWIN_ROOT + "/tmp"
(f, path) = tempfile.mkstemp(prefix="emacs", suffix=self.suffix, dir=cygwin_tmp)
os.close(f)
os.unlink(path)
cygwin_path = path[path.index("tmp") - 1:].replace("\\", "/")
emacs_path = local.CYGWIN_ROOT + "/bin/emacsclient-w32.exe"
RunApp(emacs_path, "-c", "-n", cygwin_path).execute()
class UniversalPaste(ActionBase):
"""Paste action that works everywhere, including Emacs."""
def _execute(self, data=None):
foreground = Window.get_foreground()
if foreground.title.find("Emacs editor") != -1:
Key("c-y").execute()
else:
Key("c-v").execute()
class FormattedText(DynStrActionBase):
"""Types text after running through formatter function."""
def __init__(self, spec, formatter):
DynStrActionBase.__init__(self, spec)
self.formatter = formatter
def _parse_spec(self, spec):
return spec
def _execute_events(self, events):
Text(self.formatter(events)).execute()
def lowercase_text_action(spec):
return FormattedText(spec, lambda text: text.lower())
def byteify(input):
"""Convert unicode to str. Dragonfly grammars don't play well with Unicode."""
if isinstance(input, dict):
return dict((byteify(key), byteify(value)) for key,value in input.iteritems())
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input
def load_json(filename):
try:
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), filename)) as json_file:
return byteify(json.load(json_file))
except IOError:
print filename + " not found"
return None