Clignotement du curseur basé sur un thread indépendant de pygame.
[minwii.git] / src / app / 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 from cursors import WarpingCursor
11 from column import Column
12 import events
13 from eventutils import event_handler, EventDispatcher, EventHandlerMixin
14 import types
15 from musicxml import Tone
16
17 from config import FRAMERATE
18 from config import FIRST_HUE
19 from config import MIDI_VELOCITY_RANGE
20 from config import MIDI_PAN_RANGE
21
22 from globals import BACKGROUND_LAYER
23 from globals import CURSOR_LAYER
24 from globals import PLAYING_MODES_DICT
25
26 class PlayingScreenBase(pygame.sprite.LayeredDirty, EventHandlerMixin) :
27
28 def __init__(self, synth, distinctNotes=[]) :
29 """
30 distinctNotes : notes disctinctes présentes dans la chanson
31 triées du plus grave au plus aigu.
32 """
33 super(PlayingScreenBase, self).__init__()
34 self.synth = synth
35 self.distinctNotes = distinctNotes
36 self.keyboardLength = 0
37 self.keyboardRects = []
38 self.cursor = None
39 self._initRects()
40 self.columns = {}
41 self._initColumns()
42 self._running = False
43 self.draw(pygame.display.get_surface())
44 self._initCursor()
45
46 def _initRects(self) :
47 """ création des espaces réservés pour
48 afficher les colonnes.
49 """
50 self.keyboardLength = len(self.distinctNotes)
51
52 screen = pygame.display.get_surface()
53
54 self.dispWidth = dispWidth = screen.get_width()
55 self.dispHeight = dispHeight = screen.get_height()
56
57 columnWidth = int(round(float(dispWidth) / self.keyboardLength))
58
59 rects = []
60 for i in range(self.keyboardLength) :
61 upperLeftCorner = (i*columnWidth, 0)
62 rect = pygame.Rect(upperLeftCorner, (columnWidth, dispHeight))
63 rects.append(rect)
64
65 self.keyboardRects = rects
66
67 def _initColumns(self) :
68
69 hueStep = FIRST_HUE / (self.keyboardLength - 1)
70 for i, rect in enumerate(self.keyboardRects) :
71 hue = FIRST_HUE - hueStep * i
72 tone = self.distinctNotes[i]
73 c = Column(self, i, hue, rect, tone)
74 self.add(c, layer=BACKGROUND_LAYER)
75 self.columns[tone.midi] = c
76
77
78 def _initCursor(self) :
79 self.cursor = WarpingCursor(blinkMode=True)
80 self.add(self.cursor, layer=CURSOR_LAYER)
81
82 def run(self):
83 self._running = True
84 clock = pygame.time.Clock()
85 pygame.display.flip()
86 pygame.mouse.set_visible(False)
87 while self._running :
88 EventDispatcher.dispatchEvents()
89 dirty = self.draw(pygame.display.get_surface())
90 pygame.display.update(dirty)
91 clock.tick(FRAMERATE)
92
93 def stop(self) :
94 self._running = False
95 self.synth.system_reset()
96 pygame.mouse.set_visible(True)
97 self.cursor._stopBlink()
98
99 @event_handler(pygame.KEYDOWN)
100 def handleKeyDown(self, event) :
101 if event.key == pygame.K_q:
102 self.stop()
103
104 @event_handler(pygame.MOUSEBUTTONDOWN)
105 def onMouseDown(self, event) :
106 # TODO à cleaner : on vire le dernier élément
107 # parce qu'il s'agit du curseur
108 for col in reversed(self.sprites()[:-1]) :
109 if col.rect.collidepoint(*event.pos):
110 self.raiseColDown(col, event.pos)
111 break
112
113 @event_handler(pygame.MOUSEBUTTONUP)
114 def onMouseUp(self, event) :
115 for col in reversed(self.sprites()[:-1]) :
116 if col.rect.collidepoint(*event.pos) :
117 self.raiseColUp(col, event.pos)
118 break
119
120 @event_handler(pygame.MOUSEMOTION)
121 def onMouseMove(self, event) :
122 for col in reversed(self.sprites()[:-1]) :
123 if col.rect.collidepoint(*event.pos) :
124 self.raiseColOver(col, event.pos)
125 break
126
127 def raiseColDown(self, col, pos) :
128 evt = pygame.event.Event(events.COLDOWN, column=col, pos=pos)
129 pygame.event.post(evt)
130
131 def raiseColUp(self, col, pos) :
132 evt = pygame.event.Event(events.COLUP, column=col, pos=pos)
133 pygame.event.post(evt)
134
135 def raiseColOver(self, col, pos) :
136 evt = pygame.event.Event(events.COLOVER, column=col, pos=pos)
137 pygame.event.post(evt)
138
139 def getVelocity(self, pos) :
140 vel = (float(self.dispWidth) - pos[1]) / self.dispWidth
141 vel = int(vel * (MIDI_VELOCITY_RANGE[1] - MIDI_VELOCITY_RANGE[0])) + MIDI_VELOCITY_RANGE[0]
142 return vel
143
144 def getPan(self, index) :
145 pan = float(index) / (self.keyboardLength -1)
146 pan = int(pan * (MIDI_PAN_RANGE[1] - MIDI_PAN_RANGE[0])) + MIDI_PAN_RANGE[0]
147 return pan
148
149
150 class PlayingScreen(PlayingScreenBase) :
151 "fenêtre de jeu pour improvisation"
152
153 scale = [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
154
155 def __init__(self, synth) :
156 distinctNotes = []
157 for midi in self.scale :
158 tone = Tone(midi)
159 distinctNotes.append(tone)
160
161 super(PlayingScreen, self).__init__(synth, distinctNotes)
162
163 @event_handler(events.NOTEON)
164 def noteon(self, evt) :
165 tone = evt.tone
166 self.synth.noteon(0, tone.midi, 96)
167
168 @event_handler(events.NOTEOFF)
169 def noteoff(self, evt) :
170 tone = evt.tone
171 self.synth.noteoff(0, tone.midi)
172
173
174 class SongPlayingScreen(PlayingScreenBase) :
175
176 def __init__(self, synth, song, mode=PLAYING_MODES_DICT['EASY']) :
177 super(SongPlayingScreen, self).__init__(synth, song.distinctNotes)
178 self.song = song
179 self.quarterNoteDuration = song.quarterNoteDuration
180 self.currentColumn = None
181 self.noteIterator = self.song.iterNotes()
182 self.displayNext()
183 if mode == PLAYING_MODES_DICT['NORMAL'] :
184 EventDispatcher.addEventListener(events.COLDOWN, self.handleColumnDown)
185 EventDispatcher.addEventListener(events.COLUP, self.handleColumnUp)
186 elif mode == PLAYING_MODES_DICT['EASY'] :
187 EventDispatcher.addEventListener(events.COLOVER, self.handleColumnOver)
188
189
190 def displayNext(self, event=None) :
191 if self.currentColumn:
192 self.currentColumn.update(False)
193 note, verseIndex = self.noteIterator.next()
194 syllabus = note.lyrics[verseIndex].syllabus()
195 column = self.columns[note.midi]
196 column.update(True, syllabus)
197 self.currentColumn = column
198 self.currentNote = note
199 self.currentNotePlayed = False
200
201 def handleColumnDown(self, event) :
202 col = event.column
203 if col.state:
204 pan = self.getPan(col.index)
205 self.synth.cc(0, 10, pan)
206 vel = self.getVelocity(event.pos)
207 self.synth.noteon(0, col.tone.midi, vel)
208 self.currentNotePlayed = True
209
210 def handleColumnUp(self, event) :
211 if self.currentNotePlayed :
212 self.synth.noteoff(0, self.currentColumn.tone.midi)
213 self.displayNext()
214
215 def handleColumnOver(self, event) :
216 col = event.column
217 if col.state and not self.currentNotePlayed :
218 pan = self.getPan(col.index)
219 self.synth.cc(0, 10, pan)
220 vel = self.getVelocity(event.pos)
221 self.synth.noteon(0, col.tone.midi, vel)
222 SongPlayingScreen.setNoteTimeout(
223 int(self.currentNote.duration * \
224 self.quarterNoteDuration)
225 )
226 self.currentNotePlayed = True
227
228 @event_handler(events.NOTEEND)
229 def clearTimeOutAndDisplayNext(self, evt) :
230 pygame.time.set_timer(evt.type, 0)
231 self.synth.noteoff(0, self.currentNote.midi)
232 self.displayNext()
233
234 @staticmethod
235 def setNoteTimeout(delay) :
236 pygame.time.set_timer(events.NOTEEND, delay)
237
238 def stop(self) :
239 pygame.time.set_timer(events.NOTEEND, 0)
240 super(SongPlayingScreen, self).stop()
241
242