]>
git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blob - 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
9 from collections
import defaultdict
11 from transitions
.extensions
import HierarchicalMachine
as Machine
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
18 class Mapping(RelativeLayout
):
30 'trigger': 'configure',
36 'source': 'configuring',
41 'source': 'configuring',
47 'source': 'configured',
67 master_volume
= NumericProperty(100)
68 ready_color
= ListProperty([1, 165/255, 0, 1])
69 state
= StringProperty("")
71 def __init__(self
, **kwargs
):
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
)
86 def on_enter_configuring(self
):
87 if Config
.builtin_mixing
:
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)
100 def on_enter_loading(self
):
101 for key
in self
.keys
:
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
)
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
)
116 def on_keyboard_closed(self
):
117 self
.keyboard
.unbind(on_key_down
=self
.on_keyboard_down
)
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:
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
.stop_all_running()
128 for thread
in threading
.enumerate():
129 if thread
.getName()[0:2] != "MS":
134 elif 'ctrl' in modifiers
and keycode
[0] == 114:
135 threading
.Thread(name
="MSReload", target
=self
.reload).start()
139 def allowed_modifiers(self
, modifiers
):
141 return len([a
for a
in modifiers
if a
not in allowed
]) == 0
143 def find_by_key_code(self
, key_code
):
144 if "Key_" + str(key_code
[0]) in self
.ids
:
145 return self
.ids
["Key_" + str(key_code
[0])]
148 def all_keys_ready(self
):
150 for key
in self
.keys
:
151 if not key
.is_loaded_or_failed():
153 partial
= partial
or key
.is_failed()
161 def key_loaded_callback(self
):
162 result
= self
.all_keys_ready()
163 if result
== "success":
164 self
.ready_color
= [0, 1, 0, 1]
165 elif result
== "partial":
166 self
.ready_color
= [1, 0, 0, 1]
168 self
.ready_color
= [1, 165/255, 0, 1]
170 ## Some global actions
171 def stop_all_running(self
, except_key
=None, key_start_time
=0):
172 running
= self
.running
173 self
.running
= [r
for r
in running\
174 if r
[0] == except_key
and r
[1] == key_start_time
]
175 for (key
, start_time
) in running
:
176 if (key
, start_time
) != (except_key
, key_start_time
):
179 # Master volume methods
181 def master_gain(self
):
182 return gain(self
.master_volume
)
184 def set_master_volume(self
, value
, delta
=False, fade
=0):
185 [db_gain
, self
.master_volume
] = gain(
186 value
+ int(delta
) * self
.master_volume
,
189 for music
in self
.open_files
.values():
190 music
.set_gain_with_effect(db_gain
, fade
=fade
)
192 # Wait handler methods
193 def add_wait_id(self
, wait_id
, action_or_wait
):
194 self
.wait_ids
[wait_id
] = action_or_wait
196 def interrupt_wait(self
, wait_id
):
197 if wait_id
in self
.wait_ids
:
198 action_or_wait
= self
.wait_ids
[wait_id
]
199 del(self
.wait_ids
[wait_id
])
200 if isinstance(action_or_wait
, Action
):
201 action_or_wait
.interrupt()
205 # Methods to control running keys
206 def start_running(self
, key
, start_time
):
207 self
.running
.append((key
, start_time
))
209 def keep_running(self
, key
, start_time
):
210 return (key
, start_time
) in self
.running
212 def finished_running(self
, key
, start_time
):
213 if (key
, start_time
) in self
.running
:
214 self
.running
.remove((key
, start_time
))
217 def parse_config(self
):
218 def update_alias(prop_hash
, aliases
, key
):
219 if isinstance(aliases
[key
], dict):
220 prop_hash
.update(aliases
[key
], **prop_hash
)
222 warn_print("Alias {} is not a hash, ignored".format(key
))
224 def include_aliases(prop_hash
, aliases
):
225 if 'include' not in prop_hash
:
228 included
= prop_hash
['include']
229 del(prop_hash
['include'])
230 if isinstance(included
, str):
231 update_alias(prop_hash
, aliases
, included
)
232 elif isinstance(included
, list):
233 for included_
in included
:
234 if isinstance(included_
, str):
235 update_alias(prop_hash
, aliases
, included_
)
237 warn_print("Unkown alias include type, ignored: "
238 "{} in {}".format(included_
, included
))
240 warn_print("Unkown alias include type, ignored: {}"
243 def check_key_property(key_property
, key
):
244 if 'description' in key_property
:
245 desc
= key_property
['description']
246 if not isinstance(desc
, list):
247 warn_print("description in key_property '{}' is not "
248 "a list, ignored".format(key
))
249 del(key_property
['description'])
250 if 'color' in key_property
:
251 color
= key_property
['color']
252 if not isinstance(color
, list)\
254 or not all(isinstance(item
, int) for item
in color
)\
255 or any(item
< 0 or item
> 255 for item
in color
):
256 warn_print("color in key_property '{}' is not "
257 "a list of 3 valid integers, ignored".format(key
))
258 del(key_property
['color'])
260 def check_key_properties(config
):
261 if 'key_properties' in config
:
262 if isinstance(config
['key_properties'], dict):
263 return config
['key_properties']
265 warn_print("key_properties config is not a hash, ignored")
270 def check_mapped_keys(config
):
272 if isinstance(config
['keys'], dict):
273 return config
['keys']
275 warn_print("keys config is not a hash, ignored")
280 def check_mapped_key(mapped_keys
, key
):
281 if not isinstance(mapped_keys
[key
], list):
282 warn_print("key config '{}' is not an array, ignored"
286 return mapped_keys
[key
]
288 def check_music_property(music_property
, filename
):
289 if not isinstance(music_property
, dict):
290 warn_print("music_property config '{}' is not a hash, ignored"
293 if 'name' in music_property
:
294 music_property
['name'] = str(music_property
['name'])
295 if 'gain' in music_property
:
297 music_property
['gain'] = float(music_property
['gain'])
298 except ValueError as e
:
299 del(music_property
['gain'])
300 warn_print("gain for music_property '{}' is not "
301 "a float, ignored".format(filename
))
302 return music_property
304 stream
= open(Config
.yml_file
, "r")
306 config
= yaml
.safe_load(stream
)
307 except Exception as e
:
308 error_print("Error while loading config file: {}".format(e
),
312 if not isinstance(config
, dict):
313 error_print("Top level config is supposed to be a hash",
316 if 'aliases' in config
and isinstance(config
['aliases'], dict):
317 aliases
= config
['aliases']
319 aliases
= defaultdict(dict)
320 if 'aliases' in config
:
321 warn_print("aliases config is not a hash, ignored")
323 music_properties
= defaultdict(dict)
324 if 'music_properties' in config
and\
325 isinstance(config
['music_properties'], dict):
326 music_properties
.update(config
['music_properties'])
327 elif 'music_properties' in config
:
328 warn_print("music_properties config is not a hash, ignored")
332 key_properties
= defaultdict(lambda: {
338 for key
in check_key_properties(config
):
339 key_prop
= config
['key_properties'][key
]
341 if not isinstance(key_prop
, dict):
342 warn_print("key_property '{}' is not a hash, ignored"
346 include_aliases(key_prop
, aliases
)
347 check_key_property(key_prop
, key
)
349 key_properties
[key
]["properties"] = key_prop
351 for mapped_key
in check_mapped_keys(config
):
352 for index
, action
in enumerate(check_mapped_key(
353 config
['keys'], mapped_key
)):
354 if not isinstance(action
, dict) or\
355 not len(action
) == 1 or\
356 not isinstance(list(action
.values())[0] or {}, dict):
357 warn_print("action number {} of key '{}' is invalid, "
358 "ignored".format(index
+ 1, mapped_key
))
361 action_name
= list(action
)[0]
363 if action
[action_name
] is None:
364 action
[action_name
] = {}
366 include_aliases(action
[action_name
], aliases
)
368 for argument
in action
[action_name
]:
369 if argument
== 'file':
370 filename
= str(action
[action_name
]['file'])
371 if filename
not in seen_files
:
372 music_property
= check_music_property(
373 music_properties
[filename
],
376 if filename
in self
.open_files
:
377 self
.open_files
[filename
]\
378 .reload_properties(**music_property
)
380 seen_files
[filename
] =\
381 self
.open_files
[filename
]
383 seen_files
[filename
] = MusicFile(
384 filename
, self
, **music_property
)
386 if filename
not in key_properties
[mapped_key
]['files']:
387 key_properties
[mapped_key
]['files'] \
388 .append(seen_files
[filename
])
390 action_args
['music'] = seen_files
[filename
]
392 action_args
[argument
] = action
[action_name
][argument
]
394 key_properties
[mapped_key
]['actions'] \
395 .append([action_name
, action_args
])
397 return (key_properties
, seen_files
)