Amélioration ld.
[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 in (pygame.K_q, pygame.K_ESCAPE) or \
76 event.unicode == u'q' :
77 self.stop()
78
79 @event_handler(pygame.MOUSEMOTION)
80 def onMouseMove(self, event) :
81 for tile in reversed(self.sprites()[:-1]) :
82 if tile.rect.collidepoint(*event.pos) :
83 self.raiseTileOver(tile)
84 break
85
86 def raiseTileOver(self, tile) :
87 if not tile.inflated :
88 self.change_layer(tile, FOREGROUND_LAYER)
89 tile.inflate(tile.coords)
90
91 if self._inflatedTile :
92 self._inflatedTile.deflate()
93 self.change_layer(self._inflatedTile, BACKGROUND_LAYER)
94
95 self._inflatedTile = tile
96
97 @event_handler(pygame.MOUSEBUTTONDOWN)
98 def selectInstrument(self, event) :
99 for tile in reversed(self.sprites()[:-1]) :
100 if tile.rect.collidepoint(*event.pos) :
101 self.selectedInstrument = tile.instrumentDescription
102 self.stop()
103 break
104
105
106
107 class InstrumentTile(pygame.sprite.DirtySprite) :
108
109 @staticmethod
110 def _get_instrument_image(name) :
111 imagePath = os.path.abspath(__file__).split(os.path.sep)[:-1]
112 imagePath.extend(['data', 'instruments'])
113 name, ext = os.path.splitext(name)
114 imagePath.append('%s%s' % (name, ext or '.jpg'))
115 return os.path.sep.join(imagePath)
116
117 BORDER = 10
118 INFLATE_ZOOM = 0.4
119
120 def __init__(self, instrumentDescription, group, rect, coords) :
121 pygame.sprite.DirtySprite.__init__(self, group)
122 self.inflated = False
123 self.instrumentDescription = instrumentDescription
124 self.rect = rect
125 self._baseRect = rect.copy()
126 self.coords = coords
127 imagePath = InstrumentTile._get_instrument_image(instrumentDescription['name'])
128 self._img = pygame.image.load(imagePath)
129 self.update()
130
131
132 def update(self) :
133 innerWidth, innerHeight = [l-self.BORDER*2 for l in self.rect.size]
134 innerSize = innerWidth, innerHeight
135
136 border = pygame.Surface(self.rect.size)
137 border.fill((0xdd,0xdd,0xdd,255))
138
139 bg = pygame.Surface(innerSize)
140 bg.fill((255,255,255,255))
141 bgRect = pygame.Rect((self.BORDER, self.BORDER), innerSize)
142
143 img = self._img
144 iWidth, iHeight = img.get_size()
145 imgRatio = float(iWidth) / iHeight
146
147 # adapts dimensions
148 iw = innerWidth
149 ih = int(round(innerWidth / imgRatio))
150
151 if ih > innerHeight:
152 ih = innerHeight
153 iw = int(round(innerHeight * imgRatio))
154
155 imgPosition = ((innerWidth - iw) / 2, (innerHeight - ih) / 2)
156 imgRect = pygame.Rect(imgPosition, (iw, ih))
157 img = pygame.transform.smoothscale(img, (iw, ih))
158
159 bg.blit(img, imgRect)
160 border.blit(bg, bgRect)
161 self.image = border
162
163
164 def inflate(self, refPoint) :
165 self.inflated = True
166 keep = {}
167 for name in REF_POINTS[refPoint] :
168 keep[name] = getattr(self.rect, name)
169
170 self.rect.inflate_ip(*[l*self.INFLATE_ZOOM for l in self.rect.size])
171
172 for k, v in keep.items() :
173 setattr(self.rect, k, v)
174
175 self.update()
176 self.dirty = 1
177
178
179 def deflate(self) :
180 self.inflated = False
181 self.rect = self._baseRect.copy()
182 self.update()
183 self.dirty = 1
184
185
186
187 REF_POINTS = {
188 (0, 0) : ['top', 'left'],
189 (1, 0) : ['top'],
190 (2, 0) : ['top', 'right'],
191
192 (0, 1) : ['left'],
193 (1, 1) : [],
194 (2, 1) : ['right'],
195
196 (0, 2) : ['bottom', 'left'],
197 (1, 2) : ['bottom'],
198 (2, 2) : ['bottom', 'right']
199 }