93152118743e89d964fabc75dc97db03365bf101
[minwii.git] / src / app / widgets / cursors.py
1 # -*- coding: utf-8 -*-
2 """
3 Curseurs winwii
4
5 $Id$
6 $URL$
7 """
8
9 import pygame
10 import os
11 from eventutils import EventHandlerMixin, event_handler
12 from events import TIMEOUT
13 from itertools import cycle
14
15 class WarpingCursor(pygame.sprite.DirtySprite, EventHandlerMixin):
16 '''
17 The class for animating the warping cursor
18 '''
19
20 @staticmethod
21 def _get_theme_images(name) :
22 basePath = os.path.abspath(__file__).split(os.path.sep)[:-1]
23 basePath.append('data')
24 basePath.append(name)
25 basePath = os.path.sep.join(basePath)
26 images = [f for f in os.listdir(basePath) if os.path.splitext(f)[1] == '.png']
27 return basePath, images
28
29
30 def __init__(self, theme='black', duration=50, blinkMode=True):
31 pygame.sprite.DirtySprite.__init__(self)
32 pygame.mouse.set_visible(False)
33 imagesPath, images = WarpingCursor._get_theme_images(theme)
34 flashImage = images.pop(images.index('flash.png'))
35 flashImagePath = os.path.sep.join([imagesPath, flashImage])
36 self.flashImage = pygame.image.load(flashImagePath).convert_alpha()
37 images.sort(lambda a, b : cmp(*[int(os.path.splitext(f)[0]) for f in [a, b]]))
38
39 self.images = []
40 for img in images :
41 imagePath = os.path.sep.join([imagesPath, img])
42 img = pygame.image.load(imagePath).convert_alpha()
43 self.images.append(img)
44
45 # assumes that all images have same dimensions
46 self.width = self.images[0].get_width()
47 self.height = self.images[0].get_height()
48 self.duration = duration
49
50 self.image = self.images[0]
51 self.rect = pygame.Rect((-self.width/2,-self.height/2), (self.width, self.height))
52
53 self.blinkMode = blinkMode
54 self._startBlink()
55
56 def _startBlink(self) :
57 if self.blinkMode :
58 self._blinking = True
59 pygame.time.set_timer(TIMEOUT, self.duration)
60 self.iterator = self.iterImages()
61
62 def iterImages(self) :
63 for img in cycle(self.images) :
64 yield img
65
66 @event_handler(TIMEOUT)
67 def loadNext(self, event) :
68 if self._blinking :
69 self.dirty = 1
70 self.image = self.iterator.next()
71
72 @event_handler(pygame.MOUSEBUTTONDOWN)
73 def flashOn(self, event) :
74 self.dirty = 1
75 self._blinking = False
76 self.image = self.flashImage
77
78 @event_handler(pygame.MOUSEBUTTONUP)
79 def flashOff(self, event) :
80 self.dirty = 1
81 if self.blinkMode :
82 self._blinking = True
83 self.loadNext(event)
84 else :
85 self.image = self.images[0]
86
87 @event_handler(pygame.MOUSEMOTION)
88 def move(self, event) :
89 self.dirty = 1
90 self.rect.move_ip(event.rel)