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