]> git.immae.eu Git - perso/Immae/Projets/Python/MusicSampler.git/blob - helpers/action.py
1f374ec6a4ffb843e8e938b27fb85b61a0a611f4
[perso/Immae/Projets/Python/MusicSampler.git] / helpers / action.py
1 from transitions.extensions import HierarchicalMachine as Machine
2 from . import debug_print, error_print
3 from . import actions
4
5 class Action:
6 STATES = [
7 'initial',
8 'loading',
9 'failed',
10 {
11 'name': 'loaded',
12 'children': ['running']
13 }
14 ]
15
16 TRANSITIONS = [
17 {
18 'trigger': 'load',
19 'source': 'initial',
20 'dest': 'loading'
21 },
22 {
23 'trigger': 'fail',
24 'source': 'loading',
25 'dest': 'failed',
26 'after': 'poll_loaded'
27 },
28 {
29 'trigger': 'success',
30 'source': 'loading',
31 'dest': 'loaded',
32 'after': 'poll_loaded'
33 },
34 {
35 'trigger': 'run',
36 'source': 'loaded',
37 'dest': 'loaded_running',
38 'after': 'finish_action',
39 # if a child has no transitions, then it is bubbled to the parent,
40 # and we don't want that. Not useful in that machine precisely.
41 'conditions': ['is_loaded']
42 },
43 {
44 'trigger': 'finish_action',
45 'source': 'loaded_running',
46 'dest': 'loaded'
47 }
48 ]
49
50 def __init__(self, action, key, **kwargs):
51 Machine(model=self, states=self.STATES,
52 transitions=self.TRANSITIONS, initial='initial',
53 ignore_invalid_triggers=True, queued=True)
54
55 self.action = action
56 self.key = key
57 self.mapping = key.parent
58 self.arguments = kwargs
59 self.sleep_event = None
60 self.waiting_music = None
61
62 def is_loaded_or_failed(self):
63 return self.is_loaded(allow_substates=True) or self.is_failed()
64
65 def callback_music_loaded(self, success):
66 if success:
67 self.success()
68 else:
69 self.fail()
70
71 # Machine states / events
72 def on_enter_loading(self):
73 if hasattr(actions, self.action):
74 if 'music' in self.arguments:
75 self.arguments['music'].subscribe_loaded(self.callback_music_loaded)
76 else:
77 self.success()
78 else:
79 error_print("Unknown action {}".format(self.action))
80 self.fail()
81
82 def on_enter_loaded_running(self):
83 debug_print(self.description())
84 if hasattr(actions, self.action):
85 getattr(actions, self.action).run(self, **self.arguments)
86
87 def poll_loaded(self):
88 self.key.callback_action_ready(self,
89 self.is_loaded(allow_substates=True))
90
91 # This one cannot be in the Machine state since it would be queued to run
92 # *after* the wait is ended...
93 def interrupt(self):
94 if getattr(actions, self.action, None) and\
95 hasattr(getattr(actions, self.action), 'interrupt'):
96 return getattr(getattr(actions, self.action), 'interrupt')(
97 self, **self.arguments)
98
99 # Helpers
100 def music_list(self, music):
101 if music is not None:
102 return [music]
103 else:
104 return self.mapping.open_files.values()
105
106 def description(self):
107 if hasattr(actions, self.action):
108 return getattr(actions, self.action)\
109 .description(self, **self.arguments)
110 else:
111 return "unknown action {}".format(self.action)