From 981604fc8bbeaaeb18a4f8ec6527b803b0928b2e Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Tue, 23 Sep 2014 06:55:08 +0200 Subject: [PATCH] Add initial object registry. --- qutebrowser/app.py | 2 ++ qutebrowser/utils/usertypes.py | 61 ++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/qutebrowser/app.py b/qutebrowser/app.py index ed4e84eb6..e074ca296 100644 --- a/qutebrowser/app.py +++ b/qutebrowser/app.py @@ -53,6 +53,7 @@ class Application(QApplication): """Main application instance. Attributes: + obj: The object registry. mainwindow: The MainWindow QWidget. debugconsole: The ConsoleWidget for debugging. commandrunner: The main CommandRunner instance. @@ -93,6 +94,7 @@ class Application(QApplication): 'tabs': False, 'main': False, } + self.obj = utypes.ObjectRegistry() self._timers = [] self._shutting_down = False self._keyparsers = None diff --git a/qutebrowser/utils/usertypes.py b/qutebrowser/utils/usertypes.py index e17e231ac..34a9487a8 100644 --- a/qutebrowser/utils/usertypes.py +++ b/qutebrowser/utils/usertypes.py @@ -381,3 +381,64 @@ class Timer(QTimer): super().start(msec) else: super().start() + + +class ObjectRegistry: + + """A registry of long-living objects in qutebrowser. + + Inspired by the eric IDE code (E5Gui/E5Application.py). + """ + + def __init__(self): + self._objects = {} + self._objects['global'] = {} + + def get(self, name, scope='global'): + """Get an object from the object registry. + + Args: + name: The name of the object to get. + scope: The scope the object is registered in. + + Return: + The registered object. + """ + try: + objects = self._objects[scope] + except KeyError: + raise KeyError("Invalid scope '{}'.".format(scope)) + try: + obj = objects[name] + except KeyError: + raise KeyError("No object '{}' in scope '{}'!".format(obj, scope)) + return obj + + def register(self, name, obj, scope='global'): + """Register an object in the object registry. + + Args: + name: The name to register the object as. + obj: The object to register. + scope: The scope to register the object in. + """ + if scope not in self._objects: + raise KeyError("Invalid scope '{}'.".format(scope)) + if name in self._objects[scope]: + existing_obj = self._objects[scope][name] + raise KeyError("Object '{}' is already registered in scope " + "'{}' ({})!".format(name, scope, existing_obj)) + self._objects[scope][name] = obj + + def dump_objects(self): + """Dump all objects as a string.""" + lines = [] + count = 0 + for scope, objects in self._objects.items(): + if objects: + lines.append("Scope {}:".format(scope)) + for name, obj in objects.items(): + lines.append(" {}: {}".format(name, repr(obj))) + count += 1 + lines.insert(0, '{} qutebrowser objects:'.format(count)) + return lines