Back to index

freevial  1.2
events.py
Go to the documentation of this file.
00001 # -*- coding: utf-8 -*-
00002 
00003 #
00004 # Freevial
00005 # Common event-related classes and functions
00006 #
00007 # Copyright (C) 2007, 2008 The Freevial Team
00008 #
00009 # By Carles Oriol i Margarit <carles@kumbaworld.com>
00010 # By Siegfried-Angel Gevatter Pujals <siggi.gevatter@gmail.com>
00011 #
00012 # This program is free software: you can redistribute it and/or modify
00013 # it under the terms of the GNU General Public License as published by
00014 # the Free Software Foundation, either version 3 of the License, or
00015 # (at your option) any later version.
00016 #
00017 # This program is distributed in the hope that it will be useful,
00018 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00019 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00020 # GNU General Public License for more details.
00021 #
00022 # You should have received a copy of the GNU General Public License
00023 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
00024 #
00025 
00026 import sys
00027 import re
00028 import pygame
00029 
00030 from freevialglob import screenshot
00031 
00032 
00033 mouseButtons = {
00034               'primary': 1,
00035               'secondary': 2,
00036               'middle': 3,
00037        }
00038 
00039 class EventHandle:
00040        
00041        global mouseButtons
00042        
00043        
00044        def __init__( self, event, do_base_actions = True ):
00045               
00046               if event.type == pygame.JOYBUTTONDOWN:
00047                      event = self._convert_joystick_event()
00048               
00049               self.event = event
00050               self.handled = False
00051               
00052               if do_base_actions and self.base_actions():
00053                      self.handled = True
00054        
00055        
00056        def _convert_joystick_event( self ):
00057               
00058               # Aliases for PS2 remotes
00059               joystick_aliases = {
00060                      0: K_RETURN,
00061                      1: K_ESCAPE,
00062                      2: K_RETURN,
00063                      3: K_s,
00064                      4: K_F2,
00065                      5: K_a,
00066                      6: K_F1,
00067                      7: K_F3,      
00068                      8: K_SPACE,
00069                      9: K_ESCAPE,
00070                      12: K_UP,
00071                      13: K_RIGHT,
00072                      14: K_DOWN,
00073                      15: K_LEFT,
00074               }
00075        
00076               if joystick_aliases.get( event.button ):
00077                      return pygame.event.Event( pygame.KEYUP, { 'key': joystick_aliases[ event.button ], 'unicode': u's', 'mod': 0 } )
00078        
00079        
00080        def _getKey( self, key ):
00081               
00082               if type(key) is str:
00083                      
00084                      if key[:2] != 'K_':
00085                             key = 'K_' + key
00086                      
00087                      key = getattr(pygame, key)
00088               
00089               return key
00090        
00091        
00092        def _isKeyEvent( self ):
00093               
00094               return True if hasattr(self.event, 'key') else False
00095        
00096        
00097        def _isStateEvent( self ):
00098               
00099               return True if hasattr(self.event, 'state') else False
00100        
00101        
00102        def _hasKey( self, keynames ):
00103               
00104               if not self._isKeyEvent():
00105                      return False
00106               
00107               if len(keynames) == 1 and type(keynames[0]) is tuple:
00108                      keynames = keynames[0]
00109               
00110               for key in keynames:
00111                      
00112                      if self.event.key == self._getKey(key):
00113                             return True
00114               
00115               return False
00116        
00117        
00118        def isKey( self, *keynames ):
00119               
00120               return True if self._hasKey(keynames) else False
00121        
00122        
00123        def isUp( self ):
00124               
00125               return True if self.event.type == pygame.KEYUP else False
00126        
00127        
00128        def isDown( self ):
00129               
00130               return True if self.event.type == pygame.KEYDOWN else False
00131        
00132        
00133        def isClick( self, request = 0 ):
00134               
00135               if type(request) is not int:
00136                      request = mouseButtons[ request ]
00137               
00138               return True if self.event.type == pygame.MOUSEBUTTONDOWN and (self.event.button == request or request == 0) else False
00139        
00140        
00141        def isRelease( self, request = 0 ):
00142               
00143               if type(request) is not int:
00144                      request = mouseButtons[ request ]
00145               
00146               return True if self.event.type == pygame.MOUSEBUTTONUP and (self.event.button == request or request == 0) else False
00147               
00148        
00149        def keyUp( self, *keynames ):
00150               
00151               if not self.isUp():
00152                      return False
00153               
00154               if len(keynames) == 0:
00155                      return True
00156               
00157               return self.isKey(*keynames)
00158        
00159        
00160        def keyDown( self, *keynames ):
00161               
00162               if not self.isDown():
00163                      return False
00164               
00165               if len(keynames) == 0:
00166                      return True
00167               
00168               return self.isKey(keynames)
00169        
00170        
00171        def isWindowMinimize( self ):
00172               
00173               if self._isStateEvent() and self.event.state == 6 and self.event.gain == 0:
00174                      return True
00175               
00176               return False
00177        
00178        
00179        def isWindowRestore( self ):
00180               
00181               if self._isStateEvent() and self.event.state == 4 and self.event.gain == 1:
00182                      return True
00183               
00184               return False
00185        
00186        def isWindowFocusLose( self ):
00187               
00188               if self._isStateEvent() and self.event.state == 1 and self.event.gain == 0:
00189                      return True
00190               
00191               return False
00192        
00193        def isWindowFocusGain( self ):
00194               
00195               if self._isStateEvent() and self.event.state == 1 and self.event.gain == 1:
00196                      return True
00197        
00198        def isQuit( self ):
00199               
00200               if self.event.type == pygame.QUIT:
00201                      return True
00202               
00203               return False
00204        
00205        
00206        def str( self ):
00207               
00208               if not self._isKeyEvent():
00209                      return ''
00210               
00211               return printKey(self.event.key)
00212        
00213        
00214        def base_actions( self ):
00215               
00216               if self.isQuit():
00217                      sys.exit()
00218               
00219               elif self.keyDown('PRINT'):
00220                      screenshot(pygame.display.get_surface())
00221                      return True
00222               
00223               elif self.isWindowFocusLose() or self.isWindowFocusGain():
00224                      # Those aren't interesting, skip them.
00225                      # We could also do some CPU saving here, but this would produce
00226                      # bad synchronization between the music and the images.
00227                      return True
00228               
00229               elif self.keyUp('F11'):
00230                      pygame.display.toggle_fullscreen()
00231                      return True
00232               
00233               elif self.isWindowMinimize():
00234                      pauseGameUntilRestore()
00235                      return True
00236               
00237               else:
00238                      return False
00239 
00240 
00241 def waitForMouseRelease( ):
00242 
00243        while pygame.mouse.get_pressed()[0] + pygame.mouse.get_pressed()[1] + pygame.mouse.get_pressed()[2] != 0:
00244               pygame.event.wait() 
00245 
00246 
00247 def pauseGameUntilRestore( ):
00248        
00249        while True:
00250               for event in pygame.event.get():
00251                      if EventHandle(event).isWindowRestore():
00252                             return False
00253               
00254               # Sleep for 10 milliseconds.
00255               # This has no visible effect but will drastically reduce CPU usage.
00256               pygame.time.wait(10)
00257 
00258 
00259 aobert = atancat = adieresi = acirc = False
00260 accents = [u"aeiou", u"àèìòù", u"áéíóú", u"äëïöü", u"âêîôû" ]
00261 
00262 def printKey( tecla ):
00263        """ Translates a pygame Key object for on-game printing of it's value. """
00264 
00265        global aobert, atancat, adieresi, acirc, accents
00266        
00267        keyname = pygame.key.name(tecla)
00268        
00269        if keyname == 'space': 
00270               return ' '
00271        
00272        if keyname == 'world 71':
00273               return u'ç'
00274        
00275        if keyname == 'tab':
00276               return '    '
00277        
00278        if len(keyname) == 3 and keyname[:1] == '[' and keyname[2:] == ']':
00279               keyname = keyname[1:2]
00280        
00281        pos = accents[0].find( keyname )
00282        if pos != -1:
00283               if aobert: keyname = accents[1][pos]
00284               if atancat: keyname = accents[2][pos]
00285               if adieresi: keyname = accents[3][pos]
00286               if acirc: keyname = accents[4][pos]
00287        
00288        if pygame.key.get_mods() & pygame.KMOD_SHIFT:
00289               keyname = keyname.upper()
00290        
00291        if tecla == 314:
00292               if pygame.key.get_mods() & pygame.KMOD_SHIFT:
00293                      atancat = True
00294               elif pygame.key.get_mods() & pygame.KMOD_CTRL:
00295                      adieresi = True
00296               elif pygame.key.get_mods() & pygame.KMOD_ALT:
00297                      acirc = True
00298               else:
00299                      aobert = True
00300        else:
00301               aobert = atancat = adieresi = acirc = False
00302        
00303        if not re.search(u"^[a-zA-Z0-9,.+'-/*àèìòùáéíóúäëïöüâêîôû ]$", keyname):
00304               return ''
00305        
00306        return keyname