Finitions et ajout du tempo.
[minwii.git] / src / minwii / widgets / instrumentselector.py
1 # -*- coding: utf-8 -*-
2 """
3 Écran de sélection de l'instrument
4
5 $Id$
6 $URL$
7 """
8 import os.path
9 import pygame
10 from minwii.eventutils import event_handler, EventDispatcher, EventHandlerMixin
11 from minwii.config import FRAMERATE
12 from minwii.config import INSTRUMENTS
13 from minwii.globals import BACKGROUND_LAYER
14 from minwii.globals import FOREGROUND_LAYER
15 from minwii.globals import CURSOR_LAYER
16 from minwii.globals import hls_to_rgba_8bits
17 from cursors import WarpingCursor
18
19
20 class InstrumentSelector(pygame.sprite.LayeredDirty, EventHandlerMixin) :
21
22 rows = 3
23 cols = 3
24 instruments = INSTRUMENTS
25
26 def __init__(self) :
27 super(InstrumentSelector, self).__init__()
28 #self._initRects()
29 self._initTiles()
30 self._initCursor()
31 self._inflatedTile = None
32 self.selectedInstrument = None
33
34 def _initTiles(self) :
35 screen = pygame.display.get_surface()
36 tileWidth = int(round(float(screen.get_width()) / self.cols))
37 tileHeight = int(round(float(screen.get_height()) / self.rows))
38
39 self.tiles = []
40 instrus = list(self.instruments[:])
41 for y in range(self.cols) :
42 for x in range(self.rows) :
43 upperLeftCorner = (x * tileWidth, y * tileHeight)
44 rect = pygame.Rect(upperLeftCorner, (tileWidth, tileHeight))
45 # !!! s'il y avait plus de 3x3 tuiles !!!, il faudrait alors
46 # changer le tuple (x,y) qui concerne le point d'application de l'homotétie.
47 # Cf. InstrumentTile.inflate
48 tile = InstrumentTile(instrus.pop(0), self, rect, (x,y))
49 self.add(tile, layer=BACKGROUND_LAYER)
50 self.tiles.append(tile)
51
52 def _initCursor(self) :
53 self.cursor = WarpingCursor(blinkMode=True)
54 self.add(self.cursor, layer=CURSOR_LAYER)
55
56
57 def run(self):
58 self._running = True
59 clock = pygame.time.Clock()
60 pygame.display.flip()
61 pygame.mouse.set_visible(False)
62 while self._running :
63 EventDispatcher.dispatchEvents()
64 dirty = self.draw(pygame.display.get_surface())
65 pygame.display.update(dirty)
66 clock.tick(FRAMERATE)
67
68 def stop(self) :
69 self._running = False
70 pygame.mouse.set_visible(True)
71 self.cursor._stopBlink()
72
73 @event_handler(pygame.KEYDOWN)
74 def handleKeyDown(self, event) :
75 if event.key == pygame.K_q:
76 self.stop()
77
78 @event_handler(pygame.MOUSEMOTION)
79 def onMouseMove(self, event) :
80 for tile in reversed(self.sprites()[:-1]) :
81 if tile.rect.collidepoint(*event.pos) :
82 self.raiseTileOver(tile)
83 break
84
85 def raiseTileOver(self, tile) :
86 if not tile.inflated :
87 self.change_layer(tile, FOREGROUND_LAYER)
88 tile.inflate(tile.coords)
89
90 if self._inflatedTile :
91 self._inflatedTile.deflate()
92 self.change_layer(self._inflatedTile, BACKGROUND_LAYER)
93
94 self._inflatedTile = tile
95
96 @event_handler(pygame.MOUSEBUTTONDOWN)
97 def selectInstrument(self, event) :
98 for tile in reversed(self.sprites()[:-1]) :
99 if tile.rect.collidepoint(*event.pos) :
100 self.selectedInstrument = tile.instrumentDescription
101 self.stop()
102 break
103
104
105
106 class InstrumentTile(pygame.sprite.DirtySprite) :
107
108 @staticmethod
109 def _get_instrument_image(name) :
110 imagePath = os.path.abspath(__file__).split(os.path.sep)[:-1]
111 imagePath.extend(['data', 'instruments'])
112 name, ext = os.path.splitext(name)
113 imagePath.append('%s%s' % (name, ext or '.jpg'))
114 return os.path.sep.join(imagePath)
115
116 BORDER = 10
117 INFLATE_ZOOM = 0.4
118
119 def __init__(self, instrumentDescription, group, rect, coords) :
120 pygame.sprite.DirtySprite.__init__(self, group)
121 self.inflated = False
122 self.instrumentDescription = instrumentDescription
123 self.rect = rect
124 self._baseRect = rect.copy()
125 self.coords = coords
126 imagePath = InstrumentTile._get_instrument_image(instrumentDescription['name'])
127 self._img = pygame.image.load(imagePath)
128 self.update()
129
130
131 def update(self) :
132 innerWidth, innerHeight = [l-self.BORDER*2 for l in self.rect.size]
133 innerSize = innerWidth, innerHeight
134
135 border = pygame.Surface(self.rect.size)
136 border.fill((0xdd,0xdd,0xdd,255))
137
138 bg = pygame.Surface(innerSize)
139 bg.fill((255,255,255,255))
140 bgRect = pygame.Rect((self.BORDER, self.BORDER), innerSize)
141
142 img = self._img
143 iWidth, iHeight = img.get_size()
144 imgRatio = float(iWidth) / iHeight
145
146 # adapts dimensions
147 iw = innerWidth
148 ih = int(round(innerWidth / imgRatio))
149
150 if ih > innerHeight:
151 ih = innerHeight
152 iw = int(round(innerHeight * imgRatio))
153
154 imgPosition = ((innerWidth - iw) / 2, (innerHeight - ih) / 2)
155 imgRect = pygame.Rect(imgPosition, (iw, ih))
156 img = pygame.transform.smoothscale(img, (iw, ih))
157
158 bg.blit(img, imgRect)
159 border.blit(bg, bgRect)
160 self.image = border
161
162
163 def inflate(self, refPoint) :
164 self.inflated = True
165 keep = {}
166 for name in REF_POINTS[refPoint] :
167 keep[name] = getattr(self.rect, name)
168
169 self.rect.inflate_ip(*[l*self.INFLATE_ZOOM for l in self.rect.size])
170
171 for k, v in keep.items() :
172 setattr(self.rect, k, v)
173
174 self.update()
175 self.dirty = 1
176
177
178 def deflate(self) :
179 self.inflated = False
180 self.rect = self._baseRect.copy()
181 self.update()
182 self.dirty = 1
183
184
185
186 REF_POINTS = {
187 (0, 0) : ['top', 'left'],
188 (1, 0) : ['top'],
189 (2, 0) : ['top', 'right'],
190
191 (0, 1) : ['left'],
192 (1, 1) : [],
193 (2, 1) : ['right'],
194
195 (0, 2) : ['bottom', 'left'],
196 (1, 2) : ['bottom'],
197 (2, 2) : ['bottom', 'right']
198 }