Ejemplo n.º 1
0
    def __export_task(self, path, one_file=True):
        ntables = len(db.metadata.tables)
        steps_so_far = 0
        if not one_file:
            tableset_el = etree.Element("tableset")

        for table_name, table in tables.iteritems():
            if one_file:
                tableset_el = etree.Element("tableset")
            info("exporting %s..." % table_name)
            table_el = ElementFactory(tableset_el, "table", attrib={"name": table_name})
            results = table.select().execute().fetchall()
            columns = table.c.keys()
            try:
                for row in results:
                    row_el = ElementFactory(table_el, "row")
                    for col in columns:
                        ElementFactory(row_el, "column", attrib={"name": col}, text=row[col])
            except ValueError, e:
                utils.message_details_dialog(utils.xml_safe_utf8(e), traceback.format_exc(), gtk.MESSAGE_ERROR)
                return
            else:
                if one_file:
                    tree = etree.ElementTree(tableset_el)
                    filename = os.path.join(path, "%s.xml" % table_name)
                    # TODO: can figure out why this keeps crashing
                    tree.write(filename, encoding="utf8", xml_declaration=True)
 def handle_response(self, response, commit=True):
     '''
     handle the response from self.presenter.start() in self.start()
     '''
     not_ok_msg = 'Are you sure you want to lose your changes?'
     self._return = None
     self.clean_model()
     if response == gtk.RESPONSE_OK or response in self.ok_responses:
         try:
             self._return = self.model
             if self.presenter.dirty() and commit:
                 self.commit_changes()
         except DBAPIError, e:
             msg = _('Error committing changes.\n\n%s') % \
                 utils.xml_safe(unicode(e.orig))
             utils.message_details_dialog(msg, str(e), gtk.MESSAGE_ERROR)
             self.session.rollback()
             return False
         except Exception, e:
             msg = _('Unknown error when committing changes. See the '
                     'details for more information.\n\n%s') %\
                 utils.xml_safe(e)
             logger.debug(traceback.format_exc())
             utils.message_details_dialog(msg, traceback.format_exc(),
                                          gtk.MESSAGE_ERROR)
             self.session.rollback()
             return False
