Esempio n. 1
0
    def _show_panel(self, panel_name):
        '''
        Helper function to switch between panels.

        @param panel_name: the name of the wanted panel. Choose between
                        "configuration" or "add"
        '''
        if panel_name == "configuration":
            panel_to_remove = self.add_panel
            panel_to_add = self.config_panel
            side_is_enabled = True
        elif panel_name == "add":
            panel_to_remove = self.config_panel
            panel_to_add = self.add_panel
            side_is_enabled = False
        else:
            Log.error("panel name unknown")
            return
        # Central pane
        # NOTE: self.central_pane is the Gtk.Container in which we load panels
        if panel_to_remove in self.central_pane:
            self.central_pane.remove(panel_to_remove)
        if panel_to_add not in self.central_pane:
            self.central_pane.add(panel_to_add)
        self.central_pane.show_all()
        # Side treeview
        # disabled if we're adding a new backend
        try:
            # when this is called upon initialization of this class, the
            # backends_tv object has not been created yet.
            self.add_button.set_sensitive(side_is_enabled)
            self.remove_button.set_sensitive(side_is_enabled)
            self.backends_tv.set_sensitive(side_is_enabled)
        except AttributeError:
            pass
Esempio n. 2
0
 def __init__(self):
     """
      Creates a dictionary of the currently available backend modules
     """
     super(BackendFactory, self).__init__()
     if hasattr(self, "backend_modules"):
         # This object has already been constructed
         return
     self.backend_modules = {}
     # Look for backends in the GTG/backends dir
     this_dir = os.path.dirname(__file__)
     backend_files = filter(
         lambda f: f.endswith(".py") and f.startswith(self.BACKEND_PREFIX),
         os.listdir(this_dir))
     # Create module names
     module_names = map(lambda f: f.replace(".py", ""), backend_files)
     #Log.debug("Backends found: " + str(module_names))
     #print "Backends = " + str(module_names)
     # Load backend modules
     for module_name in module_names:
         extended_module_name = "GTG.backends." + module_name
         try:
             __import__(extended_module_name)
         except ImportError, exception:
             # Something is wrong with this backend, skipping
             Log.warning("Backend %s could not be loaded: %s" %
                         (module_name, str(exception)))
             continue
         except Exception, exception:
             # Other exception log as errors
             Log.error("Malformated backend %s: %s" %
                       (module_name, str(exception)))
             continue
Esempio n. 3
0
    def __init__(self):
        """
         Creates a dictionary of the currently available backend modules
        """
        Borg.__init__(self)
        if hasattr(self, "backend_modules"):
            # This object has already been constructed
            return
        self.backend_modules = {}
        backend_files = self._find_backend_files()
        # Create module names
        module_names = [f.replace(".py", "") for f in backend_files]
        Log.debug("Backends found: " + str(module_names))
        # Load backend modules
        for module_name in module_names:
            extended_module_name = "GTG.backends." + module_name
            try:
                __import__(extended_module_name)
            except ImportError as exception:
                # Something is wrong with this backend, skipping
                Log.warning("Backend %s could not be loaded: %s" %
                            (module_name, str(exception)))
                continue
            except Exception as exception:
                # Other exception log as errors
                Log.error("Malformated backend %s: %s" %
                          (module_name, str(exception)))
                continue

            self.backend_modules[module_name] = \
                sys.modules[extended_module_name]
Esempio n. 4
0
    def __init__(self):
        """
         Creates a dictionary of the currently available backend modules
        """
        super().__init__()
        if hasattr(self, "backend_modules"):
            # This object has already been constructed
            return
        self.backend_modules = {}
        backend_files = self._find_backend_files()
        # Create module names
        module_names = [f.replace(".py", "") for f in backend_files]
        Log.debug("Backends found: " + str(module_names))
        # Load backend modules
        for module_name in module_names:
            extended_module_name = "GTG.backends." + module_name
            try:
                __import__(extended_module_name)
            except ImportError as exception:
                # Something is wrong with this backend, skipping
                Log.warning("Backend %s could not be loaded: %s" %
                            (module_name, str(exception)))
                continue
            except Exception as exception:
                # Other exception log as errors
                Log.error("Malformated backend %s: %s" %
                          (module_name, str(exception)))
                continue

            self.backend_modules[module_name] = \
                sys.modules[extended_module_name]
Esempio n. 5
0
 def __init__(self):
     """
      Creates a dictionary of the currently available backend modules
     """
     super(BackendFactory, self).__init__()
     if hasattr(self, "backend_modules"):
         # This object has already been constructed
         return
     self.backend_modules = {}
     # Look for backends in the GTG/backends dir
     this_dir = os.path.dirname(__file__)
     backend_files = filter(lambda f: f.endswith(".py") and
                            f.startswith(self.BACKEND_PREFIX),
                            os.listdir(this_dir))
     # Create module names
     module_names = map(lambda f: f.replace(".py", ""), backend_files)
     Log.debug("Backends found: " + str(module_names))
     # Load backend modules
     for module_name in module_names:
         extended_module_name = "GTG.backends." + module_name
         try:
             __import__(extended_module_name)
         except ImportError, exception:
             # Something is wrong with this backend, skipping
             Log.warning("Backend %s could not be loaded: %s" %
                        (module_name, str(exception)))
             continue
         except Exception, exception:
             # Other exception log as errors
             Log.error("Malformated backend %s: %s" %
                      (module_name, str(exception)))
             continue
