Debian Codegraph @

daemon/openrazer_daemon/misc/macro.py

raw
1 # SPDX-License-Identifier: GPL-2.0-or-later
2
3 """
4 Macro stuff
5
6 Has objects representing key events
7 Launching programs etc...
8 """
9 import logging
10 import subprocess
11 import threading
12
13 # pylint: disable=import-error
14 from openrazer_daemon.keyboard import XTE_MAPPING
15
16 # This determines if the macro keys are executed with their natural spacing
17 XTE_SLEEP = False
18
19
20 class MacroObject(object):
21 """
22 Macro base object
23 """
24
25 def to_dict(self):
26 """
27 Convert the object to a dict to be sent over DBus
28
29 :return: Dictionary
30 :rtype: dict
31 """
32 raise NotImplementedError()
33
34 @classmethod
35 def from_dict(cls, values_dict):
36 """
37 Create class from dict
38
39 :param values_dict: Dictionary of values (and a type key)
40 :type values_dict: dict
41
42 :return: Class object
43 """
44 del values_dict['type']
45 return cls(**values_dict)
46
47
48 class MacroKey(MacroObject):
49 """
50 Is an object of a key event used in macros
51 """
52
53 def __init__(self, key_id, pre_pause, state):
54 self.key_id = key_id
55 self.pre_pause = pre_pause
56 self.state = state
57
58 def __repr__(self):
59 return '{0} {1}'.format(self.key_id, self.state)
60
61 def __str__(self):
62 return 'MacroKey|{0}|{1}|{2}'.format(self.key_id, self.pre_pause, self.state)
63
64 def to_dict(self):
65 return {
66 'type': 'MacroKey',
67 'key_id': self.key_id,
68 'pre_pause': self.pre_pause,
69 'state': self.state
70 }
71
72 @property
73 def xte_key(self):
74 """
75 Convert key to XTE compatible name
76
77 :return: XTE Name
78 :rtype: str
79 """
80 return XTE_MAPPING.get(self.key_id, self.key_id)
81
82 # If it only opens a new tab in chroma - https://askubuntu.com/questions/540939/xdg-open-only-opens-a-new-tab-in-a-new-chromium-window-despite-passing-it-a-url
83
84
85 class MacroURL(MacroObject):
86 """
87 Is an object of a key event used in macros
88 """
89
90 def __init__(self, url):
91 self.url = url
92
93 def __repr__(self):
94 return '{0}'.format(self.url)
95
96 def __str__(self):
97 return 'MacroURL|{0}'.format(self.url)
98
99 def to_dict(self):
100 return {
101 'type': 'MacroURL',
102 'url': self.url,
103 }
104
105 def execute(self):
106 """
107 Open URL in the browser
108 """
109 proc = subprocess.Popen(['xdg-open', self.url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
110 proc.communicate()
111
112
113 class MacroScript(MacroObject):
114 """
115 Is an object of a key event used in macros
116 """
117
118 def __init__(self, script, args=None):
119 self.script = script
120 if isinstance(args, str):
121 self.args = ' ' + args
122 else:
123 self.args = ''
124
125 def __repr__(self):
126 return '{0}'.format(self.script)
127
128 def __str__(self):
129 return 'MacroScript|{0}'.format(self.script)
130
131 def to_dict(self):
132 return {
133 'type': 'MacroScript',
134 'script': self.script,
135 'args': self.args
136 }
137
138 def execute(self):
139 """
140 Run script
141 """
142 proc = subprocess.Popen(self.script + self.args, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
143 proc.communicate()
144
145
146 class MacroRunner(threading.Thread):
147 """
148 Thread to run macros
149 """
150
151 def __init__(self, device_id, macro_bind, macro_data):
152 super().__init__()
153
154 self._logger = logging.getLogger('razer.device{0}.macro{1}'.format(device_id, macro_bind))
155 self._macro_data = macro_data
156 self._macro_bind = macro_bind
157
158 @staticmethod
159 def xte_line(key_event):
160 """
161 Generate a line to be fet into XTE
162
163 :param key_event: Key event object
164 :type key_event: MacroKey
165
166 :return: String XTE script
167 :rtype: str
168 """
169 # Save key here to prevent 5odd dictionary lookups
170 key = key_event.xte_key
171
172 cmd = ''
173
174 if key is not None:
175 if XTE_SLEEP:
176 cmd += 'usleep {0}\n'.format(key_event.pre_pause)
177
178 if key_event.state == 'UP':
179 cmd += 'keyup {0}\n'.format(key)
180 else:
181 cmd += 'keydown {0}\n'.format(key)
182
183 return cmd
184
185 def run(self):
186 """
187 Main thread function
188 """
189
190 # TODO move the xte-munging to the init
191 xte = ''
192
193 for event in self._macro_data:
194 if isinstance(event, MacroKey):
195 xte += self.xte_line(event)
196 else:
197 if xte != '':
198 proc = subprocess.Popen(['xte'], stdin=subprocess.PIPE)
199 proc.communicate(input=xte.encode('ascii'))
200 xte = ''
201
202 # Now run everything else (this just allows for less calls to xte
203 if not isinstance(event, MacroKey):
204 event.execute()
205
206 if xte != '':
207 proc = subprocess.Popen(['xte'], stdin=subprocess.PIPE)
208 proc.communicate(input=xte.encode('ascii'))
209
210 self._logger.debug("Finished running macro %s", self._macro_bind)
211
212
213 def macro_dict_to_obj(macro_dict):
214 """
215 Converts a macro string to its relevant object
216
217 :param macro_dict: Macro string
218 :type macro_dict: dict
219
220 :return: Macro Object
221 :rtype: object
222
223 :raises ValueError: When a type isn't known
224 """
225
226 if macro_dict['type'] == 'MacroKey':
227 result = MacroKey.from_dict(macro_dict)
228 elif macro_dict['type'] == 'MacroURL':
229 result = MacroURL.from_dict(macro_dict)
230 elif macro_dict['type'] == 'MacroScript':
231 result = MacroScript.from_dict(macro_dict)
232 else:
233 raise ValueError("unknown type")
234
235 return result