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