def remove(self, vn): super(VNList, self).remove(vn) try: if vn.species.default_vernacular_name == vn: del vn.species.default_vernacular_name except Exception, e: debug(e)
def handle_response(self, response): """ @return: return True if the editor is realdy to be closes, 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.dirty(): self.commit_changes() self._committed.append(self.model) except DBAPIError, e: exc = traceback.format_exc() msg = _('Error committing changes.\n\n%s') % \ utils.xml_safe_utf8(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_utf8(e) debug(traceback.format_exc()) #warning(traceback.format_exc()) utils.message_details_dialog(msg, traceback.format_exc(), gtk.MESSAGE_ERROR) return False
def run(self): """ """ response = self.window.run() self.window.hide() if response != gtk.RESPONSE_OK: return response stored_email = meta.get_default(PICASA_EMAIL_KEY).value.strip() email = self.widgets.email_entry.get_text().strip() album = self.widgets.album_entry.get_text().strip() passwd = self.widgets.password_entry.get_text().strip() if stored_email != email or self._changed: try: token = get_auth_token(email, passwd) except Exception, e: debug(e) token = None if not token: utils.message_dialog(_('Could not authorize Google '\ 'account: %s' % email), gtk.MESSAGE_ERROR) return False update_meta(utils.utf8(email), utils.utf8(album), utils.utf8(token))
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)
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_utf8(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_utf8(e) debug(traceback.format_exc()) utils.message_details_dialog(msg, traceback.format_exc(), gtk.MESSAGE_ERROR) self.session.rollback() return False
def _animate_cb(final_height): height = 0 while height < final_height: width, height = self.size_request() height = height + 1 self.set_size_request(width, height) self.queue_resize() while gtk.events_pending(): gtk.main_iteration(False) debug('return False') return False
def refresh_view(self, prefs): """ refresh the widget values from prefs """ try: self.db_entry.set_text(prefs["db"]) self.host_entry.set_text(prefs["host"]) self.user_entry.set_text(prefs["user"]) self.passwd_check.set_active(prefs["passwd"]) except KeyError, e: debug('KeyError: %s' % e)
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) debug(traceback.format_exc())
def itest_editor(self): """ Interactively test the AccessionEditor """ #donor = self.create(Donor, name=u'test') sp2 = Species(genus=self.genus, sp=u'species') sp2.synonyms.append(self.species) self.session.add(sp2) self.session.commit() # import datetime again since sometimes i get an weird error import datetime acc_code = '%s%s1' % (datetime.date.today().year, Plant.get_delimiter()) acc = self.create(Accession, species=self.species, code=acc_code) voucher = Voucher(herbarium=u'abcd', code=u'123') acc.vouchers.append(voucher) prev = 0 def mem(size="rss"): """Generalization; memory sizes: rss, rsz, vsz.""" import os return int(os.popen('ps -p %d -o %s | tail -1' % \ (os.getpid(), size)).read()) # add verificaiton ver = Verification() ver.verifier = u'me' ver.date = datetime.date.today() ver.prev_species = self.species ver.species = self.species ver.level = 1 acc.verifications.append(ver) location = Location(name=u'loc1', code=u'loc1') plant = Plant(accession=acc, location=location, code=u'1', quantity=1) prop = Propagation(prop_type=u'Seed') seed = PropSeed(**default_seed_values) seed.propagation = prop plant.propagations.append(prop) source_detail = SourceDetail(name=u'Test Source', source_type=u'Expedition') source = Source(sources_code=u'22') source.source_detail = source_detail acc.source = source self.session.commit() self.editor = AccessionEditor(model=acc) try: self.editor.start() except Exception, e: import traceback debug(traceback.format_exc(0)) debug(e)
def itest_editor(self): """ Interactively test the PropagationEditor """ from bauble.plugins.garden.propagation import PropagationEditor propagation = Propagation() #propagation.prop_type = u'UnrootedCutting' propagation.accession = self.accession editor = PropagationEditor(model=propagation) propagation = editor.start() debug(propagation) self.assert_(propagation.accession)
def example_task(monitor): # timeout = gtasklet.WaitForTimeout(1000) # msgwait = gtasklet.WaitForMessages(accept='quit') for i in range(1, 10): debug(i) yield # timeout gtasklet.get_event() try: if i == 2: #raise Exception pass except Exception, e: return
def _formatter_combo_changed_idle(self, combo): formatter = combo.get_active_text() name = self.view.widgets.names_combo.get_active_text() try: # TODO: settings seems to always be {} here saved_name, settings = prefs[config_list_pref][name] if saved_name != formatter: settings = {} # # set the new formatter value in the preferences # set_prefs_for(name, self.formatter_class_map[title]) # #prefs[config_list_pref][name] = title, settings except KeyError, e: debug(e) return
def _find_plugins(path): """ Return the plugins at path. """ plugins = [] import bauble.plugins plugin_module = bauble.plugins errors = {} if path.find('library.zip') != -1: plugin_names = [m for m in _find_module_names(path) \ if m.startswith('bauble.plugins')] else: plugin_names =['bauble.plugins.%s'%m for m in _find_module_names(path)] for name in plugin_names: mod = None # Fast path: see if the module has already been imported. if name in sys.modules: mod = sys.modules[name] else: try: mod = __import__(name, globals(), locals(), [name], -1) except Exception, e: msg = _('Could not import the %(module)s module.\n\n'\ '%(error)s' % {'module': name, 'error': e}) debug(msg) errors[name] = sys.exc_info() if not hasattr(mod, "plugin"): continue # if mod.plugin is a function it should return a plugin or list of # plugins try: mod_plugin = mod.plugin() except: mod_plugin = mod.plugin is_plugin = lambda p: isinstance(p, (type, types.ClassType)) and issubclass(p, Plugin) if isinstance(mod_plugin, (list, tuple)): for p in mod_plugin: if is_plugin(p) or True: plugins.append(p) elif is_plugin(mod_plugin) or True: plugins.append(mod_plugin) else: warning(_('%s.plugin is not an instance of pluginmgr.Plugin'\ % mod.__name__))
def on_row_expanded(self, treeview, treeiter, path): """ Called before the row is expanded and populates the children of the row. """ debug('on_row_expanded') model = treeview.props.model parent = treeiter while model.iter_has_child(treeiter): nkids = model.iter_n_children(parent) child = model.iter_nth_child(parent, nkids-1) model.remove(child) # prop should always be a RelationProperty prop = treeview.props.model[treeiter][1] self._insert_props(prop.mapper, model, treeiter)
def on_names_combo_changed(self, combo, *args): if combo.get_model() is None: self.view.widgets.details_box.set_sensitive(False) return name = combo.get_active_text() formatters = prefs[config_list_pref] self.view.widgets.details_box.set_sensitive(name is not None) prefs[default_config_pref] = name # set the default to the new name try: title, settings = formatters[name] except (KeyError, TypeError), e: # TODO: show a dialog saying that you can't find whatever # you're looking for in the settings debug(e) return
def test_verifications(self): acc = self.create(Accession, species=self.species, code=u'1') self.session.add(acc) self.session.commit() ver = Verification() ver.verifier = u'me' ver.date = datetime.date.today() ver.level = 1 ver.species = acc.species ver.prev_species = acc.species acc.verifications.append(ver) try: self.session.commit() except Exception, e: debug(e) self.session.rollback()
def __init__(self, filename, parent=None): builder = utils.BuilderLoader.load(filename) self.widgets = utils.BuilderWidgets(builder) if parent: self.get_window().set_transient_for(parent) elif bauble.gui: self.get_window().set_transient_for(bauble.gui.window) self.response = None self.__attached_signals = [] # set the tooltips...use gtk.Tooltip api introducted in GTK+ 2.12 for widget_name, markup in self._tooltips.iteritems(): try: self.widgets[widget_name].set_tooltip_markup(markup) except Exception, e: values = dict(widget_name=widget_name, exception=e) debug(_('Couldn\'t set the tooltip on widget '\ '%(widget_name)s\n\n%(exception)s' % values))
def untag_objects(name, objs): """ Remove the tag name from objs. :param name: The name of the tag :type name: str :param objs: The list of objects to untag. :type objs: list """ # TODO: should we loop through objects in a tag to delete # the TaggedObject or should we delete tags is they match # the tag in TaggedObj.selectBy(obj_class=classname, obj_id=obj.id) session = db.Session() try: tag = session.query(Tag).filter_by(tag=utils.utf8(name)).one() except Exception, e: debug(traceback.format_exc()) return
def search(self, text, session): # TODO: this doesn't support search like plant=2009.0039.1 or # plant where accession.code=2009.0039 # TODO: searches like 2009.0039.% or * would be handy r1 = super(PlantSearch, self).search(text, session) delimiter = Plant.get_delimiter() if delimiter not in text: return [] acc_code, plant_code = text.rsplit(delimiter, 1) query = session.query(Plant) from bauble.plugins.garden import Accession try: q = query.join('accession').\ filter(and_(Accession.code==acc_code, Plant.code==plant_code)) except Exception, e: debug(e) return []
def _create_dependency_pairs(plugs): """ Returns a tuple. The first item in the tuple is the dependency pairs that can be passed to topological sort. The second item is a dictionary whose keys are plugin names and value are a list of unmet dependencies. """ depends = [] unmet = {} for p in plugs: for dep in p.depends: try: depends.append((plugins[dep], p)) except KeyError: debug('no dependency %s for %s' % (dep, p.__name__)) u = unmet.setdefault(p.__name__, []) u.append(dep) return depends, unmet
def populate_names_combo(self): ''' populates the combo with the list of configuration names from the prefs ''' configs = prefs[config_list_pref] combo = self.view.widgets.names_combo if configs is None: self.view.widgets.details_box.set_sensitive(False) utils.clear_model(combo) return try: model = gtk.ListStore(str) for cfg in configs.keys(): model.append([cfg]) combo.set_model(model) except AttributeError, e: # no formatters debug(e) pass
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') found, errors = _find_plugins(path) # 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_utf8(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: debug('No plugins found at path: %s' % path) for plugin in found: # TODO: should we include the module name of the plugin to allow # for plugin namespaces or just assume that the plugin class # name is unique plugins[plugin.__class__.__name__] = plugin
def start(self, path=None): if path == None: d = gtk.FileChooserDialog(_("Select a directory"), None, gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, (gtk.STOCK_OK, gtk.RESPONSE_ACCEPT, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)) response = d.run() path = d.get_filename() d.destroy() if response != gtk.RESPONSE_ACCEPT: return if not os.path.exists(path): raise ValueError(_("CSVExporter: path does not exist.\n%s" % path)) try: # TODO: should we support exporting other metadata # besides db.metadata bauble.task.queue(self.__export_task(path)) except Exception, e: debug(e)
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
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: debug(traceback.format_exc()) msg = _('Could not create the tags menus') utils.message_details_dialog(msg, traceback.format_exc(), gtk.MESSAGE_ERROR) # raise #debug('** maybe the tags table hasn\'t been created yet') 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()
def testTask(self): return # def example_task(monitor): # yield gtasklet.Message('quit', dest=monitor) try: bauble.task.queue(example_task, None, gtk.main_quit) except: debug('caught exception') debug('call gtk.main()') # gtk.main() debug('past gtk.main()')
def update_infobox(self): ''' Sets the infobox according to the currently selected row or remove the infobox is nothing is selected ''' self.set_infobox_from_row(None) values = self.get_selected_values() if len(values) == 0: return try: self.set_infobox_from_row(values[0]) except Exception, e: debug('SearchView.update_infobox: %s' % e) debug(traceback.format_exc()) debug(values) self.set_infobox_from_row(None)
def on_response(self, widget, response, data=None): debug('on_response') debug(response)
self.view.widgets.details_box.set_sensitive(name is not None) prefs[default_config_pref] = name # set the default to the new name try: title, settings = formatters[name] except (KeyError, TypeError), e: # TODO: show a dialog saying that you can't find whatever # you're looking for in the settings debug(e) return try: self.set_formatter_combo(title) except Exception, e: # TODO: show a dialog saying that you can't find whatever # you're looking for in the settings debug(e) self.set_formatter_combo(-1) self.view.widgets.details_box.set_sensitive(True) def on_formatter_combo_changed(self, combo, *args): ''' formatter_combo changed signal handler ''' self.view.widgets.ok_button.set_sensitive(False) gobject.idle_add(self._formatter_combo_changed_idle, combo) def _formatter_combo_changed_idle(self, combo): formatter = combo.get_active_text() name = self.view.widgets.names_combo.get_active_text()
self.vbox.show_all() response = self.run() self.hide() return response def get_query(self): """ Return query expression string. """ domain = self.domain_combo.get_active_text() query = [domain, 'where'] for row in self.expression_rows: expr = row.get_expression() if expr: query.append(expr) return ' '.join(query) if __name__ == '__main__': import bauble.test uri = 'sqlite:///:memory:' bauble.test.init_bauble(uri) qb = QueryBuilder() qb.start() debug(qb.get_query())