Ouverture par défaut du dossier courant des logs, s'il existe.
[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 event.unicode == u'q':
104 self.stop()
105
106 @event_handler(pygame.MOUSEBUTTONDOWN)
107 def onMouseDown(self, event) :
108 # TODO à cleaner : on vire le dernier élément
109 # parce qu'il s'agit du curseur
110 for col in reversed(self.sprites()[:-1]) :
111 if col.rect.collidepoint(*event.pos):
112 self.raiseColDown(col, event)
113 break
114
115 @event_handler(pygame.MOUSEBUTTONUP)
116 def onMouseUp(self, event) :
117 for col in reversed(self.sprites()[:-1]) :
118 if col.rect.collidepoint(*event.pos) :
119 self.raiseColUp(col, event)
120 break
121
122 @event_handler(pygame.MOUSEMOTION)
123 def onMouseMove(self, event) :
124 for col in reversed(self.sprites()[:-1]) :
125 if col.rect.collidepoint(*event.pos) :
126 self.raiseColOver(col, event)
127 break
128
129 def raiseColDown(self, col, mouseEvent) :
130 evt = pygame.event.Event(events.COLDOWN, column=col, pos=mouseEvent.pos)
131 pygame.event.post(evt)
132
133 def raiseColUp(self, col, mouseEvent) :
134 evt = pygame.event.Event(events.COLUP, column=col, pos=mouseEvent.pos)
135 pygame.event.post(evt)
136
137 def raiseColOver(self, col, mouseEvent) :
138 evt = pygame.event.Event(events.COLOVER, column=col, pos=mouseEvent.pos, mouseEvent=mouseEvent)
139 pygame.event.post(evt)
140
141 def getVelocity(self, pos) :
142 vel = (float(self.dispWidth) - pos[1]) / self.dispWidth
143 vel = int(vel * (MIDI_VELOCITY_RANGE[1] - MIDI_VELOCITY_RANGE[0])) + MIDI_VELOCITY_RANGE[0]
144 return vel
145
146 def getPan(self, index) :
147 pan = float(index) / (self.keyboardLength -1)
148 pan = int(pan * (MIDI_PAN_RANGE[1] - MIDI_PAN_RANGE[0])) + MIDI_PAN_RANGE[0]
149 return pan
150
151 def playnote(self, col, pos, vel=None) :
152 pan = self.getPan(col.index)
153 self.synth.cc(0, 10, pan)
154 vel = vel or self.getVelocity(pos)
155 self.synth.noteon(0, col.tone.midi, vel)
156
157 class PlayingScreen(PlayingScreenBase) :
158 "fenêtre de jeu pour improvisation"
159
160 scale = [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
161
162 def __init__(self, synth) :
163 distinctNotes = []
164 for midi in self.scale :
165 tone = Tone(midi)
166 distinctNotes.append(tone)
167
168 super(PlayingScreen, self).__init__(synth, distinctNotes)
169
170 @event_handler(events.NOTEON)
171 def noteon(self, evt) :
172 tone = evt.tone
173 self.synth.noteon(0, tone.midi, 96)
174
175 @event_handler(events.NOTEOFF)
176 def noteoff(self, evt) :
177 tone = evt.tone
178 self.synth.noteoff(0, tone.midi)
179
180
181 class SongPlayingScreen(PlayingScreenBase) :
182
183 def __init__(self, synth, song, mode=PLAYING_MODES_DICT['NORMAL']) :
184 super(SongPlayingScreen, self).__init__(synth, song.distinctNotes)
185 self.song = song
186 self.quarterNoteDuration = song.quarterNoteDuration
187 self.currentColumn = None
188 self.noteIterator = self.song.iterNotes()
189 self.displayNext()
190 self._plugListeners(mode)
191
192 def _plugListeners(self, mode) :
193 "initialisation des gestionnaires d'événements en fonction du mode"
194
195 if mode == PLAYING_MODES_DICT['BEGINNER'] :
196 EventDispatcher.addEventListener(events.COLOVER, self.handleBeginnerColumnOver)
197
198 elif mode == PLAYING_MODES_DICT['EASY'] :
199 EventDispatcher.addEventListener(events.COLDOWN, self.handleEasyColumnDown)
200 EventDispatcher.addEventListener(events.COLOVER, self.handleEasyColumnOver)
201
202 elif mode == PLAYING_MODES_DICT['NORMAL'] :
203 EventDispatcher.addEventListener(events.COLOVER, self.handleNormalColumnOver)
204 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
205 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
206
207 elif mode == PLAYING_MODES_DICT['ADVANCED'] :
208 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
209 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
210
211 elif mode == PLAYING_MODES_DICT['EXPERT'] :
212 EventDispatcher.addEventListener(events.COLDOWN, self.handleExpertColumnDown)
213 EventDispatcher.addEventListener(events.COLUP, self.handleExpertColumnUp)
214
215
216 # --- HID listeners ---
217 def handleBeginnerColumnOver(self, event) :
218 col = event.column
219 if col.state and not self.currentNotePlayed :
220 self.playnote(col, event.pos)
221 SongPlayingScreen.setNoteTimeout(
222 int(self.currentNote.duration * \
223 self.quarterNoteDuration)
224 )
225 self.currentNotePlayed = True
226
227 def handleEasyColumnOver(self, event) :
228 col = event.column
229 if col.state and \
230 any(event.mouseEvent.buttons) and \
231 not self.currentNotePlayed :
232 self.playnote(col, event.pos)
233 SongPlayingScreen.setNoteTimeout(
234 int(self.currentNote.duration * \
235 self.quarterNoteDuration)
236 )
237 self.currentNotePlayed = True
238
239
240 def handleNormalColumnOver(self, event) :
241 col = event.column
242 if col.state and \
243 any(event.mouseEvent.buttons) and \
244 not self.currentNotePlayed :
245 self.playnote(col, event.pos)
246 self.currentNotePlayed = True
247
248 def handleColumnDown(self, event) :
249 col = event.column
250 if col.state:
251 self.playnote(col, event.pos)
252 self.currentNotePlayed = True
253
254 def handleEasyColumnDown(self, event) :
255 col = event.column
256 if col.state and \
257 not self.currentNotePlayed :
258 self.playnote(col, event.pos)
259 SongPlayingScreen.setNoteTimeout(
260 int(self.currentNote.duration * \
261 self.quarterNoteDuration)
262 )
263 self.currentNotePlayed = True
264
265
266 def handleExpertColumnDown(self, event) :
267 col = event.column
268 if col.state :
269 self.playnote(col, event.pos)
270 self.currentNotePlayed = True
271 else :
272 vel = self.getVelocity(event.pos) * MIDI_VELOCITY_WRONG_NOTE_ATTN
273 vel = int(vel)
274 self.playnote(col, event.pos, vel=vel)
275 self.alternateColumn = col
276 self.currentNotePlayed = False
277
278 def handleColumnUp(self, event) :
279 if self.currentNotePlayed :
280 self.synth.noteoff(0, self.currentColumn.tone.midi)
281 self.displayNext()
282
283 def handleExpertColumnUp(self, event) :
284 if self.currentNotePlayed :
285 self.synth.noteoff(0, self.currentColumn.tone.midi)
286 self.displayNext()
287 else :
288 self.synth.noteoff(0, self.alternateColumn.tone.midi)
289
290 # --- End HID listeners ---
291
292
293 def displayNext(self, event=None) :
294 if self.currentColumn:
295 self.currentColumn.update(False)
296 try :
297 note, verseIndex = self.noteIterator.next()
298 except StopIteration :
299 self.noteIterator = self.song.iterNotes()
300 note, verseIndex = self.noteIterator.next()
301 eventLogger.info(pygame.event.Event(events.SONGEND))
302 try :
303 syllabus = note.lyrics[verseIndex].syllabus()
304 except IndexError :
305 syllabus = u'…'
306
307 column = self.columns[note.midi]
308 column.update(True, syllabus)
309 self.currentColumn = column
310 self.currentNote = note
311 self.currentNotePlayed = False
312
313 @event_handler(events.NOTEEND)
314 def clearTimeOutAndDisplayNext(self, evt) :
315 pygame.time.set_timer(evt.type, 0)
316 self.synth.noteoff(0, self.currentNote.midi)
317 self.displayNext()
318
319 @staticmethod
320 def setNoteTimeout(delay) :
321 pygame.time.set_timer(events.NOTEEND, delay)
322
323 def stop(self) :
324 pygame.time.set_timer(events.NOTEEND, 0)
325 super(SongPlayingScreen, self).stop()
326
327