Esempio n. 6
0
    def initialize(self):
        """ This is called when a backend is enabled """
        super(Backend, self).initialize()

        if "state" not in self._parameters:
            self._parameters["state"] = "start"

        # Prepare parameters
        jid = self._parameters["username"]
        password = self._parameters["password"]
        server = "pubsub." + jid.split('@', 1)[-1]

        self._xmpp = PubsubClient(jid, password, server)
        self._xmpp.register_callback("failed_auth", self.on_failed_auth)
        self._xmpp.register_callback("connected", self.on_connected)
        self._xmpp.register_callback("disconnected", self.on_disconnected)

        if self._xmpp.connect(reattempt=False):
            self._xmpp.process()
        else:
            Log.error("Can't connect to XMPP")
            if self._parameters["state"] == "start":
                self.on_failed_auth()

        BackendSignals().connect('sharing-changed', self.on_sharing_changed)

        self._xmpp.register_callback("project_tag", self.on_new_remote_project)
        self._xmpp.register_callback("set_task", self.on_remote_set_task)
        self._xmpp.register_callback("rm_task", self.on_remote_rm_task)
Esempio n. 7
0
    def _show_panel(self, panel_name):
        '''
        Helper function to switch between panels.

        @param panel_name: the name of the wanted panel. Choose between
                        "configuration" or "add"
        '''
        if panel_name == "configuration":
            panel_to_remove = self.add_panel
            panel_to_add = self.config_panel
            side_is_enabled = True
        elif panel_name == "add":
            panel_to_remove = self.config_panel
            panel_to_add = self.add_panel
            side_is_enabled = False
        else:
            Log.error("panel name unknown")
            return
        # Central pane
        # NOTE: self.central_pane is the Gtk.Container in which we load panels
        if panel_to_remove in self.central_pane:
            self.central_pane.remove(panel_to_remove)
        if not panel_to_add in self.central_pane:
            self.central_pane.add(panel_to_add)
        self.central_pane.show_all()
        # Side treeview
        # disabled if we're adding a new backend
        try:
            # when this is called upon initialization of this class, the
            # backends_tv object has not been created yet.
            self.add_button.set_sensitive(side_is_enabled)
            self.remove_button.set_sensitive(side_is_enabled)
            self.backends_tv.set_sensitive(side_is_enabled)
        except AttributeError:
            pass
Esempio n. 8
0
def openxmlfile(zefile, root):
    """ Open an XML file in a robust way

    If file could not be opened, try:
        - file__
        - file.bak.0
        - file.bak.1
        - .... until BACKUP_NBR

    If file doesn't exist, create a new file """

    tmpfile = zefile + '__'
    try:
        if os.path.exists(zefile):
            return _try_openxmlfile(zefile, root)
        elif os.path.exists(tmpfile):
            Log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            return _try_openxmlfile(zefile, root)
        else:
            # Creating empty file
            doc, xmlproject = emptydoc(root)
            newfile = savexml(zefile, doc)
            if not newfile:
                Log.error("Could not create a new file %s" % zefile)
                sys.exit(1)
            return _try_openxmlfile(zefile, root)

    except IOError, msg:
        print msg
        sys.exit(1)
Esempio n. 9
0
    def initialize(self):
        """ This is called when a backend is enabled """
        super(Backend, self).initialize()

        if "state" not in self._parameters:
            self._parameters["state"] = "start"

        # Prepare parameters
        jid = self._parameters["username"]
        password = self._parameters["password"]
        server = "pubsub." + jid.split('@', 1)[-1]

        self._xmpp = PubsubClient(jid, password, server)
        self._xmpp.register_callback("failed_auth", self.on_failed_auth)
        self._xmpp.register_callback("connected", self.on_connected)
        self._xmpp.register_callback("disconnected", self.on_disconnected)

        if self._xmpp.connect(reattempt=False):
            self._xmpp.process()
        else:
            Log.error("Can't connect to XMPP")
            if self._parameters["state"] == "start":
                self.on_failed_auth()

        BackendSignals().connect('sharing-changed', self.on_sharing_changed)

        self._xmpp.register_callback("project_tag", self.on_new_remote_project)
        self._xmpp.register_callback("set_task", self.on_remote_set_task)
        self._xmpp.register_callback("rm_task", self.on_remote_rm_task)
Esempio n. 10
0
def openxmlfile(zefile, root):
    """ Open an XML file in a robust way

    If file could not be opened, try:
        - file__
        - file.bak.0
        - file.bak.1
        - .... until BACKUP_NBR

    If file doesn't exist, create a new file """

    tmpfile = zefile + '__'
    try:
        if os.path.exists(zefile):
            return _try_openxmlfile(zefile, root)
        elif os.path.exists(tmpfile):
            Log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            return _try_openxmlfile(zefile, root)
        else:
            # Creating empty file
            doc, xmlproject = emptydoc(root)
            newfile = savexml(zefile, doc)
            if not newfile:
                Log.error("Could not create a new file %s" % zefile)
                sys.exit(1)
            return _try_openxmlfile(zefile, root)

    except IOError, msg:
        print msg
        sys.exit(1)
Esempio n. 11
0
 def _when_taking_too_long(self):
     """
     Function that is executed when the Dbus connection seems to be
     hanging. It disables the backend and signals the error to the user.
     """
     Log.error("Dbus connection is taking too long for the Tomboy/Gnote" "backend!")
     BackendSignals().backend_failed(self.backend.get_id(), BackendSignals.ERRNO_DBUS)
     self.backend.quit(disable=True)
Esempio n. 12
0
    def on_failed_auth(self):
        """ Provided credencials are not valid.

        Disable this instance and show error to user """
        Log.error('Failed to authenticate')
        BackendSignals().backend_failed(self.get_id(),
                        BackendSignals.ERRNO_AUTHENTICATION)
        self.quit(disable=True)
Esempio n. 13
0
 def get_configuration(self):
     try:
         return datetime.time(int(self.config.get('hour')),
                              int(self.config.get('min')))
     except (ValueError):
         Log.error("Invalid time values: %s:%s", self.config.get('hour'),
                   self.config.get('min'))
         return datetime.time(0, 0)
