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