Beispiel #1
0
def register_factory(parser, section, name, value, lineInfo):
    module = '.'.join(name.replace(':', '.').split('.')[:-1])
    pMap = parser.pMap
    globalDict = parser.globalDict

    def onImport(module):
        iface = importString(name)
        pMap.registerProvider(
            FactoryFor(iface),
            ruleForExpr(name, "importObject(%s)" % value, globalDict))
        pMap.registerProvider(iface, CreateViaFactory(iface))

    whenImported(module, onImport)
Beispiel #2
0
    def _(f):
        def patchmod(mod):
            #print('patching %s ...' % (modname,))
            f()

        # XXX on pypy < 7.3 lazy-loading fails: https://bitbucket.org/pypy/pypy/issues/3099
        #     -> import & patch eagerly
        if 'PyPy' in sys.version and sys.pypy_version_info < (7, 3):
            try:
                mod = __import__(modname)
            except ImportError:
                return  # module not available - nothing to patch
            patchmod(mod)
            return

        imports.whenImported(modname, patchmod)
        return f
Beispiel #3
0
def _register_rule(gf, pred, context, cls):
    """Register a rule for `gf` with possible import-deferring"""
    if not isinstance(gf, basestring):
        rules = rules_for(gf)
        rules.add(parse_rule(Dispatching(gf).engine, pred, context, cls))
        return
    if len(gf.split(':'))<>2 or len(gf.split())>1:
        raise TypeError(
            "Function specifier %r is not in 'module.name:attrib.name' format"
            % (gf,)
        )
    modname, attrname = gf.split(':')
    from peak.util.imports import whenImported
    def _delayed_register(module):
        for attr in attrname.split('.'):
            module = getattr(module, attr)
        _register_rule(module, pred, context, cls)
    whenImported(modname, _delayed_register)
Beispiel #4
0
def _register_rule(gf, pred, context, cls):
    """Register a rule for `gf` with possible import-deferring"""
    if not isinstance(gf, basestring):
        rules = rules_for(gf)
        rules.add(parse_rule(Dispatching(gf).engine, pred, context, cls))
        return
    if len(gf.split(':'))!=2 or len(gf.split())>1:
        raise TypeError(
            "Function specifier %r is not in 'module.name:attrib.name' format"
            % (gf,)
        )
    modname, attrname = gf.split(':')
    from peak.util.imports import whenImported
    def _delayed_register(module):
        for attr in attrname.split('.'):
            module = getattr(module, attr)
        _register_rule(module, pred, context, cls)
    whenImported(modname, _delayed_register)
Beispiel #5
0
        from wx import EvtHandler  #@UnusedImport
        globals()['EvtHandler'] = EvtHandler
        from wx import PyDeadObjectError  #@UnusedImport
        globals()['PyDeadObjectError'] = PyDeadObjectError
    except ImportError:
        pass
    else:
        globals()['_usingWX'] = True


class PyDeadObjectError(object):
    #must be before whenImported('wx', _setup_usingWX)
    pass


whenImported('wx', _setup_usingWX)


class mydefaultdict(defaultdict):
    pass


class ObservableBase(object):
    '''
    Provides plumbing for the observable pattern. You probably don't want to
    subclass this--try Observable instead.
    '''

    observable_attrs = 'observers _observable_frozen class_names _freezecount guimap _flags'.split(
    )
Beispiel #6
0
    try:
        import wx
        globals()['wx'] = wx
        from wx import EvtHandler #@UnusedImport
        globals()['EvtHandler'] = EvtHandler
        from wx import PyDeadObjectError #@UnusedImport
        globals()['PyDeadObjectError'] = PyDeadObjectError
    except ImportError:
        pass
    else:
        globals()['_usingWX'] = True

class PyDeadObjectError(object):
    #must be before whenImported('wx', _setup_usingWX)
    pass
whenImported('wx', _setup_usingWX)

class mydefaultdict(defaultdict):
    pass

class ObservableBase(object):
    '''
    Provides plumbing for the observable pattern. You probably don't want to
    subclass this--try Observable instead.
    '''

    observable_attrs = 'observers _observable_frozen class_names _freezecount guimap _flags'.split()

    _observable_frozen = False
    _freezecount = False
Beispiel #7
0
            for item in adapt(base, IConfigKey).registrationKeys(depth):
                if item[0] not in yielded:
                    yield item
                    yielded[item[0]] = True

    def lookupKeys(self):
        """Iterate over keys that should be used for lookup"""
        return self.subject,

    def parentKeys(self):
        return ()


whenImported(
    'zope.interface', lambda interface:
    (protocols.declareAdapter(InterfaceAsConfigKey,
                              provides=[IConfigKey],
                              forTypes=[interface.Interface.__class__])))