Esempio n. 14
0
    def on_failed_auth(self):
        """ Provided credencials are not valid.

        Disable this instance and show error to user """
        Log.error('Failed to authenticate')
        BackendSignals().backend_failed(self.get_id(),
                                        BackendSignals.ERRNO_AUTHENTICATION)
        self.quit(disable=True)
Esempio n. 15
0
 def get_configuration(self):
     try:
         return datetime.time(int(self.config.get('hour')),
                              int(self.config.get('min')))
     except(ValueError):
         Log.error("Invalid time values: %s:%s", self.config.get('hour'),
                   self.config.get('min'))
         return datetime.time(0, 0)
Esempio n. 16
0
def openxmlfile(zefile, root):
    """ Open an XML file in a robust way

    If file could not be opened, try:
        - file__
        - file.bak.0
        - file.bak.1
        - .... until BACKUP_NBR

    If file doesn't exist, create a new file """

    tmpfile = zefile + '__'
    try:
        if os.path.exists(zefile):
            return _try_openxmlfile(zefile, root)
        elif os.path.exists(tmpfile):
            Log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            return _try_openxmlfile(zefile, root)
        else:
            # Creating empty file
            doc, xmlproject = emptydoc(root)
            newfile = savexml(zefile, doc)
            if not newfile:
                Log.error("Could not create a new file %s" % zefile)
                sys.exit(1)
            return _try_openxmlfile(zefile, root)

    except IOError as msg:
        print(msg)
        sys.exit(1)

    except xml.parsers.expat.ExpatError as msg:
        errormsg = "Error parsing XML file %s: %s" % (zefile, msg)
        Log.error(errormsg)
        if os.path.exists(tmpfile):
            Log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            # Ok, try one more time now
            try:
                return _try_openxmlfile(zefile, root)
            except Exception as msg:
                Log.warning('Failed with reason: %s' % msg)

        # Try to revert to backup
        backup_name = _get_backup_name(zefile)
        for i in range(BACKUP_NBR):
            backup_file = "%s.bak.%d" % (backup_name, i)
            if os.path.exists(backup_file):
                Log.info("Trying to restore backup file %s" % backup_file)
                try:
                    return _try_openxmlfile(backup_file, root)
                except Exception as msg:
                    Log.warning('Failed with reason: %s' % msg)

        Log.info("No suitable backup was found")
        sys.exit(1)
Esempio n. 17
0
 def _when_taking_too_long(self):
     '''
     Function that is executed when the Dbus connection seems to be
     hanging. It disables the backend and signals the error to the user.
     '''
     Log.error("Dbus connection is taking too long for the Tomboy/Gnote"
               "backend!")
     BackendSignals().backend_failed(self.backend.get_id(),
                                     BackendSignals.ERRNO_DBUS)
     self.backend.quit(disable=True)
Esempio n. 18
0
 def _login(self):
     '''
     Tries to establish a connection to rtm with a token got from the
     authentication process
     '''
     try:
         self.rtm = createRTM(self.PUBLIC_KEY, self.PRIVATE_KEY, self.token)
         self.timeline = self.rtm.timelines.create().timeline
         return True
     except (RTMError, RTMAPIError), e:
         Log.error("RTM ERROR" + str(e))
 def _login(self):
     '''
     Tries to establish a connection to rtm with a token got from the
     authentication process
     '''
     try:
         self.rtm = createRTM(self.PUBLIC_KEY, self.PRIVATE_KEY, self.token)
         self.timeline = self.rtm.timelines.create().timeline
         return True
     except (RTMError, RTMAPIError), e:
         Log.error("RTM ERROR" + str(e))
Esempio n. 20
0
    def callMethod(self, aname, rargs, oargs, **params):
        # Sanity checks
        for requiredArg in rargs:
            if requiredArg not in params:
                raise TypeError(
                    'Required parameter (%s) missing' % requiredArg)

        for param in params:
            if param not in rargs + oargs:
                Log.error('Invalid parameter (%s)' % param)

        return self.rtm.get(method=aname,
                            auth_token=self.rtm.authInfo.get('token'),
                            **params)
Esempio n. 21
0
    def get_task(self, tid):
        '''
        Returns the internal task object for the given tid, or None if the
        tid is not present in this DataStore.

        @param tid: Task ID to retrieve
        @returns GTG.core.task.Task or None:  whether the Task is present
        or not
        '''
        if self.has_task(tid):
            return self.__tasks.get_node(tid)
        else:
            Log.error("requested non-existent task")
            return None
Esempio n. 22
0
    def callMethod(self, aname, rargs, oargs, **params):
        # Sanity checks
        for requiredArg in rargs:
            if requiredArg not in params:
                raise TypeError('Required parameter (%s) missing' %
                                requiredArg)

        for param in params:
            if param not in rargs + oargs:
                Log.error('Invalid parameter (%s)' % param)

        return self.rtm.get(method=aname,
                            auth_token=self.rtm.authInfo.get('token'),
                            **params)
Esempio n. 23
0
    def __load_icon(self):
        """
        Loads emblem icons from the current icon theme

        Sometimes an icon can't be loaded because of a bug in system
        libraries, e.g. bug #1079587. Gracefuly degradate and skip
        the loading of a corrupted icon.
        """
        self.symbol_model = gtk.ListStore(gtk.gdk.Pixbuf, str)
        for icon in gtk.icon_theme_get_default().list_icons(context="Emblems"):
            try:
                img = gtk.icon_theme_get_default().load_icon(icon, 16, 0)
                self.symbol_model.append([img, icon])
            except gobject.GError:
                Log.error("Failed to load icon '%s'" % icon)
        self.symbol_iv.set_model(self.symbol_model)
        self.loaded = True
