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