Implémentation du bouton « Home » de la télécommande.
[minwii.git] / src / minwii / widgets / playingscreen.py
1 # -*- coding: utf-8 -*-
2 """
3 Écran de jeu MinWii :
4 bandes arc-en-ciel représentant un clavier.
5
6 $Id$
7 $URL$
8 """
9 import pygame
10 import types
11
12 import minwii.events as events
13 from minwii.log import eventLogger
14 from minwii.eventutils import event_handler, EventDispatcher, EventHandlerMixin
15 from minwii.musicxml import Tone
16 from minwii.config import FRAMERATE
17 from minwii.config import FIRST_HUE
18 from minwii.config import MIDI_VELOCITY_RANGE
19 from minwii.config import MIDI_PAN_RANGE
20 from minwii.config import MIDI_VELOCITY_WRONG_NOTE_ATTN
21 from minwii.globals import BACKGROUND_LAYER
22 from minwii.globals import CURSOR_LAYER
23 from minwii.globals import PLAYING_MODES_DICT
24
25 from cursors import WarpingCursor
26 from column import Column
27
28 class PlayingScreenBase(pygame.sprite.LayeredDirty, EventHandlerMixin) :
29
30 def __init__(self, synth, distinctNotes=[]) :
31 """
32 distinctNotes : notes disctinctes présentes dans la chanson
33 triées du plus grave au plus aigu.
34 """
35 super(PlayingScreenBase, self).__init__()
36 self.synth = synth
37 self.distinctNotes = distinctNotes
38 self.keyboardLength = 0
39 self.keyboardRects = []
40 self.cursor = None
41 self._initRects()
42 self.columns = {}
43 self._initColumns()
44 self._running = False
45 self.draw(pygame.display.get_surface())
46 self._initCursor()
47
48 def _initRects(self) :
49 """ création des espaces réservés pour
50 afficher les colonnes.
51 """
52 self.keyboardLength = len(self.distinctNotes)
53
54 screen = pygame.display.get_surface()
55
56 self.dispWidth = dispWidth = screen.get_width()
57 self.dispHeight = dispHeight = screen.get_height()
58
59 columnWidth = int(round(float(dispWidth) / self.keyboardLength))
60
61 rects = []
62 for i in range(self.keyboardLength) :
63 upperLeftCorner = (i*columnWidth, 0)
64 rect = pygame.Rect(upperLeftCorner, (columnWidth, dispHeight))
65 rects.append(rect)
66
67 self.keyboardRects = rects
68
69 def _initColumns(self) :
70
71 hueStep = FIRST_HUE / (self.keyboardLength - 1)
72 for i, rect in enumerate(self.keyboardRects) :
73 hue = FIRST_HUE - hueStep * i
74 tone = self.distinctNotes[i]
75 c = Column(self, i, hue, rect, tone)
76 self.add(c, layer=BACKGROUND_LAYER)
77 self.columns[tone.midi] = c
78
79
80 def _initCursor(self) :
81 self.cursor = WarpingCursor(blinkMode=True)
82 self.add(self.cursor, layer=CURSOR_LAYER)
83
84 def run(self):
85 self._running = True
86 clock = pygame.time.Clock()
87 pygame.display.flip()
88 pygame.mouse.set_visible(False)
89 while self._running :
90 EventDispatcher.dispatchEvents()
91 dirty = self.draw(pygame.display.get_surface())
92 pygame.display.update(dirty)
93 clock.tick(FRAMERATE)
94
95 def stop(self) :
96 self._running = False
97 self.synth.system_reset()
98 pygame.mouse.set_visible(True)
99 self.cursor._stopBlink()
100
101 @event_handler(pygame.KEYDOWN)
102 def handleKeyDown(self, event) :
103 if event.key == pygame.K_q or \
104 event.unicode == u'q' or \
105 pygame.K_ESCAPE:
106 self.stop()
107
108 @event_handler(pygame.MOUSEBUTTONDOWN)
109 def onMouseDown(self, event) :
110 # TODO à cleaner : on vire le dernier élément
111 # parce qu'il s'agit du curseur
112 for col in reversed(self.sprites()[:-1]) :
113 if col.rect.collidepoint(*event.pos):
114 self.raiseColDown(col, event)
115 break
116
117 @event_handler(pygame.MOUSEBUTTONUP)
118 def onMouseUp(self, event) :
119 for col in reversed(self.sprites()[:-1]) :
120 if col.rect.collidepoint(*event.pos) :
121 self.raiseColUp(col, event)
122 break
123
124 @event_handler(pygame.MOUSEMOTION)
125 def onMouseMove(self, event) :
126 for col in reversed(self.sprites()[:-1]) :
127 if col.rect.collidepoint(*event.pos) :
128 self.raiseColOver(col, event)
129 break
130
131 def raiseColDown(self, col, mouseEvent) :
132 evt = pygame.event.Event(events.COLDOWN, column=col, pos=mouseEvent.pos)
133 pygame.event.post(evt)
134
135 def raiseColUp(self, col, mouseEvent) :
136 evt = pygame.event.Event(events.COLUP, column=col, pos=mouseEvent.pos)
137 pygame.event.post(evt)
138
139 def raiseColOver(self, col, mouseEvent) :
140 evt = pygame.event.Event(events.COLOVER, column=col, pos=mouseEvent.pos, mouseEvent=mouseEvent)
141 pygame.event.post(evt)
142
143 def getVelocity(self, pos) :
144 vel = (float(self.dispWidth) - pos[1]) / self.dispWidth
145 vel = int(vel * (MIDI_VELOCITY_RANGE[1] - MIDI_VELOCITY_RANGE[0])) + MIDI_VELOCITY_RANGE[0]
146 return vel
147
148 def getPan(self, index) :
149 pan = float(index) / (self.keyboardLength -1)
150 pan = int(pan * (MIDI_PAN_RANGE[1] - MIDI_PAN_RANGE[0])) + MIDI_PAN_RANGE[0]
151 return pan
152
153 def playnote(self, col, pos, vel=None) :
154 pan = self.getPan(col.index)
155 self.synth.cc(0, 10, pan)
156 vel = vel or self.getVelocity(pos)
157 self.synth.noteon(0, col.tone.midi, vel)
158
159 class PlayingScreen(PlayingScreenBase) :
160 "fenêtre de jeu pour improvisation"
161
162 scale = [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
163
164 def __init__(self, synth) :
165 distinctNotes = []
166 self.currentColumn = None
167 for midi in self.scale :
168 tone = Tone(midi)
169 distinctNotes.append(tone)
170
171 super(PlayingScreen, self).__init__(synth, distinctNotes)
172
173 @event_handler(events.COLDOWN)
174 def noteon(self, event) :
175 col = event.column
176 col.update(True)
177 self.currentColumn = col
178 self.playnote(col, event.pos)
179
180 @event_handler(events.COLUP)
181 def noteoff(self, event) :
182 if self.currentColumn :
183 self.currentColumn.update(False)
184 self.synth.noteoff(0, self.currentColumn.tone.midi)
185
186
187 class SongPlayingScreen(PlayingScreenBase) :
188
189 def __init__(self, synth, song, mode=PLAYING_MODES_DICT['NORMAL']) :
190 super(SongPlayingScreen, self).__init__(synth, song.distinctNotes)
191 self.song = song
192 self.quarterNoteDuration = song.quarterNoteDuration
193 self.currentColumn = None
194 self.noteIterator = self.song.iterNotes()
195 self.displayNext()
196 self._plugListeners(mode)
197
198 def _plugListeners(self, mode) :
199 "initialisation des gestionnaires d'événements en fonction du mode"
200
201 if mode == PLAYING_MODES_DICT['BEGINNER'] :
202 EventDispatcher.addEventListener(events.COLOVER, self.handleBeginnerColumnOver)
203
204 elif mode == PLAYING_MODES_DICT['EASY'] :
205 EventDispatcher.addEventListener(events.COLDOWN, self.handleEasyColumnDown)
206 EventDispatcher.addEventListener(events.COLOVER, self.handleEasyColumnOver)
207
208 elif mode == PLAYING_MODES_DICT['NORMAL'] :
209 EventDispatcher.addEventListener(events.COLOVER, self.handleNormalColumnOver)
210 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
211 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
212
213 elif mode == PLAYING_MODES_DICT['ADVANCED'] :
214 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
215 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
216
217 elif mode == PLAYING_MODES_DICT['EXPERT'] :
218 EventDispatcher.addEventListener(events.COLDOWN, self.handleExpertColumnDown)
219 EventDispatcher.addEventListener(events.COLUP, self.handleExpertColumnUp)
220
221
222 # --- HID listeners ---
223 def handleBeginnerColumnOver(self, event) :
224 col = event.column
225 if col.state and not self.currentNotePlayed :
226 self.playnote(col, event.pos)
227 SongPlayingScreen.setNoteTimeout(
228 int(self.currentNote.duration * \
229 self.quarterNoteDuration)
230 )
231 self.currentNotePlayed = True
232
233 def handleEasyColumnOver(self, event) :
234 col = event.column
235 if col.state and \
236 self.cursor.pressed and \
237 not self.currentNotePlayed :
238 self.playnote(col, event.pos)
239 SongPlayingScreen.setNoteTimeout(
240 int(self.currentNote.duration * \
241 self.quarterNoteDuration)
242 )
243 self.currentNotePlayed = True
244
245
246 def handleNormalColumnOver(self, event) :
247 col = event.column
248 if col.state and \
249 self.cursor.pressed and \
250 not self.currentNotePlayed :
251 self.playnote(col, event.pos)
252 self.currentNotePlayed = True
253
254 def handleColumnDown(self, event) :
255 col = event.column
256 if col.state:
257 self.playnote(col, event.pos)
258 self.currentNotePlayed = True
259
260 def handleEasyColumnDown(self, event) :
261 col = event.column
262 if col.state and \
263 not self.currentNotePlayed :
264 self.playnote(col, event.pos)
265 SongPlayingScreen.setNoteTimeout(
266 int(self.currentNote.duration * \
267 self.quarterNoteDuration)
268 )
269 self.currentNotePlayed = True
270
271
272 def handleExpertColumnDown(self, event) :
273 col = event.column
274 if col.state :
275 self.playnote(col, event.pos)
276 self.currentNotePlayed = True
277 else :
278 vel = self.getVelocity(event.pos) * MIDI_VELOCITY_WRONG_NOTE_ATTN
279 vel = int(vel)
280 self.playnote(col, event.pos, vel=vel)
281 self.alternateColumn = col
282 self.currentNotePlayed = False
283
284 def handleColumnUp(self, event) :
285 if self.currentNotePlayed :
286 self.synth.noteoff(0, self.currentColumn.tone.midi)
287 self.displayNext()
288
289 def handleExpertColumnUp(self, event) :
290 if self.currentNotePlayed :
291 self.synth.noteoff(0, self.currentColumn.tone.midi)
292 self.displayNext()
293 else :
294 self.synth.noteoff(0, self.alternateColumn.tone.midi)
295
296 # --- End HID listeners ---
297
298
299 def displayNext(self, event=None) :
300 if self.currentColumn:
301 self.currentColumn.update(False)
302 try :
303 note, verseIndex = self.noteIterator.next()
304 except StopIteration :
305 self.noteIterator = self.song.iterNotes()
306 note, verseIndex = self.noteIterator.next()
307 eventLogger.info(pygame.event.Event(events.SONGEND))
308 try :
309 syllabus = note.lyrics[verseIndex].syllabus()
310 except IndexError :
311 syllabus = u'…'
312
313 column = self.columns[note.midi]
314 column.update(True, syllabus)
315 self.currentColumn = column
316 self.currentNote = note
317 self.currentNotePlayed = False
318
319 @event_handler(events.NOTEEND)
320 def clearTimeOutAndDisplayNext(self, evt) :
321 pygame.time.set_timer(evt.type, 0)
322 self.synth.noteoff(0, self.currentNote.midi)
323 self.displayNext()
324
325 @staticmethod
326 def setNoteTimeout(delay) :
327 pygame.time.set_timer(events.NOTEEND, delay)
328
329 def stop(self) :
330 pygame.time.set_timer(events.NOTEEND, 0)
331 super(SongPlayingScreen, self).stop()
332
333