Esempio n. 24
0
    def __load_icon(self):
        """
        Loads emblem icons from the current icon theme

        Sometimes an icon can't be loaded because of a bug in system
        libraries, e.g. bug #1079587. Gracefuly degradate and skip
        the loading of a corrupted icon.
        """
        self.symbol_model = Gtk.ListStore(GdkPixbuf.Pixbuf, str)
        for icon in Gtk.IconTheme.get_default().list_icons(context="Emblems"):
            try:
                img = Gtk.IconTheme.get_default().load_icon(icon, 16, 0)
                self.symbol_model.append([img, icon])
            except GObject.GError:
                Log.error("Failed to load icon '%s'" % icon)
        self.symbol_iv.set_model(self.symbol_model)
        self.loaded = True
Esempio n. 25
0
    def save(self, quit=False):
        """
        Saves the backends parameters.

        @param quit: If quit is true, backends are shut down
        """
        try:
            self.start_get_tasks_thread.join()
        except Exception:
            pass
        doc, xmlconfig = cleanxml.emptydoc("config")
        # we ask all the backends to quit first.
        if quit:
            # we quit backends in parallel
            threads_dic = {}
            for b in self.get_all_backends():
                thread = threading.Thread(target=b.quit)
                threads_dic[b.get_id()] = thread
                thread.start()
            for backend_id, thread in threads_dic.iteritems():
                # after 20 seconds, we give up
                thread.join(20)
                if thread.isAlive():
                    Log.error("The %s backend stalled while quitting",
                              backend_id)
        # we save the parameters
        for b in self.get_all_backends(disabled=True):
            t_xml = doc.createElement("backend")
            for key, value in b.get_parameters().iteritems():
                if key in ["backend", "xmlobject"]:
                    # We don't want parameters, backend, xmlobject:
                    # we'll create them at next startup
                    continue
                param_type = b.get_parameter_type(key)
                value = b.cast_param_type_to_string(param_type, value)
                t_xml.setAttribute(str(key), value)
            # Saving all the projects at close
            xmlconfig.appendChild(t_xml)
        datadir = CoreConfig().get_data_dir()
        datafile = os.path.join(datadir, CoreConfig.DATA_FILE)
        cleanxml.savexml(datafile, doc, backup=True)
        # Saving the tagstore
        self.save_tagtree()
Esempio n. 26
0
    def save(self, quit=False):
        """
        Saves the backends parameters.

        @param quit: If quit is true, backends are shut down
        """
        try:
            self.start_get_tasks_thread.join()
        except Exception:
            pass
        doc, xmlconfig = cleanxml.emptydoc("config")
        # we ask all the backends to quit first.
        if quit:
            # we quit backends in parallel
            threads_dic = {}
            for b in self.get_all_backends():
                thread = threading.Thread(target=b.quit)
                threads_dic[b.get_id()] = thread
                thread.start()
            for backend_id, thread in threads_dic.iteritems():
                # after 20 seconds, we give up
                thread.join(20)
                if thread.isAlive():
                    Log.error("The %s backend stalled while quitting",
                              backend_id)
        # we save the parameters
        for b in self.get_all_backends(disabled=True):
            t_xml = doc.createElement("backend")
            for key, value in b.get_parameters().iteritems():
                if key in ["backend", "xmlobject"]:
                    # We don't want parameters, backend, xmlobject:
                    # we'll create them at next startup
                    continue
                param_type = b.get_parameter_type(key)
                value = b.cast_param_type_to_string(param_type, value)
                t_xml.setAttribute(str(key), value)
            # Saving all the projects at close
            xmlconfig.appendChild(t_xml)
        datadir = CoreConfig().get_data_dir()
        datafile = os.path.join(datadir, CoreConfig.DATA_FILE)
        cleanxml.savexml(datafile, doc, backup=True)
        # Saving the tagstore
        self.save_tagtree()
Esempio n. 27
0
 def _load_module(self, module_path):
     """Load the module containing this plugin."""
     try:
         # import the module containing the plugin
         f, pathname, desc = imp.find_module(self.module_name, module_path)
         module = imp.load_module(self.module_name, f, pathname, desc)
         # find the class object for the actual plugin
         for key, item in module.__dict__.items():
             if isinstance(item, type):
                 self.plugin_class = item
                 self.class_name = item.__dict__['__module__'].split('.')[1]
                 break
     except ImportError as e:
         # load_module() failed, probably because of a module dependency
         if len(self.module_depends) > 0:
             self._check_module_depends()
         else:
             # no dependencies in info file; use the ImportError instead
             self.missing_modules.append(str(e).split(" ")[3])
         self.error = True
     except Exception as e:
         # load_module() failed for some other reason
         Log.error(e)
         self.error = True
Esempio n. 28
0
 def _load_module(self, module_paths):
     """Load the module containing this plugin."""
     try:
         # import the module containing the plugin
         f, pathname, desc = imp.find_module(self.module_name, module_paths)
         module = imp.load_module(self.module_name, f, pathname, desc)
         # find the class object for the actual plugin
         for key, item in module.__dict__.items():
             if isinstance(item, type):
                 self.plugin_class = item
                 self.class_name = item.__dict__['__module__'].split('.')[1]
                 break
     except ImportError as e:
         # load_module() failed, probably because of a module dependency
         if len(self.module_depends) > 0:
             self._check_module_depends()
         else:
             # no dependencies in info file; use the ImportError instead
             self.missing_modules.append(str(e).split(" ")[3])
         self.error = True
     except Exception as e:
         # load_module() failed for some other reason
         Log.error(e)
         self.error = True
