]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blob - music_sampler/mapping.py
Cancel all timers and stop all musics when exiting
[perso/Immae/Projets/Python/MusicSampler.git] / music_sampler / mapping.py
1 from kivy.uix.relativelayout import RelativeLayout
2 from kivy.properties import NumericProperty, ListProperty, StringProperty
3 from kivy.core.window import Window
4 from kivy.clock import Clock
5
6 import threading
7 import yaml
8 import sys
9 from collections import defaultdict
10
11 from transitions.extensions import HierarchicalMachine as Machine
12
13 from .music_file import MusicFile
14 from .mixer import Mixer
15 from .helpers import Config, gain, error_print, warn_print
16 from .action import Action
17
18 class Mapping(RelativeLayout):
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'
59 },
60 {
61 'trigger': 'reload',
62 'source': 'loaded',
63 'dest': 'configuring'
64 }
65 ]
66
67 master_volume = NumericProperty(100)
68 ready_color = ListProperty([1, 165/255, 0, 1])
69 state = StringProperty("")
70
71 def __init__(self, **kwargs):
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):
87 if Config.builtin_mixing:
88 self.mixer = Mixer()
89 else:
90 self.mixer = None
91
92 try:
93 self.key_config, self.open_files = self.parse_config()
94 except Exception as e:
95 error_print("Error while loading configuration: {}".format(e),
96 with_trace=True, exit=True)
97 else:
98 self.success()
99
100 def on_enter_loading(self):
101 for key in self.keys:
102 key.reload()
103 self.success()
104
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)
110
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)
115
116 def on_keyboard_closed(self):
117 self.keyboard.unbind(on_key_down=self.on_keyboard_down)
118 self.keyboard = None
119
120 def on_keyboard_down(self, keyboard, keycode, text, modifiers):
121 key = self.find_by_key_code(keycode)
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()
126 elif 'ctrl' in modifiers and (keycode[0] == 113 or keycode[0] == '99'):
127 self.keyboard.unbind(on_key_down=self.on_keyboard_down)
128 self.stop_all_running()
129 for music in self.open_files.values():
130 music.stop()
131 for thread in threading.enumerate():
132 if thread.getName()[0:2] == "MS":
133 thread.join()
134 elif thread.__class__ == threading.Timer:
135 thread.cancel()
136 thread.join()
137
138 sys.exit()
139 elif 'ctrl' in modifiers and keycode[0] == 114:
140 threading.Thread(name="MSReload", target=self.reload).start()
141 return True
142
143 # Helpers
144 def allowed_modifiers(self, modifiers):
145 allowed = []
146 return len([a for a in modifiers if a not in allowed]) == 0
147
148 def find_by_key_code(self, key_code):
149 if "Key_" + str(key_code[0]) in self.ids:
150 return self.ids["Key_" + str(key_code[0])]
151 return None
152
153 def all_keys_ready(self):
154 partial = False
155 for key in self.keys:
156 if not key.is_loaded_or_failed():
157 return "not_ready"
158 partial = partial or key.is_failed()
159
160 if partial:
161 return "partial"
162 else:
163 return "success"
164
165 # Callbacks
166 def key_loaded_callback(self):
167 result = self.all_keys_ready()
168 if result == "success":
169 self.ready_color = [0, 1, 0, 1]
170 elif result == "partial":
171 self.ready_color = [1, 0, 0, 1]
172 else:
173 self.ready_color = [1, 165/255, 0, 1]
174
175 ## Some global actions
176 def stop_all_running(self, except_key=None, key_start_time=0):
177 running = self.running
178 self.running = [r for r in running\
179 if r[0] == except_key and r[1] == key_start_time]
180 for (key, start_time) in running:
181 if (key, start_time) != (except_key, key_start_time):
182 key.interrupt()
183
184 # Master volume methods
185 @property
186 def master_gain(self):
187 return gain(self.master_volume)
188
189 def set_master_volume(self, value, delta=False, fade=0):
190 [db_gain, self.master_volume] = gain(
191 value + int(delta) * self.master_volume,
192 self.master_volume)
193
194 for music in self.open_files.values():
195 music.set_gain_with_effect(db_gain, fade=fade)
196
197 # Wait handler methods
198 def add_wait_id(self, wait_id, action_or_wait):
199 self.wait_ids[wait_id] = action_or_wait
200
201 def interrupt_wait(self, wait_id):
202 if wait_id in self.wait_ids:
203 action_or_wait = self.wait_ids[wait_id]
204 del(self.wait_ids[wait_id])
205 if isinstance(action_or_wait, Action):
206 action_or_wait.interrupt()
207 else:
208 action_or_wait.set()
209
210 # Methods to control running keys
211 def start_running(self, key, start_time):
212 self.running.append((key, start_time))
213
214 def keep_running(self, key, start_time):
215 return (key, start_time) in self.running
216
217 def finished_running(self, key, start_time):
218 if (key, start_time) in self.running:
219 self.running.remove((key, start_time))
220
221 # YML config parser
222 def parse_config(self):
223 def update_alias(prop_hash, aliases, key):
224 if isinstance(aliases[key], dict):
225 prop_hash.update(aliases[key], **prop_hash)
226 else:
227 warn_print("Alias {} is not a hash, ignored".format(key))
228
229 def include_aliases(prop_hash, aliases):
230 if 'include' not in prop_hash:
231 return
232
233 included = prop_hash['include']
234 del(prop_hash['include'])
235 if isinstance(included, str):
236 update_alias(prop_hash, aliases, included)
237 elif isinstance(included, list):
238 for included_ in included:
239 if isinstance(included_, str):
240 update_alias(prop_hash, aliases, included_)
241 else:
242 warn_print("Unkown alias include type, ignored: "
243 "{} in {}".format(included_, included))
244 else:
245 warn_print("Unkown alias include type, ignored: {}"
246 .format(included))
247
248 def check_key_property(key_property, key):
249 if 'description' in key_property:
250 desc = key_property['description']
251 if not isinstance(desc, list):
252 warn_print("description in key_property '{}' is not "
253 "a list, ignored".format(key))
254 del(key_property['description'])
255 if 'color' in key_property:
256 color = key_property['color']
257 if not isinstance(color, list)\
258 or len(color) != 3\
259 or not all(isinstance(item, int) for item in color)\
260 or any(item < 0 or item > 255 for item in color):
261 warn_print("color in key_property '{}' is not "
262 "a list of 3 valid integers, ignored".format(key))
263 del(key_property['color'])
264
265 def check_key_properties(config):
266 if 'key_properties' in config:
267 if isinstance(config['key_properties'], dict):
268 return config['key_properties']
269 else:
270 warn_print("key_properties config is not a hash, ignored")
271 return {}
272 else:
273 return {}
274
275 def check_mapped_keys(config):
276 if 'keys' in config:
277 if isinstance(config['keys'], dict):
278 return config['keys']
279 else:
280 warn_print("keys config is not a hash, ignored")
281 return {}
282 else:
283 return {}
284
285 def check_mapped_key(mapped_keys, key):
286 if not isinstance(mapped_keys[key], list):
287 warn_print("key config '{}' is not an array, ignored"
288 .format(key))
289 return []
290 else:
291 return mapped_keys[key]
292
293 def check_music_property(music_property, filename):
294 if not isinstance(music_property, dict):
295 warn_print("music_property config '{}' is not a hash, ignored"
296 .format(filename))
297 return {}
298 if 'name' in music_property:
299 music_property['name'] = str(music_property['name'])
300 if 'gain' in music_property:
301 try:
302 music_property['gain'] = float(music_property['gain'])
303 except ValueError as e:
304 del(music_property['gain'])
305 warn_print("gain for music_property '{}' is not "
306 "a float, ignored".format(filename))
307 return music_property
308
309 stream = open(Config.yml_file, "r")
310 try:
311 config = yaml.safe_load(stream)
312 except Exception as e:
313 error_print("Error while loading config file: {}".format(e),
314 exit=True)
315 stream.close()
316
317 if not isinstance(config, dict):
318 error_print("Top level config is supposed to be a hash",
319 exit=True)
320
321 if 'aliases' in config and isinstance(config['aliases'], dict):
322 aliases = config['aliases']
323 else:
324 aliases = defaultdict(dict)
325 if 'aliases' in config:
326 warn_print("aliases config is not a hash, ignored")
327
328 music_properties = defaultdict(dict)
329 if 'music_properties' in config and\
330 isinstance(config['music_properties'], dict):
331 music_properties.update(config['music_properties'])
332 elif 'music_properties' in config:
333 warn_print("music_properties config is not a hash, ignored")
334
335 seen_files = {}
336
337 key_properties = defaultdict(lambda: {
338 "actions": [],
339 "properties": {},
340 "files": []
341 })
342
343 for key in check_key_properties(config):
344 key_prop = config['key_properties'][key]
345
346 if not isinstance(key_prop, dict):
347 warn_print("key_property '{}' is not a hash, ignored"
348 .format(key))
349 continue
350
351 include_aliases(key_prop, aliases)
352 check_key_property(key_prop, key)
353
354 key_properties[key]["properties"] = key_prop
355
356 for mapped_key in check_mapped_keys(config):
357 for index, action in enumerate(check_mapped_key(
358 config['keys'], mapped_key)):
359 if not isinstance(action, dict) or\
360 not len(action) == 1 or\
361 not isinstance(list(action.values())[0] or {}, dict):
362 warn_print("action number {} of key '{}' is invalid, "
363 "ignored".format(index + 1, mapped_key))
364 continue
365
366 action_name = list(action)[0]
367 action_args = {}
368 if action[action_name] is None:
369 action[action_name] = {}
370
371 include_aliases(action[action_name], aliases)
372
373 for argument in action[action_name]:
374 if argument == 'file':
375 filename = str(action[action_name]['file'])
376 if filename not in seen_files:
377 music_property = check_music_property(
378 music_properties[filename],
379 filename)
380
381 if filename in self.open_files:
382 self.open_files[filename]\
383 .reload_properties(**music_property)
384
385 seen_files[filename] =\
386 self.open_files[filename]
387 else:
388 seen_files[filename] = MusicFile(
389 filename, self, **music_property)
390
391 if filename not in key_properties[mapped_key]['files']:
392 key_properties[mapped_key]['files'] \
393 .append(seen_files[filename])
394
395 action_args['music'] = seen_files[filename]
396 else:
397 action_args[argument] = action[action_name][argument]
398
399 key_properties[mapped_key]['actions'] \
400 .append([action_name, action_args])
401
402 return (key_properties, seen_files)
403
404