home *** CD-ROM | disk | FTP | other *** search
/ Hackers Magazine 57 / CdHackersMagazineNr57.iso / Software / Multimedia / k3d-setup-0.7.11.0.exe / lib / site-packages / cgkit / GUI / keys.py < prev    next >
Encoding:
Python Source  |  2007-01-11  |  7.7 KB  |  254 lines

  1. # ***** BEGIN LICENSE BLOCK *****
  2. # Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3. #
  4. # The contents of this file are subject to the Mozilla Public License Version
  5. # 1.1 (the "License"); you may not use this file except in compliance with
  6. # the License. You may obtain a copy of the License at
  7. # http://www.mozilla.org/MPL/
  8. #
  9. # Software distributed under the License is distributed on an "AS IS" basis,
  10. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. # for the specific language governing rights and limitations under the
  12. # License.
  13. #
  14. # The Original Code is the Python Computer Graphics Kit.
  15. #
  16. # The Initial Developer of the Original Code is Matthias Baas.
  17. # Portions created by the Initial Developer are Copyright (C) 2004
  18. # the Initial Developer. All Rights Reserved.
  19. #
  20. # Contributor(s):
  21. #
  22. # Alternatively, the contents of this file may be used under the terms of
  23. # either the GNU General Public License Version 2 or later (the "GPL"), or
  24. # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  25. # in which case the provisions of the GPL or the LGPL are applicable instead
  26. # of those above. If you wish to allow use of your version of this file only
  27. # under the terms of either the GPL or the LGPL, and not to allow others to
  28. # use your version of this file under the terms of the MPL, indicate your
  29. # decision by deleting the provisions above and replace them with the notice
  30. # and other provisions required by the GPL or the LGPL. If you do not delete
  31. # the provisions above, a recipient may use your version of this file under
  32. # the terms of any one of the MPL, the GPL or the LGPL.
  33. #
  34. # ***** END LICENSE BLOCK *****
  35.  
  36. ## \file keys.py
  37. ## Contains the Keys class.
  38.  
  39. import wx
  40. import string
  41.  
  42. # Exceptions:
  43. class InvalidKeyDescription(Exception):
  44.     """Exception class."""
  45.     pass
  46.  
  47. class KeyNotBound(Exception):
  48.     """Exception class."""
  49.     pass
  50.  
  51. # Keys
  52. class Keys(object):
  53.     """This class manages key strokes.
  54.  
  55.     Key bindings correspond to special key attributes. The attribute
  56.     name is the name of the key and the value is a callable object
  57.     that takes no arguments.
  58.  
  59.     Example:
  60.  
  61.     \code
  62.     >>> keys = Keys()
  63.  
  64.     # Bind functions to keys...
  65.     >>> keys.ctrl_c = onExit
  66.     keys.shift_ctrl_tab = onFoo
  67.  
  68.     # Remove a key binding
  69.     >>> del keys.ctrl_c
  70.     
  71.     \endcode
  72.     """
  73.  
  74.     def __init__(self):
  75.  
  76.         # Command dictionary. The keys are the tuples that contain the
  77.         # modifier flags and the key code. The value is a callable object.
  78.         self._commands = {}
  79.         
  80.         # A dictionary that translates wx key codes into a string description
  81.         # The dictionary is built from the WXK_xyz constants
  82.         self._wxkeystrs = {}
  83.         wxkeys = filter(lambda x: x[0:4]=="WXK_", dir(wx))
  84.         for k in wxkeys:
  85.             code = getattr(wx, k)
  86.             self._wxkeystrs[code] = k[4:].capitalize()
  87.  
  88.         # The Window object that uses this key manager
  89.         self._window = None
  90.  
  91.  
  92.     def attach(self, window):
  93.         self._window = window
  94.         wx.EVT_KEY_DOWN(window, self._onKeyDown)
  95. #        wx.EVT_KEY_UP(window, self._onKeyUp)
  96. #        wx.EVT_CHAR(window, self._onChar)
  97.  
  98.     def detach(self):
  99.         pass
  100.  
  101.     def findCommandKeys(self, func):
  102.         """Search the key table for a command and return all associated keys.
  103.  
  104.         \param func (\c callable) The bound function
  105.         \return A list of readable key strings.
  106.         """
  107.  
  108.         res = []
  109.         # Compare all commands...
  110.         for key in self._commands.iterkeys():
  111.             cmd = self._commands[key]
  112.             if func==cmd:
  113.                 res.append(self._cmdkey2text(key))
  114.  
  115.         return res
  116.  
  117.     ######################################################################
  118.     ## protected:
  119.  
  120. #    def __setitem__(self, name, value):
  121. #        print "setitem"
  122. #        key = self._str2cmdkey(name)
  123. #        print "Setting",key,"to",value
  124. #        self._commands[key] = value        
  125.  
  126.     def _onKeyDown(self, event):
  127.         """Handle a KeyDown event.
  128.  
  129.         Note: This event handler is \b not called if the corresponding
  130.         description text is present in the menu. In that case, the menu
  131.         handles the events itself (a wx feature). But it seems this only
  132.         works with English modifier names.
  133.         """
  134.         print "KeyDown",
  135.         print "KeyCode:",event.GetKeyCode(),"RawKeyCode:",event.GetRawKeyCode()
  136.  
  137.         # Create the key tuple
  138.         key = self._event2cmdkey(event)
  139.         # Check if the key was bound
  140.         if key in self._commands:
  141.             # Call the bound function
  142.             func = self._commands[key]
  143.             func()
  144.         else:
  145.             event.Skip()
  146.     
  147.     def _onKeyUp(self, event):
  148. #        print "KeyUp",
  149. #        print "KeyCode:",event.GetKeyCode(),"RawKeyCode:",event.GetRawKeyCode()
  150.         event.Skip()
  151.  
  152.     def __setattr__(self, name, value):
  153.         if name=="":
  154.             return
  155.         # If the name starts with an underscore then it's not a key description
  156.         if name[0]=="_":
  157.             object.__setattr__(self, name, value)
  158.             return
  159.  
  160.         # Bind key...
  161.  
  162.         # Create the key tuple
  163.         key = self._str2cmdkey(name)
  164.         # Remove an existing binding
  165.         if self._commands.has_key(key):
  166.             self.__delattr__(name)
  167.         # Store the key binding
  168.         self._commands[key] = value
  169.  
  170.         # Update menu items
  171.         self._updateMenu(value)
  172.  
  173.     def __delattr__(self, name):
  174.         # If the name starts with an underscore then it's not a key description
  175.         if name[0]=="_":
  176.             object.__delattr__(self, name)
  177.             return
  178.  
  179.         # Create the key tuple
  180.         key = self._str2cmdkey(name)
  181.         # Check if a key binding exists
  182.         if self._commands.has_key(key):
  183.             func = self._commands[key]
  184.             del self._commands[key]
  185.             # Update menu items
  186.             self._updateMenu(func)
  187.         else:
  188.             raise KeyNotBound, "Key '%s' is not bound to a function."%name
  189.  
  190.  
  191.     def _updateMenu(self, func):
  192.         """Update all menu items that are bound to func."""
  193.         # Check if any menu items have to be updated
  194.         menu = getattr(self._window, "menu", None)
  195.         if menu==None:
  196.             return
  197.         nodes = menu.findCommandNodes(func)
  198.         for n in nodes:
  199.             n.update()        
  200.         
  201.  
  202.     def _event2cmdkey(self, event):
  203.         """Convert a key event into a tuple which can be used as key."""
  204.         return (bool(event.ShiftDown()), bool(event.ControlDown()),
  205.                 bool(event.AltDown()), bool(event.MetaDown()),
  206.                 event.GetKeyCode())
  207.  
  208.     def _str2cmdkey(self, s):
  209.         """Convert a key description string into the key tuple."""
  210.  
  211.         f = s.upper().split("_")
  212.  
  213.         # Check if the modifiers are correct
  214.         for m in f[:-1]:
  215.             if m not in ["SHIFT", "CTRL", "ALT", "META"]:
  216.                 raise InvalidKeyDescription, "Key '%s' contains invalid modifiers."%s
  217.  
  218.         # Convert the last argument into a key code
  219.         skey = f[-1]
  220.         if len(skey)==1:
  221.             key = ord(skey)
  222.         else:
  223.             key = getattr(wx, "WXK_%s"%skey, None)
  224.             if key==None:
  225.                 raise InvalidKeyDescription, "Key '%s' does not exist."%s
  226.         
  227.         return ("SHIFT" in f, "CTRL" in f, "ALT" in f, "META" in f, key)
  228.  
  229.     def _cmdkey2text(self, key):
  230.         shift, ctrl, alt, meta, key = key
  231.         mods = []
  232.         if shift:
  233.             mods.append("Shift")
  234. #            mods.append("Umschalt")
  235.         if ctrl:
  236.             mods.append("Ctrl")
  237. #            mods.append("Strg")
  238.         if alt:
  239.             mods.append("Alt")
  240.         if meta:
  241.             mods.append("Meta")
  242.  
  243.         ks = self._wxkeystrs.get(key, None)
  244.         if ks==None:
  245.             ks=chr(key)
  246.         mods.append(ks)
  247.             
  248.         return string.join(mods, "+")
  249.         
  250.             
  251.         
  252.     
  253.         
  254.