Esempio n. 29
0
    def register_backend(self, backend_dic):
        """
        Registers a TaskSource as a backend for this DataStore

        @param backend_dic: Dictionary object containing all the
                            parameters to initialize the backend
                            (filename...). It should also contain the
                            backend class (under "backend"), and its
                            unique id (under "pid")
        """
        if "backend" in backend_dic:
            if "pid" not in backend_dic:
                Log.error("registering a backend without pid.")
                return None
            backend = backend_dic["backend"]
            # Checking that is a new backend
            if backend.get_id() in self.backends:
                Log.error("registering already registered backend")
                return None
            # creating the TaskSource which will wrap the backend,
            # filtering the tasks that should hit the backend.
            source = TaskSource(requester=self.requester,
                                backend=backend,
                                datastore=self.filtered_datastore)
            self.backends[backend.get_id()] = source
            # we notify that a new backend is present
            self._backend_signals.backend_added(backend.get_id())
            # saving the backend in the correct dictionary (backends for
            # enabled backends, disabled_backends for the disabled ones)
            # this is useful for retro-compatibility
            if GenericBackend.KEY_ENABLED not in backend_dic:
                source.set_parameter(GenericBackend.KEY_ENABLED, True)
            if GenericBackend.KEY_DEFAULT_BACKEND not in backend_dic:
                source.set_parameter(GenericBackend.KEY_DEFAULT_BACKEND, True)
            # if it's enabled, we initialize it
            if source.is_enabled() and \
                    (self.is_default_backend_loaded or source.is_default()):
                source.initialize(connect_signals=False)
                # Filling the backend
                # Doing this at start is more efficient than
                # after the GUI is launched
                source.start_get_tasks()
            return source
        else:
            Log.error("Tried to register a backend without a  pid")
Esempio n. 30
0
    def register_backend(self, backend_dic):
        """
        Registers a TaskSource as a backend for this DataStore

        @param backend_dic: Dictionary object containing all the
                            parameters to initialize the backend
                            (filename...). It should also contain the
                            backend class (under "backend"), and its
                            unique id (under "pid")
        """
        if "backend" in backend_dic:
            if "pid" not in backend_dic:
                Log.error("registering a backend without pid.")
                return None
            backend = backend_dic["backend"]
            # Checking that is a new backend
            if backend.get_id() in self.backends:
                Log.error("registering already registered backend")
                return None
            # creating the TaskSource which will wrap the backend,
            # filtering the tasks that should hit the backend.
            source = TaskSource(requester=self.requester,
                                backend=backend,
                                datastore=self.filtered_datastore)
            self.backends[backend.get_id()] = source
            # we notify that a new backend is present
            self._backend_signals.backend_added(backend.get_id())
            # saving the backend in the correct dictionary (backends for
            # enabled backends, disabled_backends for the disabled ones)
            # this is useful for retro-compatibility
            if not GenericBackend.KEY_ENABLED in backend_dic:
                source.set_parameter(GenericBackend.KEY_ENABLED, True)
            if not GenericBackend.KEY_DEFAULT_BACKEND in backend_dic:
                source.set_parameter(GenericBackend.KEY_DEFAULT_BACKEND, True)
            # if it's enabled, we initialize it
            if source.is_enabled() and \
                    (self.is_default_backend_loaded or source.is_default()):
                source.initialize(connect_signals=False)
                # Filling the backend
                # Doing this at start is more efficient than
                # after the GUI is launched
                source.start_get_tasks()
            return source
        else:
            Log.error("Tried to register a backend without a  pid")
Esempio n. 31
0
    def _load_pickled_file(self, path, default_value=None):
        '''
        A helper function to load some object from a file.

        @param path: the relative path of the file
        @param default_value: the value to return if the file is missing or
        corrupt
        @returns object: the needed object, or default_value
        '''
        path = os.path.join(CoreConfig().get_data_dir(), path)
        if not os.path.exists(path):
            return default_value

        with open(path, 'r') as file:
            try:
                return pickle.load(file)
            except Exception:
                Log.error("Pickle file for backend '%s' is damaged" %
                          self.get_name())

        # Loading file failed, trying backups
        for i in range(1, PICKLE_BACKUP_NBR + 1):
            backup_file = "%s.bak.%d" % (path, i)
            if os.path.exists(backup_file):
                with open(backup_file, 'r') as file:
                    try:
                        data = pickle.load(file)
                        Log.info("Succesfully restored backup #%d for '%s'" %
                                 (i, self.get_name()))
                        return data
                    except Exception:
                        Log.error("Backup #%d for '%s' is damaged as well" %
                                  (i, self.get_name()))

        # Data could not be loaded, degrade to default data
        Log.error("There is no suitable backup for '%s', "
                  "loading default data" % self.get_name())
        return default_value
Esempio n. 32
0
    def _load_pickled_file(self, path, default_value=None):
        '''
        A helper function to load some object from a file.

        @param path: the relative path of the file
        @param default_value: the value to return if the file is missing or
        corrupt
        @returns object: the needed object, or default_value
        '''
        path = os.path.join(CoreConfig().get_data_dir(), path)
        if not os.path.exists(path):
            return default_value

        with open(path, 'r') as file:
            try:
                return pickle.load(file)
            except Exception:
                Log.error("Pickle file for backend '%s' is damaged" %
                          self.get_name())

        # Loading file failed, trying backups
        for i in range(1, PICKLE_BACKUP_NBR + 1):
            backup_file = "%s.bak.%d" % (path, i)
            if os.path.exists(backup_file):
                with open(backup_file, 'r') as file:
                    try:
                        data = pickle.load(file)
                        Log.info("Succesfully restored backup #%d for '%s'" %
                                (i, self.get_name()))
                        return data
                    except Exception:
                        Log.error("Backup #%d for '%s' is damaged as well" %
                                 (i, self.get_name()))

        # Data could not be loaded, degrade to default data
        Log.error("There is no suitable backup for '%s', "
                  "loading default data" % self.get_name())
        return default_value
Esempio n. 33
0
 def _callback(self, name, *args):
     """ Trigger a callback defined by its name and pass arguments """
     if name in self._callbacks:
         self._callbacks[name](*args)
     else:
         Log.error("Unknown callback '%s'(%s)" % (name, args))
