]>
Commit | Line | Data |
---|---|---|
4b2d79ca | 1 | from kivy.uix.relativelayout import RelativeLayout |
ab47d2a1 | 2 | from kivy.properties import NumericProperty, ListProperty, StringProperty |
4b2d79ca | 3 | from kivy.core.window import Window |
30d8796f | 4 | from kivy.clock import Clock |
4b2d79ca | 5 | |
be27763f | 6 | import threading |
4b2d79ca | 7 | import yaml |
b68b4e8f | 8 | import sys |
05d0d2ed | 9 | from collections import defaultdict |
4b2d79ca | 10 | |
8ba7d831 IB |
11 | from transitions.extensions import HierarchicalMachine as Machine |
12 | ||
e55b29bb | 13 | from .music_file import MusicFile |
22514f3a | 14 | from .mixer import Mixer |
6ebe6247 | 15 | from .helpers import Config, gain, error_print, warn_print |
3aaddc9d | 16 | from .action import Action |
4b2d79ca IB |
17 | |
18 | class Mapping(RelativeLayout): | |
8ba7d831 IB |
19 | STATES = [ |
20 | 'initial', | |
21 | 'configuring', | |
22 | 'configured', | |
23 | 'loading', | |
24 | 'loaded', | |
25 | 'failed' | |
26 | ] | |
27 | ||
28 | TRANSITIONS = [ | |
29 | { | |
30 | 'trigger': 'configure', | |
31 | 'source': 'initial', | |
32 | 'dest': 'configuring' | |
33 | }, | |
34 | { | |
35 | 'trigger': 'fail', | |
36 | 'source': 'configuring', | |
37 | 'dest': 'failed' | |
38 | }, | |
39 | { | |
40 | 'trigger': 'success', | |
41 | 'source': 'configuring', | |
42 | 'dest': 'configured', | |
43 | 'after': 'load' | |
44 | }, | |
45 | { | |
46 | 'trigger': 'load', | |
47 | 'source': 'configured', | |
48 | 'dest': 'loading' | |
49 | }, | |
50 | { | |
51 | 'trigger': 'fail', | |
52 | 'source': 'loading', | |
53 | 'dest': 'failed' | |
54 | }, | |
55 | { | |
56 | 'trigger': 'success', | |
57 | 'source': 'loading', | |
58 | 'dest': 'loaded' | |
ab47d2a1 IB |
59 | }, |
60 | { | |
61 | 'trigger': 'reload', | |
62 | 'source': 'loaded', | |
63 | 'dest': 'configuring' | |
8ba7d831 IB |
64 | } |
65 | ] | |
66 | ||
1b4b78f5 | 67 | master_volume = NumericProperty(100) |
30d8796f | 68 | ready_color = ListProperty([1, 165/255, 0, 1]) |
ab47d2a1 | 69 | state = StringProperty("") |
4b2d79ca IB |
70 | |
71 | def __init__(self, **kwargs): | |
ab47d2a1 IB |
72 | self.keys = [] |
73 | self.running = [] | |
74 | self.wait_ids = {} | |
75 | self.open_files = {} | |
76 | ||
77 | Machine(model=self, states=self.STATES, | |
78 | transitions=self.TRANSITIONS, initial='initial', | |
79 | ignore_invalid_triggers=True, queued=True) | |
80 | super(Mapping, self).__init__(**kwargs) | |
81 | self.keyboard = Window.request_keyboard(self.on_keyboard_closed, self) | |
82 | self.keyboard.bind(on_key_down=self.on_keyboard_down) | |
83 | ||
84 | self.configure() | |
85 | ||
86 | def on_enter_configuring(self): | |
d6290f14 | 87 | if Config.builtin_mixing: |
af27d782 | 88 | self.mixer = Mixer() |
d6290f14 IB |
89 | else: |
90 | self.mixer = None | |
9c4f705f IB |
91 | |
92 | try: | |
93 | self.key_config, self.open_files = self.parse_config() | |
94 | except Exception as e: | |
05d0d2ed | 95 | error_print("Error while loading configuration: {}".format(e), |
2010311b | 96 | with_trace=True, exit=True) |
ab47d2a1 IB |
97 | else: |
98 | self.success() | |
9c4f705f | 99 | |
ab47d2a1 IB |
100 | def on_enter_loading(self): |
101 | for key in self.keys: | |
102 | key.reload() | |
103 | self.success() | |
1b4b78f5 | 104 | |
8ba7d831 IB |
105 | # Kivy events |
106 | def add_widget(self, widget, index=0): | |
107 | if type(widget).__name__ == "Key" and widget not in self.keys: | |
108 | self.keys.append(widget) | |
109 | return super(Mapping, self).add_widget(widget, index) | |
3aaddc9d | 110 | |
8ba7d831 IB |
111 | def remove_widget(self, widget, index=0): |
112 | if type(widget).__name__ == "Key" and widget in self.keys: | |
113 | self.keys.remove(widget) | |
114 | return super(Mapping, self).remove_widget(widget, index) | |
3aaddc9d | 115 | |
8ba7d831 IB |
116 | def on_keyboard_closed(self): |
117 | self.keyboard.unbind(on_key_down=self.on_keyboard_down) | |
118 | self.keyboard = None | |
4b2d79ca | 119 | |
8ba7d831 | 120 | def on_keyboard_down(self, keyboard, keycode, text, modifiers): |
4b2d79ca | 121 | key = self.find_by_key_code(keycode) |
4b6d1836 IB |
122 | if self.allowed_modifiers(modifiers) and key is not None: |
123 | modifiers.sort() | |
124 | threading.Thread(name="MSKeyAction", target=key.run, | |
125 | args=['-'.join(modifiers)]).start() | |
b68b4e8f | 126 | elif 'ctrl' in modifiers and (keycode[0] == 113 or keycode[0] == '99'): |
ca3264c8 | 127 | self.leave_application() |
b68b4e8f | 128 | sys.exit() |
ab47d2a1 IB |
129 | elif 'ctrl' in modifiers and keycode[0] == 114: |
130 | threading.Thread(name="MSReload", target=self.reload).start() | |
4b2d79ca IB |
131 | return True |
132 | ||
ca3264c8 IB |
133 | def leave_application(self): |
134 | self.keyboard.unbind(on_key_down=self.on_keyboard_down) | |
135 | self.stop_all_running() | |
136 | for music in self.open_files.values(): | |
137 | music.stop() | |
138 | for thread in threading.enumerate(): | |
139 | if thread.getName()[0:2] == "MS": | |
140 | thread.join() | |
141 | elif thread.__class__ == threading.Timer: | |
142 | thread.cancel() | |
143 | thread.join() | |
144 | ||
4b6d1836 IB |
145 | # Helpers |
146 | def allowed_modifiers(self, modifiers): | |
147 | allowed = [] | |
148 | return len([a for a in modifiers if a not in allowed]) == 0 | |
149 | ||
4b2d79ca IB |
150 | def find_by_key_code(self, key_code): |
151 | if "Key_" + str(key_code[0]) in self.ids: | |
152 | return self.ids["Key_" + str(key_code[0])] | |
be27763f IB |
153 | return None |
154 | ||
8ba7d831 IB |
155 | def all_keys_ready(self): |
156 | partial = False | |
157 | for key in self.keys: | |
e55b29bb | 158 | if not key.is_loaded_or_failed(): |
8ba7d831 IB |
159 | return "not_ready" |
160 | partial = partial or key.is_failed() | |
161 | ||
162 | if partial: | |
163 | return "partial" | |
164 | else: | |
165 | return "success" | |
166 | ||
167 | # Callbacks | |
168 | def key_loaded_callback(self): | |
169 | result = self.all_keys_ready() | |
170 | if result == "success": | |
171 | self.ready_color = [0, 1, 0, 1] | |
172 | elif result == "partial": | |
173 | self.ready_color = [1, 0, 0, 1] | |
ab47d2a1 IB |
174 | else: |
175 | self.ready_color = [1, 165/255, 0, 1] | |
30d8796f | 176 | |
8ba7d831 | 177 | ## Some global actions |
62a8b07a | 178 | def stop_all_running(self, except_key=None, key_start_time=0): |
0deb82a5 | 179 | running = self.running |
62a8b07a IB |
180 | self.running = [r for r in running\ |
181 | if r[0] == except_key and r[1] == key_start_time] | |
0deb82a5 | 182 | for (key, start_time) in running: |
62a8b07a IB |
183 | if (key, start_time) != (except_key, key_start_time): |
184 | key.interrupt() | |
be27763f | 185 | |
8ba7d831 IB |
186 | # Master volume methods |
187 | @property | |
188 | def master_gain(self): | |
189 | return gain(self.master_volume) | |
190 | ||
191 | def set_master_volume(self, value, delta=False, fade=0): | |
192 | [db_gain, self.master_volume] = gain( | |
193 | value + int(delta) * self.master_volume, | |
194 | self.master_volume) | |
195 | ||
196 | for music in self.open_files.values(): | |
197 | music.set_gain_with_effect(db_gain, fade=fade) | |
198 | ||
199 | # Wait handler methods | |
200 | def add_wait_id(self, wait_id, action_or_wait): | |
201 | self.wait_ids[wait_id] = action_or_wait | |
202 | ||
203 | def interrupt_wait(self, wait_id): | |
204 | if wait_id in self.wait_ids: | |
205 | action_or_wait = self.wait_ids[wait_id] | |
206 | del(self.wait_ids[wait_id]) | |
207 | if isinstance(action_or_wait, Action): | |
208 | action_or_wait.interrupt() | |
209 | else: | |
210 | action_or_wait.set() | |
211 | ||
212 | # Methods to control running keys | |
be27763f IB |
213 | def start_running(self, key, start_time): |
214 | self.running.append((key, start_time)) | |
215 | ||
216 | def keep_running(self, key, start_time): | |
217 | return (key, start_time) in self.running | |
218 | ||
219 | def finished_running(self, key, start_time): | |
220 | if (key, start_time) in self.running: | |
221 | self.running.remove((key, start_time)) | |
222 | ||
8ba7d831 | 223 | # YML config parser |
4b2d79ca | 224 | def parse_config(self): |
05d0d2ed IB |
225 | def update_alias(prop_hash, aliases, key): |
226 | if isinstance(aliases[key], dict): | |
227 | prop_hash.update(aliases[key], **prop_hash) | |
228 | else: | |
229 | warn_print("Alias {} is not a hash, ignored".format(key)) | |
230 | ||
231 | def include_aliases(prop_hash, aliases): | |
232 | if 'include' not in prop_hash: | |
233 | return | |
234 | ||
235 | included = prop_hash['include'] | |
236 | del(prop_hash['include']) | |
237 | if isinstance(included, str): | |
238 | update_alias(prop_hash, aliases, included) | |
239 | elif isinstance(included, list): | |
240 | for included_ in included: | |
241 | if isinstance(included_, str): | |
242 | update_alias(prop_hash, aliases, included_) | |
243 | else: | |
244 | warn_print("Unkown alias include type, ignored: " | |
245 | "{} in {}".format(included_, included)) | |
246 | else: | |
247 | warn_print("Unkown alias include type, ignored: {}" | |
248 | .format(included)) | |
249 | ||
250 | def check_key_property(key_property, key): | |
251 | if 'description' in key_property: | |
252 | desc = key_property['description'] | |
253 | if not isinstance(desc, list): | |
254 | warn_print("description in key_property '{}' is not " | |
255 | "a list, ignored".format(key)) | |
256 | del(key_property['description']) | |
257 | if 'color' in key_property: | |
258 | color = key_property['color'] | |
259 | if not isinstance(color, list)\ | |
260 | or len(color) != 3\ | |
261 | or not all(isinstance(item, int) for item in color)\ | |
262 | or any(item < 0 or item > 255 for item in color): | |
263 | warn_print("color in key_property '{}' is not " | |
264 | "a list of 3 valid integers, ignored".format(key)) | |
265 | del(key_property['color']) | |
266 | ||
267 | def check_key_properties(config): | |
268 | if 'key_properties' in config: | |
269 | if isinstance(config['key_properties'], dict): | |
270 | return config['key_properties'] | |
271 | else: | |
272 | warn_print("key_properties config is not a hash, ignored") | |
273 | return {} | |
274 | else: | |
275 | return {} | |
276 | ||
277 | def check_mapped_keys(config): | |
278 | if 'keys' in config: | |
279 | if isinstance(config['keys'], dict): | |
280 | return config['keys'] | |
281 | else: | |
282 | warn_print("keys config is not a hash, ignored") | |
283 | return {} | |
284 | else: | |
285 | return {} | |
286 | ||
287 | def check_mapped_key(mapped_keys, key): | |
288 | if not isinstance(mapped_keys[key], list): | |
289 | warn_print("key config '{}' is not an array, ignored" | |
290 | .format(key)) | |
291 | return [] | |
292 | else: | |
293 | return mapped_keys[key] | |
294 | ||
295 | def check_music_property(music_property, filename): | |
296 | if not isinstance(music_property, dict): | |
297 | warn_print("music_property config '{}' is not a hash, ignored" | |
298 | .format(filename)) | |
299 | return {} | |
300 | if 'name' in music_property: | |
301 | music_property['name'] = str(music_property['name']) | |
302 | if 'gain' in music_property: | |
303 | try: | |
304 | music_property['gain'] = float(music_property['gain']) | |
305 | except ValueError as e: | |
306 | del(music_property['gain']) | |
307 | warn_print("gain for music_property '{}' is not " | |
308 | "a float, ignored".format(filename)) | |
309 | return music_property | |
310 | ||
75d6cdba | 311 | stream = open(Config.yml_file, "r") |
6c44b231 | 312 | try: |
05d0d2ed | 313 | config = yaml.safe_load(stream) |
aee1334c | 314 | except Exception as e: |
2010311b IB |
315 | error_print("Error while loading config file: {}".format(e), |
316 | exit=True) | |
4b2d79ca IB |
317 | stream.close() |
318 | ||
05d0d2ed | 319 | if not isinstance(config, dict): |
2010311b IB |
320 | error_print("Top level config is supposed to be a hash", |
321 | exit=True) | |
05d0d2ed IB |
322 | |
323 | if 'aliases' in config and isinstance(config['aliases'], dict): | |
324 | aliases = config['aliases'] | |
325 | else: | |
326 | aliases = defaultdict(dict) | |
327 | if 'aliases' in config: | |
328 | warn_print("aliases config is not a hash, ignored") | |
329 | ||
330 | music_properties = defaultdict(dict) | |
331 | if 'music_properties' in config and\ | |
332 | isinstance(config['music_properties'], dict): | |
333 | music_properties.update(config['music_properties']) | |
334 | elif 'music_properties' in config: | |
335 | warn_print("music_properties config is not a hash, ignored") | |
336 | ||
4b2d79ca IB |
337 | seen_files = {} |
338 | ||
05d0d2ed IB |
339 | key_properties = defaultdict(lambda: { |
340 | "actions": [], | |
341 | "properties": {}, | |
342 | "files": [] | |
343 | }) | |
4b2d79ca | 344 | |
05d0d2ed IB |
345 | for key in check_key_properties(config): |
346 | key_prop = config['key_properties'][key] | |
347 | ||
348 | if not isinstance(key_prop, dict): | |
349 | warn_print("key_property '{}' is not a hash, ignored" | |
350 | .format(key)) | |
351 | continue | |
352 | ||
353 | include_aliases(key_prop, aliases) | |
354 | check_key_property(key_prop, key) | |
355 | ||
356 | key_properties[key]["properties"] = key_prop | |
357 | ||
358 | for mapped_key in check_mapped_keys(config): | |
359 | for index, action in enumerate(check_mapped_key( | |
360 | config['keys'], mapped_key)): | |
361 | if not isinstance(action, dict) or\ | |
362 | not len(action) == 1 or\ | |
363 | not isinstance(list(action.values())[0] or {}, dict): | |
364 | warn_print("action number {} of key '{}' is invalid, " | |
365 | "ignored".format(index + 1, mapped_key)) | |
366 | continue | |
e5edd8b9 | 367 | |
4b2d79ca IB |
368 | action_name = list(action)[0] |
369 | action_args = {} | |
370 | if action[action_name] is None: | |
05d0d2ed | 371 | action[action_name] = {} |
4b2d79ca | 372 | |
05d0d2ed | 373 | include_aliases(action[action_name], aliases) |
4b2d79ca IB |
374 | |
375 | for argument in action[action_name]: | |
376 | if argument == 'file': | |
05d0d2ed | 377 | filename = str(action[action_name]['file']) |
4b2d79ca | 378 | if filename not in seen_files: |
05d0d2ed IB |
379 | music_property = check_music_property( |
380 | music_properties[filename], | |
381 | filename) | |
382 | ||
ab47d2a1 IB |
383 | if filename in self.open_files: |
384 | self.open_files[filename]\ | |
385 | .reload_properties(**music_property) | |
386 | ||
6c42e32d IB |
387 | seen_files[filename] =\ |
388 | self.open_files[filename] | |
ab47d2a1 IB |
389 | else: |
390 | seen_files[filename] = MusicFile( | |
391 | filename, self, **music_property) | |
4b2d79ca IB |
392 | |
393 | if filename not in key_properties[mapped_key]['files']: | |
2e404903 IB |
394 | key_properties[mapped_key]['files'] \ |
395 | .append(seen_files[filename]) | |
4b2d79ca IB |
396 | |
397 | action_args['music'] = seen_files[filename] | |
4b2d79ca IB |
398 | else: |
399 | action_args[argument] = action[action_name][argument] | |
400 | ||
2e404903 IB |
401 | key_properties[mapped_key]['actions'] \ |
402 | .append([action_name, action_args]) | |
4b2d79ca | 403 | |
29597680 | 404 | return (key_properties, seen_files) |
4b2d79ca IB |
405 | |
406 |