92966462b5612a47bd378daf84445a16b84bf334
[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 a 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']) :
195 super(SongPlayingScreen, self).__init__(synth, song.distinctNotes)
196 self.song = song
197 self.quarterNoteDuration = song.quarterNoteDuration
198 self.currentColumn = None
199 self.noteIterator = self.song.iterNotes()
200 self.displayNext()
201 self._plugListeners(mode)
202
203 def _plugListeners(self, mode) :
204 "initialisation des gestionnaires d'événements en fonction du mode"
205
206 if mode == PLAYING_MODES_DICT['BEGINNER'] :
207 EventDispatcher.addEventListener(events.COLOVER, self.handleBeginnerColumnOver)
208
209 elif mode == PLAYING_MODES_DICT['EASY'] :
210 EventDispatcher.addEventListener(events.COLDOWN, self.handleEasyColumnDown)
211 EventDispatcher.addEventListener(events.COLOVER, self.handleEasyColumnOver)
212
213 elif mode == PLAYING_MODES_DICT['NORMAL'] :
214 EventDispatcher.addEventListener(events.COLOVER, self.handleNormalColumnOver)
215 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
216 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
217
218 elif mode == PLAYING_MODES_DICT['ADVANCED'] :
219 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
220 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
221
222 elif mode == PLAYING_MODES_DICT['EXPERT'] :
223 EventDispatcher.addEventListener(events.COLDOWN, self.handleExpertColumnDown)
224 EventDispatcher.addEventListener(events.COLUP, self.handleExpertColumnUp)
225
226
227 # --- HID listeners ---
228 def handleBeginnerColumnOver(self, event) :
229 col = event.column
230 if col.state and not self.currentNotePlayed :
231 self.playnote(col, event.pos)
232 SongPlayingScreen.setNoteTimeout(
233 int(self.currentNote.duration * \
234 self.quarterNoteDuration)
235 )
236 self.currentNotePlayed = True
237
238 def handleEasyColumnOver(self, event) :
239 col = event.column
240 if col.state and \
241 self.cursor.pressed and \
242 not self.currentNotePlayed :
243 self.playnote(col, event.pos)
244 SongPlayingScreen.setNoteTimeout(
245 int(self.currentNote.duration * \
246 self.quarterNoteDuration)
247 )
248 self.currentNotePlayed = True
249
250
251 def handleNormalColumnOver(self, event) :
252 col = event.column
253 if col.state and \
254 self.cursor.pressed and \
255 not self.currentNotePlayed :
256 self.playnote(col, event.pos)
257 self.currentNotePlayed = True
258
259 def handleColumnDown(self, event) :
260 col = event.column
261 if col.state:
262 self.playnote(col, event.pos)
263 self.currentNotePlayed = True
264
265 def handleEasyColumnDown(self, event) :
266 col = event.column
267 if col.state and \
268 not self.currentNotePlayed :
269 self.playnote(col, event.pos)
270 SongPlayingScreen.setNoteTimeout(
271 int(self.currentNote.duration * \
272 self.quarterNoteDuration)
273 )
274 self.currentNotePlayed = True
275
276
277 def handleExpertColumnDown(self, event) :
278 col = event.column
279 if col.state :
280 self.playnote(col, event.pos)
281 self.currentNotePlayed = True
282 else :
283 vel = self.getVelocity(event.pos) * MIDI_VELOCITY_WRONG_NOTE_ATTN
284 vel = int(vel)
285 self.playnote(col, event.pos, vel=vel)
286 self.alternateColumn = col
287 self.currentNotePlayed = False
288
289 def handleColumnUp(self, event) :
290 if self.currentNotePlayed :
291 self.synth.noteoff(0, self.currentColumn.tone.midi)
292 self.displayNext()
293
294 def handleExpertColumnUp(self, event) :
295 if self.currentNotePlayed :
296 self.synth.noteoff(0, self.currentColumn.tone.midi)
297 self.displayNext()
298 else :
299 self.synth.noteoff(0, self.alternateColumn.tone.midi)
300
301 # --- End HID listeners ---
302
303
304 def displayNext(self, event=None) :
305 if self.currentColumn:
306 self.currentColumn.update(False)
307 try :
308 note, verseIndex = self.noteIterator.next()
309 except StopIteration :
310 self.noteIterator = self.song.iterNotes()
311 note, verseIndex = self.noteIterator.next()
312 eventLogger.info(pygame.event.Event(events.SONGEND))
313 try :
314 syllabus = note.lyrics[verseIndex].syllabus()
315 except IndexError :
316 syllabus = u'…'
317
318 column = self.columns[note.midi]
319 column.update(True, syllabus)
320 self.currentColumn = column
321 self.currentNote = note
322 self.currentNotePlayed = False
323
324 @event_handler(events.NOTEEND)
325 def clearTimeOutAndDisplayNext(self, evt) :
326 pygame.time.set_timer(evt.type, 0)
327 self.synth.noteoff(0, self.currentNote.midi)
328 self.displayNext()
329
330 @staticmethod
331 def setNoteTimeout(delay) :
332 pygame.time.set_timer(events.NOTEEND, delay)
333
334 def stop(self) :
335 pygame.time.set_timer(events.NOTEEND, 0)
336 super(SongPlayingScreen, self).stop()
337
338