Esempio n. 34
0
def openxmlfile(zefile, root):
    """ Open an XML file in a robust way

    If file could not be opened, try:
        - file__
        - file.bak.0
        - file.bak.1
        - .... until BACKUP_NBR

    If file doesn't exist, create a new file """

    # reset _USED_BACKUP and _BACKUP_FILE_INFO
    global _USED_BACKUP
    global _BACKUP_FILE_INFO
    _USED_BACKUP = False
    _BACKUP_FILE_INFO = ""
    tmpfile = zefile + '__'
    try:
        if os.path.exists(zefile):
            return _try_openxmlfile(zefile, root)
        elif os.path.exists(tmpfile):
            Log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            _USED_BACKUP = True
            _BACKUP_FILE_INFO = "Recovered from backup made on: " + \
                datetime.datetime.fromtimestamp(
                    os.path.getmtime(tmpfile)).strftime('%Y-%m-%d')
            return _try_openxmlfile(zefile, root)

    except IOError as msg:
        print(msg)
        sys.exit(1)

    except xml.parsers.expat.ExpatError as msg:
        errormsg = "Error parsing XML file %s: %s" % (zefile, msg)
        Log.error(errormsg)
        if os.path.exists(tmpfile):
            Log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            _USED_BACKUP = True
            _BACKUP_FILE_INFO = "Recovered from backup made on: " + \
                datetime.datetime.fromtimestamp(
                    os.path.getmtime(tmpfile)).strftime('%Y-%m-%d')
            # Ok, try one more time now
            try:
                return _try_openxmlfile(zefile, root)
            except Exception as msg:
                Log.warning('Failed with reason: %s' % msg)

    # Try to revert to backup
    backup_name = _get_backup_name(zefile)
    for i in range(BACKUP_NBR):
        backup_file = "%s.bak.%d" % (backup_name, i)
        if os.path.exists(backup_file):
            Log.info("Trying to restore backup file %s" % backup_file)
            _USED_BACKUP = True
            _BACKUP_FILE_INFO = "Recovered from backup made on: " + \
                datetime.datetime.fromtimestamp(
                    os.path.getmtime(backup_file)).strftime('%Y-%m-%d')
            try:
                return _try_openxmlfile(backup_file, root)
            except Exception as msg:
                Log.warning('Failed with reason: %s' % msg)

    Log.info("No suitable backup was found")

    # Creating empty file
    doc, xmlproject = emptydoc(root)
    newfile = savexml(zefile, doc)
    if not newfile:
        Log.error("Could not create a new file %s" % zefile)
        sys.exit(1)
    # set _USED_BACKUP even if there's a failure to notify about the same
    _USED_BACKUP = True
    _BACKUP_FILE_INFO = "No backups found. Created a new file"
    return _try_openxmlfile(zefile, root)

    # exit if execution reached this statement
    sys.exit(1)
Esempio n. 35
0
class Plugin(object):
    """A class to represent a plugin."""

    # A reference to an instance of the plugin class
    instance = None
    # True if the plugin has been enabled by the user.
    enabled = False
    # True if some error prevents the plugin from being activated.
    error = False
    # True if the plugin is actually loaded and running.
    _active = False
    missing_modules = []
    missing_dbus = []

    def __init__(self, info, module_path):
        """Initialize the Plugin using a ConfigObj."""
        info_fields = {
            'module_name': 'Module',
            'full_name': 'Name',
            'version': 'Version',
            'authors': 'Authors',
            'short_description': 'Short-description',
            'description': 'Description',
            'module_depends': 'Dependencies',
            'dbus_depends': 'Dbus-dependencies',
        }
        for attr, field in info_fields.iteritems():
            try:
                setattr(self, attr, info[field])
            except KeyError:
                setattr(self, attr, [])
        # turn the enabled attribute into a bool
        self.enabled = info['Enabled'].lower() == "true"
        # ensure the dbus dependencies are a list
        if isinstance(self.dbus_depends, str):
            self.dbus_depends = [self.dbus_depends]
        self._load_module(module_path)
        self._check_dbus_depends()

    # 'active' property
    def _get_active(self):
        return self._active

    def _set_active(self, value):
        if value:
            self.instance = self.plugin_class()
        else:
            self.instance = None
        self._active = value

    active = property(_get_active, _set_active)

    def _check_dbus_depends(self):
        """Check the availability of DBus interfaces this plugin depends on."""
        self.missing_dbus = []
        for dbobj in self.dbus_depends:
            if dbobj.find(':'):
                bus, obj_path = dbobj.split(':')
                try:
                    dbus.SessionBus().get_object(bus, obj_path)
                except Exception:
                    self.missing_dbus.append(dbobj.split(':'))
                    self.error = True
            else:
                if dbobj:
                    self.missing_dbus.append(dbobj)
                    self.error = True

    def _check_module_depends(self):
        """Check the availability of modules this plugin depends on."""
        self.missing_modules = []
        for mod_name in self.module_depends:
            try:
                __import__(mod_name)
            except:
                self.missing_modules.append(mod_name)
                self.error = True

    def is_configurable(self):
        """Since some plugins don't have a is_configurable() method."""
        return self.instance and hasattr(self.instance, 'is_configurable') and\
            self.instance.is_configurable()

    def _load_module(self, module_path):
        """Load the module containing this plugin."""
        try:
            # import the module containing the plugin
            f, pathname, desc = imp.find_module(self.module_name, module_path)
            module = imp.load_module(self.module_name, f, pathname, desc)
            # find the class object for the actual plugin
            for key, item in module.__dict__.iteritems():
                if isinstance(item, types.ClassType):
                    self.plugin_class = item
                    self.class_name = item.__dict__['__module__'].split('.')[1]
                    break
        except ImportError, e:
            # load_module() failed, probably because of a module dependency
            if len(self.module_depends) > 0:
                self._check_module_depends()
            else:
                # no dependencies in info file; use the ImportError instead
                self.missing_modules.append(str(e).split(" ")[3])
            self.error = True
        except Exception, e:
            # load_module() failed for some other reason
            Log.error(e)
            self.error = True
