home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 October / maximum-cd-2011-10.iso / DiscContents / digsby_setup.exe / lib / gui / input / inputmanager.pyo (.txt) < prev   
Encoding:
Python Compiled Bytecode  |  2011-06-22  |  11.1 KB  |  360 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. from __future__ import with_statement
  5. from traceback import print_exc
  6. from collections import defaultdict
  7. from util.introspect import import_function, memoize
  8. from util.primitives.funcs import Delegate
  9. from util.merge import merge_keys
  10. from prefs import flatten
  11. import wx
  12. from wx import WXK_F1, WXK_F24, wxEVT_KEY_DOWN
  13. from logging import getLogger
  14. log = getLogger('input')
  15. DEBUG = log.debug
  16.  
  17. class InputManager(object):
  18.     
  19.     def __init__(self):
  20.         self.reset()
  21.  
  22.     
  23.     def reset(self):
  24.         self.handlers = defaultdict(Delegate)
  25.         self.actions = defaultdict(dict)
  26.         self.contexts = []
  27.         self.context_lookups = []
  28.         self.actionnames = { }
  29.         self.context_cache = { }
  30.         self.bound = False
  31.  
  32.     
  33.     def AddGlobalContext(self, name, contextstr):
  34.         self.context_lookups.append((contextstr.lower(), GlobalContext()))
  35.         self.context_cache.clear()
  36.         self.resolve_actions()
  37.  
  38.     
  39.     def AddClassContext(self, name, contextstr, cls):
  40.         self.context_lookups.append((contextstr.lower(), ClassContext(name, cls)))
  41.         self.context_cache.clear()
  42.         self.resolve_actions()
  43.  
  44.     
  45.     def AddKeyboardShortcut(self, actionname, accels):
  46.         keys = (KeyActionSet,)((lambda .0: for accel in .0:
  47. (keycodes(accel), actionname))(accels.split(',')))
  48.         self.actionnames[actionname.lower()] = keys
  49.         self.resolve_actions()
  50.  
  51.     
  52.     def LoadKeys(self, filepath):
  53.         addkey = self.AddKeyboardShortcut
  54.         import syck
  55.         
  56.         try:
  57.             f = _[1]
  58.             for actionname, accels in flatten(merge_keys(syck.load(f))):
  59.                 addkey(actionname, accels)
  60.         finally:
  61.             pass
  62.  
  63.  
  64.     
  65.     def resolve_actions(self):
  66.         if not self.bound:
  67.             return None
  68.         contexts = set()
  69.         find_context = self.find_context
  70.         for actionname, actionset in self.actionnames.iteritems():
  71.             context = find_context(actionname)
  72.             if context is not None:
  73.                 
  74.                 try:
  75.                     keyactions = self.actions[wxEVT_KEY_DOWN][context]
  76.                 except KeyError:
  77.                     self.bound
  78.                     self.bound
  79.                     keyactions = self.actions[wxEVT_KEY_DOWN][context] = KeyActionSet()
  80.                 except:
  81.                     self.bound
  82.  
  83.                 keyactions.update(actionset)
  84.                 contexts.add(context)
  85.                 continue
  86.             self.bound
  87.         
  88.         self.contexts = sorted(contexts, reverse = True)
  89.  
  90.     
  91.     def AddActionCallback(self, actionname, callback):
  92.         actionname = actionname.lower()
  93.         if isinstance(callback, basestring):
  94.             callback = LazyStringImport(callback)
  95.         
  96.         if actionname not in self.handlers:
  97.             self.handlers[actionname] = Delegate([
  98.                 callback])
  99.         else:
  100.             self.handlers[actionname] += callback
  101.         self.resolve_actions()
  102.  
  103.     
  104.     def BindWxEvents(self, evt_handler):
  105.         if self.bound is not evt_handler:
  106.             evt_handler.Bind(wx.EVT_KEY_DOWN, self.handle_event)
  107.             self.bound = evt_handler
  108.         
  109.         self.resolve_actions()
  110.  
  111.     
  112.     def find_context(self, actionname):
  113.         if actionname in self.context_cache:
  114.             return self.context_cache[actionname]
  115.         actionname = actionname.lower()
  116.         startswith = actionname.startswith
  117.         found = _[1]
  118.         found.sort(key = (lambda s: len(s[0])), reverse = True)
  119.         context = [] if found else None
  120.         return self.context_cache.setdefault(actionname, context)
  121.  
  122.     
  123.     def handle_event(self, e):
  124.         contexts = self.contexts
  125.         for win in child_and_parents(e.EventObject):
  126.             for context in contexts:
  127.                 if context(win):
  128.                     if self.invoke_actions(context, e, win) is False:
  129.                         return None
  130.                     continue
  131.                 self.invoke_actions(context, e, win) is False
  132.             
  133.         
  134.         e.Skip()
  135.  
  136.     
  137.     def invoke_actions(self, context, e, win):
  138.         
  139.         try:
  140.             actionset = self.actions[e.EventType][context]
  141.         except KeyError:
  142.             return None
  143.  
  144.         
  145.         try:
  146.             actionname = actionset(e, win)
  147.             if actionname is False:
  148.                 return None
  149.             if actionname is not None:
  150.                 return self.event(actionname, win)
  151.         except Exception:
  152.             print_exc()
  153.  
  154.  
  155.     
  156.     def event(self, actionname, *a, **k):
  157.         
  158.         try:
  159.             DEBUG('firing action %r', actionname)
  160.             action_delegate = self.handlers[actionname]
  161.             DEBUG(' callbacks: %r', action_delegate)
  162.         except KeyError:
  163.             pass
  164.  
  165.         
  166.         try:
  167.             if action_delegate:
  168.                 action_delegate(*a, **k)
  169.                 return False
  170.         except Exception:
  171.             print_exc()
  172.  
  173.  
  174.  
  175.  
  176. class Context(object):
  177.     __slots__ = [
  178.         'name']
  179.     priority = 0
  180.     
  181.     def __init__(self, name):
  182.         self.name = name
  183.  
  184.     
  185.     def __call__(self):
  186.         raise NotImplementedError('Context subclasses must implement __call__')
  187.  
  188.     
  189.     def __cmp__(self, other):
  190.         return cmp(self.priority, other.priority)
  191.  
  192.     
  193.     def __hash__(self):
  194.         return hash(id(self))
  195.  
  196.  
  197.  
  198. class WindowNameContext(Context):
  199.     __slots__ = [
  200.         'window_name']
  201.     priority = 100
  202.     
  203.     def __init__(self, name, window_name):
  204.         Context.__init__(self, name)
  205.         self.window_name = window_name
  206.  
  207.     
  208.     def __call__(self, window):
  209.         return window.Name == self.window_name
  210.  
  211.     
  212.     def __repr__(self):
  213.         return '<WindowNameContext %r>' % self.window_name
  214.  
  215.  
  216.  
  217. class ClassContext(Context):
  218.     __slots__ = [
  219.         'cls']
  220.     priority = 90
  221.     
  222.     def __init__(self, name, cls):
  223.         Context.__init__(self, name)
  224.         self.cls = cls
  225.  
  226.     
  227.     def __call__(self, window):
  228.         return isinstance(window, self.cls)
  229.  
  230.     
  231.     def __repr__(self):
  232.         return '<ClassContext %r>' % self.cls
  233.  
  234.  
  235.  
  236. class GlobalContext(Context):
  237.     priority = 10
  238.     
  239.     def __init__(self, name = 'Global Shortcuts'):
  240.         Context.__init__(self, name)
  241.  
  242.     
  243.     def __call__(self, window, tlw = wx.TopLevelWindow):
  244.         return isinstance(window, tlw)
  245.  
  246.     
  247.     def __repr__(self):
  248.         return '<GlobalContext %s>' % self.name
  249.  
  250.  
  251.  
  252. class KeyActionSet(dict):
  253.     
  254.     def __call__(self, e, win):
  255.         keycode = e.KeyCode
  256.         if keycode <= keycode:
  257.             pass
  258.         elif keycode <= WXK_F24:
  259.             pass
  260.         elif keycode < 256:
  261.             keycode = ord(chr(keycode).upper())
  262.         
  263.         key = (e.Modifiers, keycode)
  264.         return self.get(key, None)
  265.  
  266.  
  267.  
  268. def child_and_parents(win):
  269.     yield win
  270.     win = getattr(win, 'Parent', None)
  271.     while win is not None:
  272.         yield win
  273.         win = win.Parent
  274.  
  275.  
  276. def _accelerr(s):
  277.     raise ValueError('illegal accelerator: like "cmd+k" or "k" (you gave "%s")' % s)
  278.  
  279. replacements = {
  280.     'backspace': 'back',
  281.     'capslock': 'capital',
  282.     '=': 43 }
  283.  
  284. def keycodes(s, accel = True):
  285.     if isinstance(s, basestring):
  286.         s = s.strip()
  287.         seq = s.split('+')
  288.         for i, _elem in enumerate(seq[:]):
  289.             if _elem == '':
  290.                 seq[i] = '+'
  291.                 continue
  292.         
  293.         if len(seq) == 1:
  294.             modifiers = [
  295.                 'normal']
  296.             key = s
  297.         else:
  298.             modifiers = seq[:-1]
  299.             key = seq[-1]
  300.     elif not isinstance(s, int):
  301.         _accelerr(s)
  302.     
  303.     modifiers = [
  304.         'normal']
  305.     key = s
  306.     modifier = 0
  307.     PREFIX = None if accel else 'MOD_'
  308.     for mod in modifiers:
  309.         modifier |= getattr(wx, PREFIX + mod.upper())
  310.     
  311.     if isinstance(key, basestring):
  312.         if len(key) == 1 and key not in replacements:
  313.             key = ord(key.upper())
  314.         else:
  315.             key = replacements.get(key.lower(), key)
  316.             if isinstance(key, basestring):
  317.                 
  318.                 try:
  319.                     key = getattr(wx, 'WXK_' + replacements.get(key.lower(), key).upper())
  320.                 except AttributeError:
  321.                     _accelerr(s)
  322.                 except:
  323.                     None<EXCEPTION MATCH>AttributeError
  324.                 
  325.  
  326.             None<EXCEPTION MATCH>AttributeError
  327.     
  328.     return (modifier, key)
  329.  
  330. keycodes = memoize(keycodes)
  331.  
  332. class LazyStringImport(str):
  333.     
  334.     def __call__(self, *a, **k):
  335.         
  336.         try:
  337.             return self.cb()
  338.         except TypeError:
  339.             e = None
  340.             if str(e).endswith('takes exactly 1 argument (0 given)'):
  341.                 return self.cb(*a, **k)
  342.             raise 
  343.         except:
  344.             str(e).endswith('takes exactly 1 argument (0 given)')
  345.  
  346.  
  347.     
  348.     def cb(self):
  349.         
  350.         try:
  351.             return self._cb
  352.         except AttributeError:
  353.             self._cb = import_function(self)
  354.             return self._cb
  355.  
  356.  
  357.     cb = property(cb)
  358.  
  359. input_manager = InputManager()
  360.