class ImmutableConfig(object):
    def __init__(self, baseMaps=(), items=()):

        self.depth = depths = {}
        self.keysIndex = keysIndex = {}
        self.data = data = {}

        for base in baseMaps:
            adapt(base, ImmutableConfig)
            for key, depth in base.depth.items():
                old = depths.get(key, depth)
Beispiel #8
0
    r.bottom = rect.Y + rect.Height
    return r


def wxRectFromRECT(rect):
    return wx.Rect(rect.left, rect.top, rect.right - rect.left,
                   rect.bottom - rect.top)


def GetRECT(win):
    return wxRectToRECT(win.Rect)


def GetLRECT(win):
    return wxRectToRECT(wx.RectS(win.GetSize()))


def _monkeypatch(*a, **k):
    # Hack until patching methods works better in new bindings.
    WindowClass = wx._Window if wx.WXPY else wx.Window

    WindowClass.GetRECT = GetRECT
    WindowClass.RECT = property(GetRECT)
    WindowClass.GetLRECT = GetLRECT
    WindowClass.LRECT = property(GetLRECT)
    wx.Rect.FromRECT = staticmethod(wxRectFromRECT)
    wx.Rect.RECT = property(wxRectToRECT)


whenImported('wx', _monkeypatch)
Beispiel #9
0
            if wxonly:
                timer.notify = lambda: ontimer(*a, **k)

    return wrapper

def TimeRouterCallLater(*a, **k):
    t = Timer(0, *a, **k)
    t._verbose = False
    t.start()

def wakeup():
    TimeRouterCallLater(lambda: None)

def _register_call_later(callbacks):
    callbacks.register_call_later('TimeRouter', TimeRouterCallLater)
whenImported('util.callbacks', _register_call_later)

if __name__ == "__main__":
    from util import CallCounter
    class WaitNSeconds(TimeOut):

        def __init__(self, seconds, name):
            TimeOut.__init__(self)
            self._finished = False
            self.seconds = seconds
            self.name    = name
            self.totaltime = 0
            self.cc = CallCounter(4, self.stop)
            self.done_at = default_timer() + seconds

        def compute_timeout(self):
Beispiel #10
0
def TimeRouterCallLater(*a, **k):
    t = Timer(0, *a, **k)
    t._verbose = False
    t.start()


def wakeup():
    TimeRouterCallLater(lambda: None)


def _register_call_later(callbacks):
    callbacks.register_call_later('TimeRouter', TimeRouterCallLater)


whenImported('util.callbacks', _register_call_later)

if __name__ == "__main__":
    from util import CallCounter

    class WaitNSeconds(TimeOut):
        def __init__(self, seconds, name):
            TimeOut.__init__(self)
            self._finished = False
            self.seconds = seconds
            self.name = name
            self.totaltime = 0
            self.cc = CallCounter(4, self.stop)
            self.done_at = default_timer() + seconds

        def compute_timeout(self):
Beispiel #11
0
            return int(ob)
        except ValueError:
            pass

        if default is NOT_GIVEN:
            raise LookupError("No such log level", ob)

        return default


whenImported(
    'logging',
    lambda logging: (
        # Add the other syslog levels
        logging.addLevelName(25, 'NOTICE'),
        logging.addLevelName(60, 'ALERT'),
        logging.addLevelName(70, 'EMERG'),

        # And make it so PEP 282 loggers can be adapted to ILogger
        protocols.declareImplementation(logging.getLogger().__class__,
                                        instancesProvide=[IBasicLogger])))


class Event(binding.Component):

    ident = 'PEAK'  # XXX use component names if avail?
    msg = ''
    args = ()
    priority = binding.Require("Integer priority level")
    timestamp = binding.Make(lambda: time())
    uuid = binding.Make('peak.util.uuid:UUID')
Beispiel #12
0
def wxRectToRECT(rect):
    r = wintypes.RECT()
    r.left = rect.X
    r.top  = rect.Y
    r.right = rect.X + rect.Width
    r.bottom = rect.Y + rect.Height
    return r

def wxRectFromRECT(rect):
    return wx.Rect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top)

def GetRECT(win):
    return wxRectToRECT(win.Rect)

def GetLRECT(win):
    return wxRectToRECT(wx.RectS(win.GetSize()))

def _monkeypatch(*a, **k):
    # Hack until patching methods works better in new bindings.
    WindowClass = wx._Window if wx.WXPY else wx.Window
    
    WindowClass.GetRECT = GetRECT
    WindowClass.RECT = property(GetRECT)
    WindowClass.GetLRECT = GetLRECT
    WindowClass.LRECT = property(GetLRECT)
    wx.Rect.FromRECT = staticmethod(wxRectFromRECT)
    wx.Rect.RECT = property(wxRectToRECT)

whenImported('wx', _monkeypatch)