Esempio n. 36
0
def openxmlfile(zefile, root):
    """ Open an XML file in a robust way

    If file could not be opened, try:
        - file__
        - file.bak.0
        - file.bak.1
        - .... until BACKUP_NBR

    If file doesn't exist, create a new file """

    # reset _USED_BACKUP and _BACKUP_FILE_INFO
    global _USED_BACKUP
    global _BACKUP_FILE_INFO
    _USED_BACKUP = False
    _BACKUP_FILE_INFO = ""
    tmpfile = zefile + '__'
    try:
        if os.path.exists(zefile):
            return _try_openxmlfile(zefile, root)
        elif os.path.exists(tmpfile):
            Log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            _USED_BACKUP = True
            _BACKUP_FILE_INFO = "Recovered from backup made on: " + \
                datetime.datetime.fromtimestamp(
                    os.path.getmtime(tmpfile)).strftime('%Y-%m-%d')
            return _try_openxmlfile(zefile, root)

    except IOError as msg:
        print(msg)
        sys.exit(1)

    except xml.parsers.expat.ExpatError as msg:
        errormsg = "Error parsing XML file %s: %s" % (zefile, msg)
        Log.error(errormsg)
        if os.path.exists(tmpfile):
            Log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            _USED_BACKUP = True
            _BACKUP_FILE_INFO = "Recovered from backup made on: " + \
                datetime.datetime.fromtimestamp(
                    os.path.getmtime(tmpfile)).strftime('%Y-%m-%d')
            # Ok, try one more time now
            try:
                return _try_openxmlfile(zefile, root)
            except Exception as msg:
                Log.warning('Failed with reason: %s' % msg)

    # Try to revert to backup
    backup_name = _get_backup_name(zefile)
    for i in range(BACKUP_NBR):
        backup_file = "%s.bak.%d" % (backup_name, i)
        if os.path.exists(backup_file):
            Log.info("Trying to restore backup file %s" % backup_file)
            _USED_BACKUP = True
            _BACKUP_FILE_INFO = "Recovered from backup made on: " + \
                datetime.datetime.fromtimestamp(
                    os.path.getmtime(backup_file)).strftime('%Y-%m-%d')
            try:
                return _try_openxmlfile(backup_file, root)
            except Exception as msg:
                Log.warning('Failed with reason: %s' % msg)

    Log.info("No suitable backup was found")

    # Creating empty file
    doc, xmlproject = emptydoc(root)
    newfile = savexml(zefile, doc)
    if not newfile:
        Log.error("Could not create a new file %s" % zefile)
        sys.exit(1)
    # set _USED_BACKUP even if there's a failure to notify about the same
    _USED_BACKUP = True
    _BACKUP_FILE_INFO = "No backups found. Created a new file"
    return _try_openxmlfile(zefile, root)

    # exit if execution reached this statement
    sys.exit(1)
Esempio n. 37
0
        else:
            # Creating empty file
            doc, xmlproject = emptydoc(root)
            newfile = savexml(zefile, doc)
            if not newfile:
                Log.error("Could not create a new file %s" % zefile)
                sys.exit(1)
            return _try_openxmlfile(zefile, root)

    except IOError, msg:
        print msg
        sys.exit(1)

    except xml.parsers.expat.ExpatError, msg:
        errormsg = "Error parsing XML file %s: %s" % (zefile, msg)
        Log.error(errormsg)
        if os.path.exists(tmpfile):
            Log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            # Ok, try one more time now
            try:
                return _try_openxmlfile(zefile, root)
            except Exception, msg:
                Log.warning('Failed with reason: %s' % msg)

        # Try to revert to backup
        backup_name = _get_backup_name(zefile)
        for i in range(BACKUP_NBR):
            backup_file = "%s.bak.%d" % (backup_name, i)
            if os.path.exists(backup_file):
                Log.info("Trying to restore backup file %s" % backup_file)
Esempio n. 38
0
    def on_render(self, window, widget, background_area, cell_area,
                  expose_area, flags):

        vw_tags = self.__count_viewable_tags()
        count = 0

        # Select source
        if self.tag_list is not None:
            tags = self.tag_list
        elif self.tag is not None:
            tags = [self.tag]
        else:
            return

        # Drawing context
        cr = window.cairo_create()
        gdkcontext = gtk.gdk.CairoContext(cr)
        gdkcontext.set_antialias(cairo.ANTIALIAS_NONE)

        # Coordinates of the origin point
        x_align = self.get_property("xalign")
        y_align = self.get_property("yalign")
        padding = self.PADDING
        orig_x = cell_area.x + int(
            (cell_area.width - 16 * vw_tags - padding * 2 *
             (vw_tags - 1)) * x_align)
        orig_y = cell_area.y + int((cell_area.height - 16) * y_align)

        # We draw the icons & squares
        for my_tag in tags:

            my_tag_icon = my_tag.get_attribute("icon")
            my_tag_color = my_tag.get_attribute("color")

            rect_x = orig_x + self.PADDING * 2 * count + 16 * count
            rect_y = orig_y

            if my_tag_icon:
                try:
                    pixbuf = gtk.icon_theme_get_default().load_icon(
                        my_tag_icon, 16, 0)
                    gdkcontext.set_source_pixbuf(pixbuf, rect_x, rect_y)
                    gdkcontext.paint()
                    count = count + 1
                except glib.GError:
                    # In some rare cases an icon could not be found
                    # (e.g. wrong set icon path, missing icon)
                    # Raising an exception breaks UI and signal catcher badly
                    Log.error("Can't load icon '%s'" % my_tag_icon)

            elif my_tag_color:

                # Draw rounded rectangle
                my_color = gtk.gdk.color_parse(my_tag_color)
                gdkcontext.set_source_color(my_color)
                self.__roundedrec(gdkcontext, rect_x, rect_y, 16, 16, 8)
                gdkcontext.fill()
                count = count + 1

                # Outer line
                gdkcontext.set_source_rgba(0, 0, 0, 0.20)
                gdkcontext.set_line_width(1.0)
                self.__roundedrec(gdkcontext, rect_x, rect_y, 16, 16, 8)
                gdkcontext.stroke()

        if self.tag and my_tag:

            my_tag_icon = my_tag.get_attribute("icon")
            my_tag_color = my_tag.get_attribute("color")

            if not my_tag_icon and not my_tag_color:
                # Draw rounded rectangle
                gdkcontext.set_source_rgba(0.95, 0.95, 0.95, 1)
                self.__roundedrec(gdkcontext, rect_x, rect_y, 16, 16, 8)
                gdkcontext.fill()

                # Outer line
                gdkcontext.set_source_rgba(0, 0, 0, 0.20)
                gdkcontext.set_line_width(1.0)
                self.__roundedrec(gdkcontext, rect_x, rect_y, 16, 16, 8)
                gdkcontext.stroke()
