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