home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 February / maximum-cd-2011-02.iso / DiscContents / digsby_setup85.exe / lib / common / actions.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-11-24  |  8.3 KB  |  245 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. from __future__ import with_statement
  5. from functools import partial
  6. from types import FunctionType as function
  7. from util.observe import Observable, ObservableMeta
  8. import logging
  9. import util.data_importer as importer
  10. import util.introspect as introspect
  11. import util.merge as util
  12. import util.primitives.funcs as funcs
  13. import util.primitives.mapping as mapping
  14. import util.primitives.strings as strings
  15. log = logging.getLogger('actions')
  16. __author__ = 'dotSyntax'
  17. _actions_cached = None
  18. _actions_imported = False
  19.  
  20. def _actions():
  21.     global _actions_imported
  22.     if _actions_imported:
  23.         return _actions_cached
  24.     skin = skin
  25.     import gui
  26.     
  27.     try:
  28.         actions = importer.yaml_import('actions', loadpath = [
  29.             skin.resourcedir()])
  30.     except ImportError:
  31.         _actions_imported
  32.         _actions_imported
  33.         actions = { }
  34.     except:
  35.         _actions_imported
  36.     finally:
  37.         _actions_imported = True
  38.  
  39.     add_actions(actions)
  40.     return _actions_cached
  41.  
  42.  
  43. def add_actions(actionsdict):
  44.     global _actions_cached
  45.     the_actions = _actions()
  46.     if the_actions is None:
  47.         the_actions = { }
  48.     
  49.     the_actions = util.merge.merge(the_actions, actionsdict)
  50.     _actions_cached = the_actions
  51.  
  52.  
  53. def forclass(cls, search_bases = True):
  54.     if not isinstance(cls, type) and hasattr(cls, '__class__'):
  55.         cls = cls.__class__
  56.     
  57.     if search_bases:
  58.         classes = list(reversed(cls.__mro__))
  59.     else:
  60.         classes = [
  61.             cls]
  62.     return funcs.flatten((lambda .0: for c in .0:
  63. _actions().get(c.__name__, []))(classes))
  64.  
  65.  
  66. class Action(Observable):
  67.     
  68.     def __init__(self, name, callable):
  69.         Observable.__init__(self)
  70.         funcs.autoassign(self, locals())
  71.  
  72.     
  73.     def __call__(self, *args, **kws):
  74.         return self.callable(*args, **kws)
  75.  
  76.     
  77.     def __repr__(self):
  78.         return '<Action %s for %r>' % (self.name, self.callable)
  79.  
  80.  
  81.  
  82. def menu(parent, obj, menu = None, cls = None, search_bases = True, filter = (lambda func: True)):
  83.     UMenu = UMenu
  84.     import gui.uberwidgets.umenu
  85.     actions = None(forclass if cls is not None else obj, search_bases)
  86.     menu = None if menu is not None else UMenu(parent)
  87.     names = set()
  88.     for action in actions:
  89.         if isinstance(action, basestring) and action.startswith('--'):
  90.             menu.AddSep()
  91.             continue
  92.         elif 'method' in action:
  93.             introspect.import_function(action['method'])(menu, obj)
  94.             continue
  95.         
  96.         name = action['call']
  97.         if name in names:
  98.             continue
  99.         else:
  100.             names.add(name)
  101.         func = getattr(obj, name, None)
  102.         if func is None:
  103.             continue
  104.         
  105.         gui_name = action['name']
  106.         
  107.         try:
  108.             (precondition, needslist) = getattr(obj, '_actions')[name]
  109.         except KeyError:
  110.             _e = None
  111.             
  112.             precondition = lambda v: True
  113.             needslist = []
  114.  
  115.         if needslist:
  116.             import gui.userform as userform
  117.             callback = partial(userform.getinput, obj, parent, needslist, func, title = gui_name.replace('&', ''))
  118.         elif 'gui' in action:
  119.             gui = introspect.import_function(action['gui'])
  120.             if not hasattr(gui, 'Prompt'):
  121.                 
  122.                 callback = lambda gui = gui, func = (func,): gui(obj, func)
  123.             else:
  124.                 
  125.                 def callback(gui = gui, func = (func,)):
  126.                     gui(None, obj).Prompt(func)
  127.  
  128.         else:
  129.             callback = func
  130.         result = None if precondition is not None else True
  131.         if filter(func):
  132.             if precondition is None or result is not None:
  133.                 name = action_name(obj, gui_name)
  134.                 menu.AddItem(name, callback = callback).Enable(bool(result))
  135.                 continue
  136.     
  137.     if menu.GetMenuItemCount() == 0:
  138.         menu.AddItem(_('No actions')).Enable(False)
  139.     
  140.     while menu[-1].IsSeparator():
  141.         menu.RemoveItem(menu[len(menu) - 1])
  142.     return menu
  143.  
  144.  
  145. def action_name(obj, name):
  146.     if name.find('$') != -1:
  147.         name = strings.curly(name, source = {
  148.             'obj': obj })
  149.     
  150.     return name
  151.  
  152. _actioncalls = dict()
  153.  
  154. class ActionMeta(type):
  155.     action_prefix = '__ACTION__'
  156.     class_action_attr = '_actions'
  157.     
  158.     def __init__(cls, name, bases, dict):
  159.         super(ActionMeta, cls).__init__(name, bases, dict)
  160.         superactions = mapping.odict()
  161.         if 'inherited_actions' in dict:
  162.             bases = bases + tuple(dict['inherited_actions'])
  163.         
  164.         (funcs.do,)((lambda .0: for c in .0:
  165. if hasattr(c, '_actions'):
  166. superactions.update(c._actions)continue)(bases))
  167.         setattr(cls, ActionMeta.class_action_attr, superactions)
  168.         actions = getattr(cls, ActionMeta.class_action_attr)
  169.         prefix = ActionMeta.action_prefix
  170.         for v in dict.itervalues():
  171.             if isinstance(v, function) and v.__name__.startswith(prefix):
  172.                 v.__name__ = v.__name__[len(prefix):]
  173.                 val = _actioncalls.pop(v)
  174.                 actions[v.__name__] = val
  175.                 continue
  176.         
  177.  
  178.  
  179.  
  180. class ActionType(object):
  181.     __metaclass__ = ActionMeta
  182.  
  183.  
  184. class ObservableActionMeta(ObservableMeta, ActionMeta):
  185.     pass
  186.  
  187.  
  188. class ActionError(Exception):
  189.     pass
  190.  
  191.  
  192. def _action_err_info(callable_predicate):
  193.     code = callable_predicate.func_code
  194.     fn = code.co_filename
  195.     ln = code.co_firstlineno
  196.     getline = getline
  197.     import linecache
  198.     if not getline(fn, ln):
  199.         pass
  200.     line = '<UNKNOWN>'
  201.     return (fn, ln, line)
  202.  
  203.  
  204. def action(callable_predicate = None, needs = None):
  205.     if callable_predicate is not None and not callable(callable_predicate):
  206.         raise TypeError("action decorator needs a callable or None as it's only argument (you gave a %s)" % type(callable_predicate))
  207.     not callable(callable_predicate)
  208.     
  209.     def action_dec(meth):
  210.         
  211.         def func(*args, **kws):
  212.             if callable_predicate:
  213.                 (filename, line, line_text) = _action_err_info(callable_predicate)
  214.                 err_msg = '%s is not allowed, %%s\nFile "%s", line %d, in %s\n%s' % (meth.__name__, filename, line, callable_predicate.__name__, line_text)
  215.                 
  216.                 try:
  217.                     allow = callable_predicate(*args, **kws)
  218.                 except TypeError:
  219.                     e = None
  220.                     raise ActionError, err_msg % 'error in precondition function: ' + str(e)
  221.  
  222.                 if not allow:
  223.                     log.warning(str(ActionError(err_msg % 'precondition not met for')))
  224.                 
  225.             
  226.             return meth(*args, **kws)
  227.  
  228.         func.__name__ = ActionMeta.action_prefix + meth.__name__
  229.         func.__doc__ = meth.__doc__
  230.         
  231.         def allowed(obj):
  232.             if hasattr(obj, '_disallow_actions'):
  233.                 return False
  234.             if callable_predicate:
  235.                 return callable_predicate(obj)
  236.             return True
  237.  
  238.         func.action_allowed = allowed
  239.         tneeds = needs
  240.         _actioncalls[func] = (allowed, tneeds)
  241.         return func
  242.  
  243.     return action_dec
  244.  
  245.