Esempio n. 39
0
 def _callback(self, name, *args):
     """ Trigger a callback defined by its name and pass arguments """
     if name in self._callbacks:
         self._callbacks[name](*args)
     else:
         Log.error("Unknown callback '%s'(%s)" % (name, args))
Esempio n. 40
0
    def do_render(self, cr, widget, background_area, cell_area, flags):

        vw_tags = self.__count_viewable_tags()
        count = 0

        # Select source
        if self.tag_list is not None:
            tags = self.tag_list
        elif self.tag is not None:
            tags = [self.tag]
        else:
            return

        # Drawing context
        gdkcontext = cr
        gdkcontext.set_antialias(cairo.ANTIALIAS_NONE)

        # Coordinates of the origin point
        x_align = self.get_property("xalign")
        y_align = self.get_property("yalign")
        padding = self.PADDING
        orig_x = cell_area.x + int((cell_area.width - 16 * vw_tags -
                                    padding * 2 * (vw_tags - 1)) * x_align)
        orig_y = cell_area.y + int((cell_area.height - 16) * y_align)

        # We draw the icons & squares
        for my_tag in tags:

            my_tag_icon = my_tag.get_attribute("icon")
            my_tag_color = my_tag.get_attribute("color")

            rect_x = orig_x + self.PADDING * 2 * count + 16 * count
            rect_y = orig_y

            if my_tag_icon:
                try:
                    pixbuf = Gtk.IconTheme.get_default().load_icon(
                        my_tag_icon, 16, 0)
                    Gdk.cairo_set_source_pixbuf(gdkcontext, pixbuf,
                                                rect_x, rect_y)
                    gdkcontext.paint()
                    count = count + 1
                except GLib.GError:
                    # In some rare cases an icon could not be found
                    # (e.g. wrong set icon path, missing icon)
                    # Raising an exception breaks UI and signal catcher badly
                    Log.error("Can't load icon '%s'" % my_tag_icon)

            elif my_tag_color:

                # Draw rounded rectangle
                my_color = Gdk.color_parse(my_tag_color)
                Gdk.cairo_set_source_color(gdkcontext, my_color)
                self.__roundedrec(gdkcontext, rect_x, rect_y, 16, 16, 8)
                gdkcontext.fill()
                count = count + 1

                # Outer line
                Gdk.cairo_set_source_rgba(gdkcontext, Gdk.RGBA(0, 0, 0, 0.20))
                gdkcontext.set_line_width(1.0)
                self.__roundedrec(gdkcontext, rect_x, rect_y, 16, 16, 8)
                gdkcontext.stroke()

        if self.tag and my_tag:

            my_tag_icon = my_tag.get_attribute("icon")
            my_tag_color = my_tag.get_attribute("color")

            if not my_tag_icon and not my_tag_color:
                # Draw rounded rectangle
                Gdk.cairo_set_source_rgba(gdkcontext,
                                          Gdk.RGBA(0.95, 0.95, 0.95, 1))
                self.__roundedrec(gdkcontext, rect_x, rect_y, 16, 16, 8)
                gdkcontext.fill()

                # Outer line
                Gdk.cairo_set_source_rgba(gdkcontext, Gdk.RGBA(0, 0, 0, 0.20))
                gdkcontext.set_line_width(1.0)
                self.__roundedrec(gdkcontext, rect_x, rect_y, 16, 16, 8)
                gdkcontext.stroke()
Esempio n. 41
0
        else:
            # Creating empty file
            doc, xmlproject = emptydoc(root)
            newfile = savexml(zefile, doc)
            if not newfile:
                Log.error("Could not create a new file %s" % zefile)
                sys.exit(1)
            return _try_openxmlfile(zefile, root)

    except IOError, msg:
        print msg
        sys.exit(1)

    except xml.parsers.expat.ExpatError, msg:
        errormsg = "Error parsing XML file %s: %s" % (zefile, msg)
        Log.error(errormsg)
        if os.path.exists(tmpfile):
            Log.warning("Something happened to %s. Using backup" % zefile)
            os.rename(tmpfile, zefile)
            # Ok, try one more time now
            try:
                return _try_openxmlfile(zefile, root)
            except Exception, msg:
                Log.warning('Failed with reason: %s' % msg)

        # Try to revert to backup
        backup_name = _get_backup_name(zefile)
        for i in range(BACKUP_NBR):
            backup_file = "%s.bak.%d" % (backup_name, i)
            if os.path.exists(backup_file):
                Log.info("Trying to restore backup file %s" % backup_file)