Ejemplo n.º 3
0
def remove_callback(genera):
    """
    The callback function to remove a genus from the genus context menu.
    """
    genus = genera[0]
    from bauble.plugins.plants.species_model import Species
    session = db.Session()
    nsp = session.query(Species).filter_by(genus_id=genus.id).count()
    safe_str = utils.xml_safe(str(genus))
    if nsp > 0:
        msg = (_('The genus <i>%(genus)s</i> has %(num_species)s species.  '
                 'Are you sure you want to remove it?') %
               dict(genus=safe_str, num_species=nsp))
    else:
        msg = (_("Are you sure you want to remove the genus <i>%s</i>?") %
               safe_str)
    if not utils.yes_no_dialog(msg):
        return
    try:
        obj = session.query(Genus).get(genus.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg,
                                     traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
Ejemplo n.º 4
0
    def __export_task(self, path, one_file=True):
        if not one_file:
            tableset_el = etree.Element('tableset')

        for table_name, table in db.metadata.tables.iteritems():
            if one_file:
                tableset_el = etree.Element('tableset')
            logger.info('exporting %s...' % table_name)
            table_el = ElementFactory(tableset_el, 'table',
                                      attrib={'name': table_name})
            results = table.select().execute().fetchall()
            columns = table.c.keys()
            try:
                for row in results:
                    row_el = ElementFactory(table_el, 'row')
                    for col in columns:
                        ElementFactory(row_el, 'column', attrib={'name': col},
                                       text=row[col])
            except ValueError, e:
                utils.message_details_dialog(utils.xml_safe(e),
                                             traceback.format_exc(),
                                             gtk.MESSAGE_ERROR)
                return
            else:
                if one_file:
                    tree = etree.ElementTree(tableset_el)
                    filename = os.path.join(path, '%s.xml' % table_name)
                    # TODO: can figure out why this keeps crashing
                    tree.write(filename, encoding='utf8', xml_declaration=True)
Ejemplo n.º 5
0
def remove_callback(genera):
    """
    The callback function to remove a genus from the genus context menu.
    """
    genus = genera[0]
    from bauble.plugins.plants.species_model import Species
    session = db.Session()
    nsp = session.query(Species).filter_by(genus_id=genus.id).count()
    safe_str = utils.xml_safe(str(genus))
    if nsp > 0:
        msg = (_('The genus <i>%(genus)s</i> has %(num_species)s species.  '
                 'Are you sure you want to remove it?')
               % dict(genus=safe_str, num_species=nsp))
    else:
        msg = (_("Are you sure you want to remove the genus <i>%s</i>?")
               % safe_str)
    if not utils.yes_no_dialog(msg):
        return
    try:
        obj = session.query(Genus).get(genus.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
Ejemplo n.º 6
0
 def handle_response(self, response):
     """
     @return: return True if the editor is ready to be closed, False if
     we want to keep editing, if any changes are committed they are stored
     in self._committed
     """
     # TODO: need to do a __cleanup_model before the commit to do things
     # like remove the insfraspecific information that's attached to the
     # model if the infraspecific rank is None
     not_ok_msg = 'Are you sure you want to lose your changes?'
     if response == gtk.RESPONSE_OK or response in self.ok_responses:
         try:
             if self.presenter.is_dirty():
                 self.commit_changes()
                 self._committed.append(self.model)
         except DBAPIError, e:
             msg = _('Error committing changes.\n\n%s') % \
                 utils.xml_safe(e.orig)
             logger.debug(traceback.format_exc())
             utils.message_details_dialog(msg, str(e), gtk.MESSAGE_ERROR)
             return False
         except Exception, e:
             msg = _('Unknown error when committing changes. See the '
                     'details for more information.\n\n%s') % \
                 utils.xml_safe(e)
             logger.debug(traceback.format_exc())
             utils.message_details_dialog(msg, traceback.format_exc(),
                                          gtk.MESSAGE_ERROR)
             return False
Ejemplo n.º 7
0
    def __export_task(self, path, one_file=True):
        if not one_file:
            tableset_el = etree.Element('tableset')

        for table_name, table in db.metadata.tables.iteritems():
            if one_file:
                tableset_el = etree.Element('tableset')
            logger.info('exporting %s...' % table_name)
            table_el = ElementFactory(tableset_el,
                                      'table',
                                      attrib={'name': table_name})
            results = table.select().execute().fetchall()
            columns = table.c.keys()
            try:
                for row in results:
                    row_el = ElementFactory(table_el, 'row')
                    for col in columns:
                        ElementFactory(row_el,
                                       'column',
                                       attrib={'name': col},
                                       text=row[col])
            except ValueError, e:
                utils.message_details_dialog(utils.xml_safe(e),
                                             traceback.format_exc(),
                                             gtk.MESSAGE_ERROR)
                return
            else:
                if one_file:
                    tree = etree.ElementTree(tableset_el)
                    filename = os.path.join(path, '%s.xml' % table_name)
                    # TODO: can figure out why this keeps crashing
                    tree.write(filename, encoding='utf8', xml_declaration=True)
Ejemplo n.º 8
0
    def start(self):
        '''
        '''
        # get the select results from the search view
        from bauble.view import SearchView
        view = bauble.gui.get_view()
        if not isinstance(view, SearchView):
            utils.message_dialog(_('Search for something first.'))
            return

        model = view.results_view.get_model()
        if model is None:
            utils.message_dialog(_('Search for something first.'))
            return

        bauble.gui.set_busy(True)
        ok = False
        try:
            while True:
                dialog = ReportToolDialog()
                formatter, settings = dialog.start()
                if formatter is None:
                    break
                ok = formatter.format([row[0] for row in model], **settings)
                if ok:
                    break
        except AssertionError, e:
            logger.debug(e)
            logger.debug(traceback.format_exc())
            parent = None
            if hasattr(self, 'view') and hasattr(self.view, 'dialog'):
                parent = self.view.dialog

            utils.message_details_dialog(str(e), traceback.format_exc(),
                                         gtk.MESSAGE_ERROR, parent=parent)
Ejemplo n.º 9
0
    def start(self):
        '''
        '''
        # get the select results from the search view
        from bauble.view import SearchView
        view = bauble.gui.get_view()
        if not isinstance(view, SearchView):
            utils.message_dialog(_('Search for something first.'))
            return

        model = view.results_view.get_model()
        if model is None:
            utils.message_dialog(_('Search for something first.'))
            return

        bauble.gui.set_busy(True)
        ok = False
        try:
            while True:
                dialog = ReportToolDialog()
                formatter, settings = dialog.start()
                if formatter is None:
                    break
                ok = formatter.format([row[0] for row in model], **settings)
                if ok:
                    break
        except AssertionError, e:
            debug(e)
            debug(traceback.format_exc())
            parent = None
            if hasattr(self, 'view') and hasattr(self.view, 'dialog'):
                parent = self.view.dialog

            utils.message_details_dialog(str(e), traceback.format_exc(),
                                         gtk.MESSAGE_ERROR, parent=parent)
Ejemplo n.º 10
0
def _reset_tags_menu():
    tags_menu = gtk.Menu()
    add_tag_menu_item = gtk.MenuItem(_('Tag Selection'))
    add_tag_menu_item.connect('activate', _on_add_tag_activated)
    accel_group = gtk.AccelGroup()
    bauble.gui.window.add_accel_group(accel_group)
    add_tag_menu_item.add_accelerator('activate', accel_group, ord('T'),
                                      gtk.gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE)
    tags_menu.append(add_tag_menu_item)

    #manage_tag_item = gtk.MenuItem('Manage Tags')
    #tags_menu.append(manage_tag_item)
    tags_menu.append(gtk.SeparatorMenuItem())
    session = db.Session()
    query = session.query(Tag)
    try:
        for tag in query:
            item = gtk.MenuItem(tag.tag, use_underline=False)
            item.connect("activate", _tag_menu_item_activated, tag.tag)
            tags_menu.append(item)
    except Exception:
        logger.debug(traceback.format_exc())
        msg = _('Could not create the tags menus')
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     gtk.MESSAGE_ERROR)

    global _tags_menu_item
    if _tags_menu_item is None:
        _tags_menu_item = bauble.gui.add_menu(_("Tags"), tags_menu)
    else:
        _tags_menu_item.remove_submenu()
        _tags_menu_item.set_submenu(tags_menu)
        _tags_menu_item.show_all()
    session.close()
Ejemplo n.º 11
0
def remove_callback(families):
    """
    The callback function to remove a family from the family context menu.
    """
    family = families[0]
    from bauble.plugins.plants.genus import Genus
    session = db.Session()
    ngen = session.query(Genus).filter_by(family_id=family.id).count()
    safe_str = utils.xml_safe(str(family))
    if ngen > 0:
        msg = _('The family <i>%(family)s</i> has %(num_genera)s genera.  Are '
                'you sure you want to remove it?') % dict(family=safe_str,
                                                          num_genera=ngen)
    else:
        msg = _("Are you sure you want to remove the family <i>%s</i>?") \
            % safe_str
    if not utils.yes_no_dialog(msg):
        return
    try:
        obj = session.query(Family).get(family.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg,
                                     traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
Ejemplo n.º 12
0
def remove_callback(families):
    """
    The callback function to remove a family from the family context menu.
    """
    family = families[0]
    from bauble.plugins.plants.genus import Genus
    session = db.Session()
    ngen = session.query(Genus).filter_by(family_id=family.id).count()
    safe_str = utils.xml_safe_utf8(str(family))
    if ngen > 0:
        msg = _('The family <i>%(family)s</i> has %(num_genera)s genera.  Are '
                'you sure you want to remove it?') % dict(family=safe_str,
                                                          num_genera=ngen)
    else:
        msg = _("Are you sure you want to remove the family <i>%s</i>?") \
            % safe_str
    if not utils.yes_no_dialog(msg):
        return
    try:
        obj = session.query(Family).get(family.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe_utf8(e)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
Ejemplo n.º 13
0
def remove_callback(values):
    """
    The callback function to remove a species from the species context menu.
    """
    from bauble.plugins.garden.accession import Accession

    session = db.Session()
    species = values[0]
    if isinstance(species, VernacularName):
        species = species.species
    nacc = session.query(Accession).filter_by(species_id=species.id).count()
    safe_str = utils.xml_safe(str(species))
    if nacc > 0:
        msg = _(
            "The species <i>%(species)s</i> has %(num_accessions)s " "accessions.  Are you sure you want remove it?"
        ) % dict(species=safe_str, num_accessions=nacc)
    else:
        msg = _("Are you sure you want to remove the species <i>%s</i>?") % safe_str
    if not utils.yes_no_dialog(msg):
        return
    try:
        obj = session.query(Species).get(species.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _("Could not delete.\n\n%s") % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(), type=gtk.MESSAGE_ERROR)
Ejemplo n.º 14
0
 def on_key_released(self, widget, event):
     '''
     if the user hits the delete key on a selected tag in the tag editor
     then delete the tag
     '''
     keyname = gtk.gdk.keyval_name(event.keyval)
     if keyname != "Delete":
         return
     model, row_iter = self.tag_tree.get_selection().get_selected()
     tag_name = model[row_iter][1]
     msg = _('Are you sure you want to delete the tag "%s"?') % tag_name
     if not utils.yes_no_dialog(msg):
         return
     session = db.Session()
     try:
         query = session.query(Tag)
         tag = query.filter_by(tag=unicode(tag_name)).one()
         session.delete(tag)
         session.commit()
         model.remove(row_iter)
         _reset_tags_menu()
         view = bauble.gui.get_view()
         if hasattr(view, 'update'):
             view.update()
     except Exception, e:
         utils.message_details_dialog(utils.xml_safe(str(e)),
                                      traceback.format_exc(),
                                      gtk.MESSAGE_ERROR)
Ejemplo n.º 15
0
 def on_key_released(self, widget, event):
     '''
     if the user hits the delete key on a selected tag in the tag editor
     then delete the tag
     '''
     keyname = gtk.gdk.keyval_name(event.keyval)
     if keyname != "Delete":
         return
     model, row_iter = self.tag_tree.get_selection().get_selected()
     tag_name = model[row_iter][1]
     msg = _('Are you sure you want to delete the tag "%s"?') % tag_name
     if not utils.yes_no_dialog(msg):
         return
     session = db.Session()
     try:
         query = session.query(Tag)
         tag = query.filter_by(tag=unicode(tag_name)).one()
         session.delete(tag)
         session.commit()
         model.remove(row_iter)
         _reset_tags_menu()
         view = bauble.gui.get_view()
         if hasattr(view, 'update'):
             view.update()
     except Exception, e:
         utils.message_details_dialog(utils.xml_safe(str(e)),
                                      traceback.format_exc(),
                                      gtk.MESSAGE_ERROR)
Ejemplo n.º 16
0
def _reset_tags_menu():
    tags_menu = gtk.Menu()
    add_tag_menu_item = gtk.MenuItem(_('Tag Selection'))
    add_tag_menu_item.connect('activate', _on_add_tag_activated)
    accel_group = gtk.AccelGroup()
    bauble.gui.window.add_accel_group(accel_group)
    add_tag_menu_item.add_accelerator('activate', accel_group, ord('T'),
                                      gtk.gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE)
    tags_menu.append(add_tag_menu_item)

    #manage_tag_item = gtk.MenuItem('Manage Tags')
    #tags_menu.append(manage_tag_item)
    tags_menu.append(gtk.SeparatorMenuItem())
    session = db.Session()
    query = session.query(Tag)
    try:
        for tag in query:
            item = gtk.MenuItem(tag.tag, use_underline=False)
            item.connect("activate", _tag_menu_item_activated, tag.tag)
            tags_menu.append(item)
    except Exception:
        logger.debug(traceback.format_exc())
        msg = _('Could not create the tags menus')
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     gtk.MESSAGE_ERROR)

    global _tags_menu_item
    if _tags_menu_item is None:
        _tags_menu_item = bauble.gui.add_menu(_("Tags"), tags_menu)
    else:
        _tags_menu_item.remove_submenu()
        _tags_menu_item.set_submenu(tags_menu)
        _tags_menu_item.show_all()
    session.close()
Ejemplo n.º 17
0
 def handle_response(self, response):
     """
     @return: return True if the editor is ready to be closed, False if
     we want to keep editing, if any changes are committed they are stored
     in self._committed
     """
     # TODO: need to do a __cleanup_model before the commit to do things
     # like remove the insfraspecific information that's attached to the
     # model if the infraspecific rank is None
     not_ok_msg = 'Are you sure you want to lose your changes?'
     if response == gtk.RESPONSE_OK or response in self.ok_responses:
         try:
             if self.presenter.is_dirty():
                 self.commit_changes()
                 self._committed.append(self.model)
         except DBAPIError, e:
             msg = _('Error committing changes.\n\n%s') % \
                 utils.xml_safe(e.orig)
             logger.debug(traceback.format_exc())
             utils.message_details_dialog(msg, str(e), gtk.MESSAGE_ERROR)
             return False
         except Exception, e:
             msg = _('Unknown error when committing changes. See the '
                     'details for more information.\n\n%s') % \
                 utils.xml_safe(e)
             logger.debug(traceback.format_exc())
             utils.message_details_dialog(msg, traceback.format_exc(),
                                          gtk.MESSAGE_ERROR)
             return False
Ejemplo n.º 18
0
def remove_callback(values):
    """
    The callback function to remove a species from the species context menu.
    """
    from bauble.plugins.garden.accession import Accession
    session = db.Session()
    species = values[0]
    if isinstance(species, VernacularName):
        species = species.species
    nacc = session.query(Accession).filter_by(species_id=species.id).count()
    safe_str = utils.xml_safe(str(species))
    if nacc > 0:
        msg = _('The species <i>%(species)s</i> has %(num_accessions)s '
                'accessions.  Are you sure you want remove it?') \
            % dict(species=safe_str, num_accessions=nacc)
    else:
        msg = _("Are you sure you want to remove the species <i>%s</i>?") \
            % safe_str
    if not utils.yes_no_dialog(msg):
        return
    try:
        obj = session.query(Species).get(species.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg,
                                     traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
Ejemplo n.º 19
0
 def handle_response(self, response, commit=True):
     '''
     handle the response from self.presenter.start() in self.start()
     '''
     not_ok_msg = 'Are you sure you want to lose your changes?'
     self._return = None
     self.clean_model()
     if response == gtk.RESPONSE_OK or response in self.ok_responses:
         try:
             self._return = self.model
             if self.presenter.dirty() and commit:
                 self.commit_changes()
         except DBAPIError, e:
             msg = _('Error committing changes.\n\n%s') % \
                 utils.xml_safe(unicode(e.orig))
             utils.message_details_dialog(msg, str(e), gtk.MESSAGE_ERROR)
             self.session.rollback()
             return False
         except Exception, e:
             msg = _('Unknown error when committing changes. See the '
                     'details for more information.\n\n%s') %\
                 utils.xml_safe(e)
             logger.debug(traceback.format_exc())
             utils.message_details_dialog(msg, traceback.format_exc(),
                                          gtk.MESSAGE_ERROR)
             self.session.rollback()
             return False
Ejemplo n.º 20
0
 def on_tools_menu_item_activate(self, widget, tool):
     """
     Start a tool on the Tool menu.
     """
     try:
         tool.start()
     except Exception, e:
         utils.message_details_dialog(utils.xml_safe(str(e)), traceback.format_exc(), gtk.MESSAGE_ERROR)
         logger.debug(traceback.format_exc())
Ejemplo n.º 21
0
 def on_tools_menu_item_activate(self, widget, tool):
     """
     Start a tool on the Tool menu.
     """
     try:
         tool.start()
     except Exception, e:
         utils.message_details_dialog(utils.xml_safe(str(e)),
                                      traceback.format_exc(),
                                      gtk.MESSAGE_ERROR)
         logger.debug(traceback.format_exc())
Ejemplo n.º 22
0
def load(path=None):
    """
    Search the plugin path for modules that provide a plugin. If path
    is a directory then search the directory for plugins. If path is
    None then use the default plugins path, bauble.plugins.

    This method populates the pluginmgr.plugins dict and imports the
    plugins but doesn't do any plugin initialization.

    :param path: the path where to look for the plugins
    :type path: str
    """

    if path is None:
        if bauble.main_is_frozen():
            #path = os.path.join(paths.lib_dir(), 'library.zip')
            path = os.path.join(paths.main_dir(), 'library.zip')
        else:
            path = os.path.join(paths.lib_dir(), 'plugins')
    logger.debug('pluginmgr.load(%s)' % path)
    found, errors = _find_plugins(path)
    logger.debug('found=%s, errors=%s' % (found, errors))

    # show error dialog for plugins that couldn't be loaded...we only
    # give details for the first error and assume the others are the
    # same...and if not then it doesn't really help anyways
    if errors:
        name = ', '.join(sorted(errors.keys()))
        exc_info = errors.values()[0]
        exc_str = utils.xml_safe(exc_info[1])
        tb_str = ''.join(traceback.format_tb(exc_info[2]))
        utils.message_details_dialog('Could not load plugin: '
                                     '\n\n<i>%s</i>\n\n%s'
                                     % (name, exc_str),
                                     tb_str, type=gtk.MESSAGE_ERROR)

    if len(found) == 0:
        logger.debug('No plugins found at path: %s' % path)

    for plugin in found:
        # issue #27: should we include the module name of the plugin to
        # allow for plugin namespaces or just assume that the plugin class
        # name is unique?
        if isinstance(plugin, (type, types.ClassType)):
            plugins[plugin.__name__] = plugin
            logger.debug("registering plugin %s: %s"
                         % (plugin.__name__, plugin))
        else:
            plugins[plugin.__class__.__name__] = plugin
            logger.debug("registering plugin %s: %s"
                         % (plugin.__class__.__name__, plugin))
Ejemplo n.º 23
0
def source_detail_remove_callback(details):
    detail = details[0]
    s = "%s: %s" % (detail.__class__.__name__, str(detail))
    msg = _("Are you sure you want to remove %s?") % utils.xml_safe(s)
    if not utils.yes_no_dialog(msg):
        return
    try:
        session = db.Session()
        obj = session.query(SourceDetail).get(detail.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _("Could not delete.\n\n%s") % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(), type=gtk.MESSAGE_ERROR)
Ejemplo n.º 24
0
def _config_logger(name, level, format, propagate=False):
    try:
        handler = _default_handler()
    except IOError, e:
        import traceback
        global __yesyesiknow
        if not __yesyesiknow and not _main_is_frozen():
            msg = _('** Could not open the default log file.\n'\
                    'Press OK key to continue.\n\n%s') % \
                    bauble.utils.xml_safe_utf8(e)
            utils.message_details_dialog(msg, traceback.format_exc(),
                                         gtk.MESSAGE_WARNING)
            __yesyesiknow = True
        handler = logging.StreamHandler()
Ejemplo n.º 25
0
 def on_insert_menu_item_activate(self, widget, editor_cls):
     try:
         view = self.get_view()
         if isinstance(view, SearchView):
             expanded_rows = view.get_expanded_rows()
         editor = editor_cls()
         committed = editor.start()
         if committed is not None and isinstance(view, SearchView):
             view.results_view.collapse_all()
             view.expand_to_all_refs(expanded_rows)
     except Exception, e:
         utils.message_details_dialog(utils.xml_safe(str(e)), traceback.format_exc(), gtk.MESSAGE_ERROR)
         logger.error("bauble.gui.on_insert_menu_item_activate():\n %s" % traceback.format_exc())
         return
Ejemplo n.º 26
0
 def on_activate(item, cb):
     result = False
     try:
         # have to get the selected values again here
         # because for some unknown reason using the
         # "selected" variable from the parent scope
         # will give us the objects but they won't be
         # in an session...maybe its a thread thing
         values = self.get_selected_values()
         result = cb(values)
     except Exception, e:
         msg = utils.xml_safe_utf8(str(e))
         tb = utils.xml_safe_utf8(traceback.format_exc())
         utils.message_details_dialog(msg, tb,gtk.MESSAGE_ERROR)
         warning(traceback.format_exc())
Ejemplo n.º 27
0
def source_detail_remove_callback(details):
    detail = details[0]
    s = '%s: %s' % (detail.__class__.__name__, str(detail))
    msg = _("Are you sure you want to remove %s?") % utils.xml_safe(s)
    if not utils.yes_no_dialog(msg):
        return
    try:
        session = db.Session()
        obj = session.query(SourceDetail).get(detail.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg,
                                     traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
Ejemplo n.º 28
0
 def on_activate(item, cb):
     result = False
     try:
         # have to get the selected values again here
         # because for some unknown reason using the
         # "selected" variable from the parent scope
         # will give us the objects but they won't be
         # in an session...maybe it's a thread thing
         values = self.get_selected_values()
         result = cb(values)
     except Exception, e:
         msg = utils.xml_safe(str(e))
         tb = utils.xml_safe(traceback.format_exc())
         utils.message_details_dialog(msg, tb,
                                      gtk.MESSAGE_ERROR)
         logger.warning(traceback.format_exc())
Ejemplo n.º 29
0
 def on_insert_menu_item_activate(self, widget, editor_cls):
     try:
         view = self.get_view()
         if isinstance(view, SearchView):
             expanded_rows = view.get_expanded_rows()
         editor = editor_cls()
         committed = editor.start()
         if committed is not None and isinstance(view, SearchView):
             view.results_view.collapse_all()
             view.expand_to_all_refs(expanded_rows)
     except Exception, e:
         utils.message_details_dialog(utils.xml_safe(str(e)),
                                      traceback.format_exc(),
                                      gtk.MESSAGE_ERROR)
         logger.error('bauble.gui.on_insert_menu_item_activate():\n %s' %
                      traceback.format_exc())
         return
Ejemplo n.º 30
0
def remove_callback(locations):
    loc = locations[0]
    s = "%s: %s" % (loc.__class__.__name__, str(loc))
    if len(loc.plants) > 0:
        msg = _("Please remove the plants from <b>%(location)s</b> " "before deleting it.") % {"location": loc}
        utils.message_dialog(msg, gtk.MESSAGE_WARNING)
        return
    msg = _("Are you sure you want to remove %s?") % utils.xml_safe(s)
    if not utils.yes_no_dialog(msg):
        return
    try:
        session = db.Session()
        obj = session.query(Location).get(loc.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _("Could not delete.\n\n%s") % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(), type=gtk.MESSAGE_ERROR)
Ejemplo n.º 31
0
def remove_callback(plants):
    s = ', '.join([str(p) for p in plants])
    msg = _("Are you sure you want to remove the following plants?\n\n%s") \
        % utils.xml_safe_utf8(s)
    if not utils.yes_no_dialog(msg):
        return

    session = db.Session()
    for plant in plants:
        obj = session.query(Plant).get(plant.id)
        session.delete(obj)
    try:
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe_utf8(e)

        utils.message_details_dialog(msg, traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
Ejemplo n.º 32
0
def remove_callback(tags):
    """
    :param tags: a list of :class:`Tag` objects.
    """
    tag = tags[0]
    s = '%s: %s' % (tag.__class__.__name__, utils.xml_safe(tag))
    msg = _("Are you sure you want to remove %s?") % s
    if not utils.yes_no_dialog(msg):
        return
    session = db.Session()
    try:
        obj = session.query(Tag).get(tag.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
Ejemplo n.º 33
0
def remove_callback(tags):
    """
    :param tags: a list of :class:`Tag` objects.
    """
    tag = tags[0]
    s = '%s: %s' % (tag.__class__.__name__, utils.xml_safe(tag))
    msg = _("Are you sure you want to remove %s?") % s
    if not utils.yes_no_dialog(msg):
        return
    session = object_session(tag)
    try:
        obj = session.query(Tag).get(tag.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
Ejemplo n.º 34
0
def remove_callback(locations):
    loc = locations[0]
    s = '%s: %s' % (loc.__class__.__name__, str(loc))
    if len(loc.plants) > 0:
        msg = _('Please remove the plants from <b>%(location)s</b> '
                'before deleting it.') % {'location': loc}
        utils.message_dialog(msg, gtk.MESSAGE_WARNING)
        return
    msg = _("Are you sure you want to remove %s?") % \
        utils.xml_safe(s)
    if not utils.yes_no_dialog(msg):
        return
    try:
        session = db.Session()
        obj = session.query(Location).get(loc.id)
        session.delete(obj)
        session.commit()
    except Exception, e:
        msg = _('Could not delete.\n\n%s') % utils.xml_safe(e)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     type=gtk.MESSAGE_ERROR)
Ejemplo n.º 35
0
 def handle_response(self, response):
     """
     handle the response from self.presenter.start() in self.start()
     """
     not_ok_msg = _("Are you sure you want to lose your changes?")
     if response == gtk.RESPONSE_OK or response in self.ok_responses:
         try:
             if self.presenter.dirty():
                 self.commit_changes()
                 self._committed.append(self.model)
         except DBAPIError, e:
             msg = _("Error committing changes.\n\n%s" % utils.xml_safe(e.orig))
             utils.message_details_dialog(msg, str(e), gtk.MESSAGE_ERROR)
             return False
         except Exception, e:
             msg = _(
                 "Unknown error when committing changes. See the "
                 "details for more information.\n\n%s" % utils.xml_safe(e)
             )
             utils.message_details_dialog(msg, traceback.format_exc(), gtk.MESSAGE_ERROR)
             return False
Ejemplo n.º 36
0
 def handle_response(self, response):
     """
     @return: return a list if we want to tell start() to close the editor,
     the list should either be empty or the list of committed values, return
     None if we want to keep editing
     """
     not_ok_msg = "Are you sure you want to lose your changes?"
     if response == gtk.RESPONSE_OK or response in self.ok_responses:
         try:
             if self.presenter.dirty():
                 self.commit_changes()
                 self._committed.append(self.model)
         except DBAPIError, e:
             msg = _("Error committing changes.\n\n%s") % utils.xml_safe(e.orig)
             utils.message_details_dialog(msg, str(e), gtk.MESSAGE_ERROR)
             return False
         except Exception, e:
             msg = _(
                 "Unknown error when committing changes. See the " "details for more information.\n\n%s"
             ) % utils.xml_safe(e)
             utils.message_details_dialog(msg, traceback.format_exc(), gtk.MESSAGE_ERROR)
             return False
Ejemplo n.º 37
0
    def on_file_menu_new(self, widget, data=None):
        msg = "If a database already exists at this connection then creating "\
              "a new database could destroy your data.\n\n<i>Are you sure "\
              "this is what you want to do?</i>"

        if not utils.yes_no_dialog(msg, yes_delay=2):
            return

        #if gui is not None and hasattr(gui, 'insert_menu'):
        submenu = self.insert_menu.get_submenu()
        for c in submenu.get_children():
            submenu.remove(c)
        self.insert_menu.show()
        try:
            db.create()
            pluginmgr.init()
        except Exception, e:
            msg = _('Could not create a new database.\n\n%s') % \
                utils.xml_safe(e)
            tb = utils.xml_safe(traceback.format_exc())
            utils.message_details_dialog(msg, tb, gtk.MESSAGE_ERROR)
            return
Ejemplo n.º 38
0
 def handle_response(self, response):
     '''
     handle the response from self.presenter.start() in self.start()
     '''
     not_ok_msg = _('Are you sure you want to lose your changes?')
     if response == gtk.RESPONSE_OK or response in self.ok_responses:
         try:
             if self.presenter.dirty():
                 self.commit_changes()
                 self._committed.append(self.model)
         except DBAPIError, e:
             msg = _('Error committing changes.\n\n%s') % \
                 utils.xml_safe(e.orig)
             utils.message_details_dialog(msg, str(e), gtk.MESSAGE_ERROR)
             return False
         except Exception, e:
             msg = _('Unknown error when committing changes. See the '
                     'details for more information.\n\n%s') % \
                 utils.xml_safe(e)
             utils.message_details_dialog(msg, traceback.format_exc(),
                                          gtk.MESSAGE_ERROR)
             return False
Ejemplo n.º 39
0
    def on_file_menu_new(self, widget, data=None):
        msg = "If a database already exists at this connection then creating "\
              "a new database could destroy your data.\n\n<i>Are you sure "\
              "this is what you want to do?</i>"

        if not utils.yes_no_dialog(msg, yes_delay=2):
            return

        #if gui is not None and hasattr(gui, 'insert_menu'):
        submenu = self.insert_menu.get_submenu()
        for c in submenu.get_children():
            submenu.remove(c)
        self.insert_menu.show()
        try:
            db.create()
            pluginmgr.init()
        except Exception, e:
            msg = _('Could not create a new database.\n\n%s') % \
                utils.xml_safe(e)
            tb = utils.xml_safe(traceback.format_exc())
            utils.message_details_dialog(msg, tb, gtk.MESSAGE_ERROR)
            return
Ejemplo n.º 40
0
 def handle_response(self, response):
     not_ok_msg = _('Are you sure you want to lose your changes?')
     if response == gtk.RESPONSE_OK or response in self.ok_responses:
         try:
             if self.presenter.dirty():
                 # commit_changes() will append the commited plants
                 # to self._committed
                 self.commit_changes()
         except DBAPIError, e:
             exc = traceback.format_exc()
             msg = _('Error committing changes.\n\n%s') % e.orig
             utils.message_details_dialog(msg, str(e), gtk.MESSAGE_ERROR)
             self.session.rollback()
             return False
         except Exception, e:
             msg = _('Unknown error when committing changes. See the '\
                   'details for more information.\n\n%s') \
                   % utils.xml_safe_utf8(e)
             debug(traceback.format_exc())
             utils.message_details_dialog(msg, traceback.format_exc(),
                                          gtk.MESSAGE_ERROR)
             self.session.rollback()
             return False
Ejemplo n.º 41
0
 def handle_response(self, response):
     '''
     @return: return a list if we want to tell start() to close the editor,
     the list should either be empty or the list of committed values, return
     None if we want to keep editing
     '''
     not_ok_msg = 'Are you sure you want to lose your changes?'
     if response == gtk.RESPONSE_OK or response in self.ok_responses:
         try:
             if self.presenter.dirty():
                 self.commit_changes()
                 self._committed.append(self.model)
         except DBAPIError, e:
             msg = _('Error committing changes.\n\n%s') % \
                 utils.xml_safe(e.orig)
             utils.message_details_dialog(msg, str(e), gtk.MESSAGE_ERROR)
             return False
         except Exception, e:
             msg = _('Unknown error when committing changes. See the '
                     'details for more information.\n\n%s') % \
                 utils.xml_safe(e)
             utils.message_details_dialog(msg, traceback.format_exc(),
                                          gtk.MESSAGE_ERROR)
             return False
Ejemplo n.º 42
0
 def _post_loop():
     gtk.gdk.threads_enter()
     try:
         if isinstance(open_exc, err.DatabaseError):
             msg = _('Would you like to create a new Bauble database at '
                     'the current connection?\n\n<i>Warning: If there is '
                     'already a database at this connection any existing '
                     'data will be destroyed!</i>')
             if utils.yes_no_dialog(msg, yes_delay=2):
                 try:
                     db.create()
                     # db.create() creates all tables registered with
                     # the default metadata so the pluginmgr should be
                     # loaded after the database is created so we don't
                     # inadvertantly create tables from the plugins
                     pluginmgr.init()
                     # set the default connection
                     prefs[conn_default_pref] = conn_name
                 except Exception, e:
                     utils.message_details_dialog(utils.xml_safe(e),
                                                  traceback.format_exc(),
                                                  gtk.MESSAGE_ERROR)
                     logger.error("%s(%s)" % (type(e), e))
         else:
Ejemplo n.º 43
0
 def _post_loop():
     gtk.gdk.threads_enter()
     try:
         if isinstance(open_exc, err.DatabaseError):
             msg = _('Would you like to create a new Bauble database at ' \
                     'the current connection?\n\n<i>Warning: If there is '\
                     'already a database at this connection any existing '\
                     'data will be destroyed!</i>')
             if utils.yes_no_dialog(msg, yes_delay=2):
                 try:
                     db.create()
                     # db.create() creates all tables registered with
                     # the default metadata so the pluginmgr should be
                     # loaded after the database is created so we don't
                     # inadvertantly create tables from the plugins
                     pluginmgr.init()
                     # set the default connection
                     prefs[conn_default_pref] = conn_name
                 except Exception, e:
                     utils.message_details_dialog(utils.xml_safe_utf8(e),
                                                  traceback.format_exc(),
                                                  gtk.MESSAGE_ERROR)
                     error(e)
         else:
Ejemplo n.º 44
0
        # by setting the sequence manually to the max(column)+1
        col = None
        try:
            for table, filename in sorted_tables:
                for col in table.c:
                    utils.reset_sequence(col)
        except Exception, e:
            col_name = None
            try:
                col_name = col.name
            except Exception:
                pass
            msg = _('Error: Could not set the sequence for column: %s') \
                  % col_name
            utils.message_details_dialog(_(utils.xml_safe_utf8(msg)),
                                         traceback.format_exc(),
                                         type=gtk.MESSAGE_ERROR)


# TODO: we don't use the progress dialog any more but we'll leave this
# around to remind us when we support cancelling via the progress statusbar
#
#     def _cancel_import(self, *args):
#         '''
#         called by the progress dialog to cancel the current import
#         '''
#         msg = _('Are you sure you want to cancel importing?\n\n<i>All '
#                 'changes so far will be rolled back.</i>')
#         self.__pause = True
#         if utils.yes_no_dialog(msg, parent=self.__progress_dialog):
#             self.__cancel = True
Ejemplo n.º 45
0
        # by setting the sequence manually to the max(column)+1
        col = None
        try:
            for table, filename in sorted_tables:
                for col in table.c:
                    utils.reset_sequence(col)
        except Exception, e:
            col_name = None
            try:
                col_name = col.name
            except Exception:
                pass
            msg = _('Error: Could not set the sequence for column: %s') \
                % col_name
            utils.message_details_dialog(_(utils.xml_safe(msg)),
                                         traceback.format_exc(),
                                         type=gtk.MESSAGE_ERROR)

# TODO: we don't use the progress dialog any more but we'll leave this
# around to remind us when we support cancelling via the progress statusbar
#
#     def _cancel_import(self, *args):
#         '''
#         called by the progress dialog to cancel the current import
#         '''
#         msg = _('Are you sure you want to cancel importing?\n\n<i>All '
#                 'changes so far will be rolled back.</i>')
#         self.__pause = True
#         if utils.yes_no_dialog(msg, parent=self.__progress_dialog):
#             self.__cancel = True
##         self.__pause = False
Ejemplo n.º 46
0
            # could overwrite data
            ordered.remove(plugin)
            msg = (_("The %(plugin_name)s plugin is listed in the registry "
                     "but isn't wasn't found in the plugin directory")
                   % dict(plugin_name=plugin.__class__.__name__))
            logger.warning(msg)
        except Exception, e:
            logger.error(e)
            ordered.remove(plugin)
            logger.error(traceback.print_exc())
            safe = utils.xml_safe
            values = dict(entry_name=plugin.__class__.__name__,
                          exception=safe(e))
            utils.message_details_dialog(
                _("Error: Couldn't initialize %(entry_name)s\n\n"
                  "%(exception)s.") % values,
                traceback.format_exc(),
                gtk.MESSAGE_ERROR)

    # register the plugin commands seperately from the plugin initialization
    for plugin in ordered:
        if plugin.commands in (None, []):
            continue
        for cmd in plugin.commands:
            try:
                register_command(cmd)
            except Exception, e:
                logger.debug("exception %s while registering command %s"
                             % (e, cmd))
                msg = 'Error: Could not register command handler.\n\n%s' % \
                      utils.xml_safe(str(e))
Ejemplo n.º 47
0
    old_view = gui.get_view()
    if type(old_view) != type(handler_view) and handler_view:
        # remove the accel_group from the window if the previous view
        # had one
        if hasattr(old_view, 'accel_group'):
            gui.window.remove_accel_group(old_view.accel_group)
        # add the new view, and its accel_group if it has one
        gui.set_view(handler_view)
        if hasattr(handler_view, 'accel_group'):
            gui.window.add_accel_group(handler_view.accel_group)
    try:
        last_handler(cmd, arg)
    except Exception, e:
        msg = utils.xml_safe(e)
        logger.error('bauble.command_handler(): %s' % msg)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     gtk.MESSAGE_ERROR)


conn_default_pref = "conn.default"
conn_list_pref = "conn.list"


def main(uri=None):
    """
    Run the main Bauble application.

    :param uri:  the URI of the database to connect to.  For more information
                 about database URIs see `<http://www.sqlalchemy.org/docs/05/\
dbengine.html#create-engine-url-arguments>`_

    :type uri: str
Ejemplo n.º 48
0
    old_view = gui.get_view()
    if type(old_view) != type(handler_view) and handler_view:
        # remove the accel_group from the window if the previous view
        # had one
        if hasattr(old_view, 'accel_group'):
            gui.window.remove_accel_group(old_view.accel_group)
        # add the new view and its accel_group if it has one
        gui.set_view(handler_view)
        if hasattr(handler_view, 'accel_group'):
            gui.window.add_accel_group(handler_view.accel_group)
    try:
        last_handler(cmd, arg)
    except Exception, e:
        msg = utils.xml_safe_utf8(e)
        error('bauble.command_handler(): %s' % msg)
        utils.message_details_dialog(msg, traceback.format_exc(),
                                     gtk.MESSAGE_ERROR)


conn_default_pref = "conn.default"
conn_list_pref = "conn.list"

def main(uri=None):
    """
    Run the main Bauble application.

    :param uri:  the URI of the database to connect to.  For more information about database URIs see `<http://www.sqlalchemy.org/docs/05/dbengine.html#create-engine-url-arguments>`_
    :type uri: str
    """
    # TODO: it would be nice to show a Tk dialog here saying we can't
    # import gtk...but then we would have to include all of the Tk libs in
    # with the win32 batteries-included installer