]>
git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blob - helpers/mapping.py
1 from kivy
.uix
.relativelayout
import RelativeLayout
2 from kivy
.properties
import NumericProperty
, ListProperty
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 . 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',
62 master_volume
= NumericProperty(100)
63 ready_color
= ListProperty([1, 165/255, 0, 1])
65 def __init__(self
, **kwargs
):
66 if Config
.builtin_mixing
:
72 self
.key_config
, self
.open_files
= self
.parse_config()
73 except Exception as e
:
74 error_print("Error while loading configuration: {}".format(e
),
82 super(Mapping
, self
).__init
__(**kwargs
)
83 self
.keyboard
= Window
.request_keyboard(self
.on_keyboard_closed
, self
)
84 self
.keyboard
.bind(on_key_down
=self
.on_keyboard_down
)
87 def add_widget(self
, widget
, index
=0):
88 if type(widget
).__name
__ == "Key" and widget
not in self
.keys
:
89 self
.keys
.append(widget
)
90 return super(Mapping
, self
).add_widget(widget
, index
)
92 def remove_widget(self
, widget
, index
=0):
93 if type(widget
).__name
__ == "Key" and widget
in self
.keys
:
94 self
.keys
.remove(widget
)
95 return super(Mapping
, self
).remove_widget(widget
, index
)
97 def on_keyboard_closed(self
):
98 self
.keyboard
.unbind(on_key_down
=self
.on_keyboard_down
)
101 def on_keyboard_down(self
, keyboard
, keycode
, text
, modifiers
):
102 key
= self
.find_by_key_code(keycode
)
103 if self
.allowed_modifiers(modifiers
) and key
is not None:
105 threading
.Thread(name
="MSKeyAction", target
=key
.run
,
106 args
=['-'.join(modifiers
)]).start()
107 elif 'ctrl' in modifiers
and (keycode
[0] == 113 or keycode
[0] == '99'):
108 self
.stop_all_running()
109 for thread
in threading
.enumerate():
110 if thread
.getName()[0:2] != "MS":
118 def allowed_modifiers(self
, modifiers
):
120 return len([a
for a
in modifiers
if a
not in allowed
]) == 0
122 def find_by_key_code(self
, key_code
):
123 if "Key_" + str(key_code
[0]) in self
.ids
:
124 return self
.ids
["Key_" + str(key_code
[0])]
127 def all_keys_ready(self
):
129 for key
in self
.keys
:
130 if not key
.is_loaded_or_failed():
132 partial
= partial
or key
.is_failed()
140 def key_loaded_callback(self
):
141 result
= self
.all_keys_ready()
142 if result
== "success":
143 self
.ready_color
= [0, 1, 0, 1]
144 elif result
== "partial":
145 self
.ready_color
= [1, 0, 0, 1]
147 ## Some global actions
148 def stop_all_running(self
):
149 running
= self
.running
151 for (key
, start_time
) in running
:
154 # Master volume methods
156 def master_gain(self
):
157 return gain(self
.master_volume
)
159 def set_master_volume(self
, value
, delta
=False, fade
=0):
160 [db_gain
, self
.master_volume
] = gain(
161 value
+ int(delta
) * self
.master_volume
,
164 for music
in self
.open_files
.values():
165 music
.set_gain_with_effect(db_gain
, fade
=fade
)
167 # Wait handler methods
168 def add_wait_id(self
, wait_id
, action_or_wait
):
169 self
.wait_ids
[wait_id
] = action_or_wait
171 def interrupt_wait(self
, wait_id
):
172 if wait_id
in self
.wait_ids
:
173 action_or_wait
= self
.wait_ids
[wait_id
]
174 del(self
.wait_ids
[wait_id
])
175 if isinstance(action_or_wait
, Action
):
176 action_or_wait
.interrupt()
180 # Methods to control running keys
181 def start_running(self
, key
, start_time
):
182 self
.running
.append((key
, start_time
))
184 def keep_running(self
, key
, start_time
):
185 return (key
, start_time
) in self
.running
187 def finished_running(self
, key
, start_time
):
188 if (key
, start_time
) in self
.running
:
189 self
.running
.remove((key
, start_time
))
192 def parse_config(self
):
193 def update_alias(prop_hash
, aliases
, key
):
194 if isinstance(aliases
[key
], dict):
195 prop_hash
.update(aliases
[key
], **prop_hash
)
197 warn_print("Alias {} is not a hash, ignored".format(key
))
199 def include_aliases(prop_hash
, aliases
):
200 if 'include' not in prop_hash
:
203 included
= prop_hash
['include']
204 del(prop_hash
['include'])
205 if isinstance(included
, str):
206 update_alias(prop_hash
, aliases
, included
)
207 elif isinstance(included
, list):
208 for included_
in included
:
209 if isinstance(included_
, str):
210 update_alias(prop_hash
, aliases
, included_
)
212 warn_print("Unkown alias include type, ignored: "
213 "{} in {}".format(included_
, included
))
215 warn_print("Unkown alias include type, ignored: {}"
218 def check_key_property(key_property
, key
):
219 if 'description' in key_property
:
220 desc
= key_property
['description']
221 if not isinstance(desc
, list):
222 warn_print("description in key_property '{}' is not "
223 "a list, ignored".format(key
))
224 del(key_property
['description'])
225 if 'color' in key_property
:
226 color
= key_property
['color']
227 if not isinstance(color
, list)\
229 or not all(isinstance(item
, int) for item
in color
)\
230 or any(item
< 0 or item
> 255 for item
in color
):
231 warn_print("color in key_property '{}' is not "
232 "a list of 3 valid integers, ignored".format(key
))
233 del(key_property
['color'])
235 def check_key_properties(config
):
236 if 'key_properties' in config
:
237 if isinstance(config
['key_properties'], dict):
238 return config
['key_properties']
240 warn_print("key_properties config is not a hash, ignored")
245 def check_mapped_keys(config
):
247 if isinstance(config
['keys'], dict):
248 return config
['keys']
250 warn_print("keys config is not a hash, ignored")
255 def check_mapped_key(mapped_keys
, key
):
256 if not isinstance(mapped_keys
[key
], list):
257 warn_print("key config '{}' is not an array, ignored"
261 return mapped_keys
[key
]
263 def check_music_property(music_property
, filename
):
264 if not isinstance(music_property
, dict):
265 warn_print("music_property config '{}' is not a hash, ignored"
268 if 'name' in music_property
:
269 music_property
['name'] = str(music_property
['name'])
270 if 'gain' in music_property
:
272 music_property
['gain'] = float(music_property
['gain'])
273 except ValueError as e
:
274 del(music_property
['gain'])
275 warn_print("gain for music_property '{}' is not "
276 "a float, ignored".format(filename
))
277 return music_property
279 stream
= open(Config
.yml_file
, "r")
281 config
= yaml
.safe_load(stream
)
282 except Exception as e
:
283 error_print("Error while loading config file: {}".format(e
))
287 if not isinstance(config
, dict):
288 raise Exception("Top level config is supposed to be a hash")
290 if 'aliases' in config
and isinstance(config
['aliases'], dict):
291 aliases
= config
['aliases']
293 aliases
= defaultdict(dict)
294 if 'aliases' in config
:
295 warn_print("aliases config is not a hash, ignored")
297 music_properties
= defaultdict(dict)
298 if 'music_properties' in config
and\
299 isinstance(config
['music_properties'], dict):
300 music_properties
.update(config
['music_properties'])
301 elif 'music_properties' in config
:
302 warn_print("music_properties config is not a hash, ignored")
306 key_properties
= defaultdict(lambda: {
312 for key
in check_key_properties(config
):
313 key_prop
= config
['key_properties'][key
]
315 if not isinstance(key_prop
, dict):
316 warn_print("key_property '{}' is not a hash, ignored"
320 include_aliases(key_prop
, aliases
)
321 check_key_property(key_prop
, key
)
323 key_properties
[key
]["properties"] = key_prop
325 for mapped_key
in check_mapped_keys(config
):
326 for index
, action
in enumerate(check_mapped_key(
327 config
['keys'], mapped_key
)):
328 if not isinstance(action
, dict) or\
329 not len(action
) == 1 or\
330 not isinstance(list(action
.values())[0] or {}, dict):
331 warn_print("action number {} of key '{}' is invalid, "
332 "ignored".format(index
+ 1, mapped_key
))
335 action_name
= list(action
)[0]
337 if action
[action_name
] is None:
338 action
[action_name
] = {}
340 include_aliases(action
[action_name
], aliases
)
342 for argument
in action
[action_name
]:
343 if argument
== 'file':
344 filename
= str(action
[action_name
]['file'])
345 if filename
not in seen_files
:
346 music_property
= check_music_property(
347 music_properties
[filename
],
350 seen_files
[filename
] = MusicFile(
351 filename
, self
, **music_property
)
353 if filename
not in key_properties
[mapped_key
]['files']:
354 key_properties
[mapped_key
]['files'] \
355 .append(seen_files
[filename
])
357 action_args
['music'] = seen_files
[filename
]
359 action_args
[argument
] = action
[action_name
][argument
]
361 key_properties
[mapped_key
]['actions'] \
362 .append([action_name
, action_args
])
364 return (key_properties
, seen_files
)