Example #1
0
 def foreach(model,path,iter,recs):
     debug("foreach(model,path,iter,recs):",5)
     try:
         recs.append(model[path][0])
         #recs.append(self.get_rec_from_iter(iter))
     except:
         debug("DEBUG: There was a problem with iter: %s path: %s"%(iter,path),1)
Example #2
0
 def get_instantiated_plugin(self, plugin):
     if self.instantiated_plugins.has_key(plugin):
         return self.instantiated_plugins[plugin]
     else:
         debug('Instantiate %s from %s' % (plugin, plugin.__module__), 1)
         self.instantiated_plugins[plugin] = plugin()
         return self.instantiated_plugins[plugin]
Example #3
0
 def get_instantiated_plugin(self, plugin):
     if self.instantiated_plugins.has_key(plugin):
         return self.instantiated_plugins[plugin]
     else:
         debug("Instantiate %s from %s" % (plugin, plugin.__module__), 1)
         self.instantiated_plugins[plugin] = plugin()
         return self.instantiated_plugins[plugin]
Example #4
0
    def getOptionalIngDic (self, ivw, mult, prefs):
        """Return a dictionary of optional ingredients with a TRUE|FALSE value

        Alternatively, we return a boolean value, in which case that is
        the value for all ingredients.
        
        The dictionary will tell us which ingredients to add to our shopping list.
        We look at prefs to see if 'shop_always_add_optional' is set, in which case
        we don't ask our user."""    
        debug("getOptionalIngDic (ivw):",5)
        #vw = ivw.select(optional=True)
        vw = filter(lambda r: r.optional==True, ivw)
        # optional_mode: 0==ask, 1==add, -1==dont add
        optional_mode=prefs.get('shop_handle_optional',0)
        if optional_mode:
            if optional_mode==1:
                return True
            elif optional_mode==-1:
                return False
        elif len(vw) > 0:
            if not None in [i.shopoptional for i in vw]:
                # in this case, we have a simple job -- load our saved
                # defaults
                dic = {}
                for i in vw:
                    if i.shopoptional==2: dic[i.ingkey]=True
                    else: dic[i.ingkey]=False
                return dic
            # otherwise, we ask our user
            oid=OptionalIngDialog(vw, prefs, mult)
            retval = oid.run()
            if retval:
                return retval
            else:
                raise de.UserCancelError("Option Dialog cancelled!")
Example #5
0
    def getOptionalIngDic(self, ivw, mult, prefs):
        """Return a dictionary of optional ingredients with a TRUE|FALSE value

        Alternatively, we return a boolean value, in which case that is
        the value for all ingredients.

        The dictionary will tell us which ingredients to add to our shopping list.
        We look at prefs to see if 'shop_always_add_optional' is set, in which case
        we don't ask our user."""
        debug("getOptionalIngDic (ivw):", 5)
        # vw = ivw.select(optional=True)
        vw = filter(lambda r: r.optional == True, ivw)
        # optional_mode: 0==ask, 1==add, -1==dont add
        optional_mode = prefs.get('shop_handle_optional', 0)
        if optional_mode:
            if optional_mode == 1:
                return True
            elif optional_mode == -1:
                return False
        elif len(vw) > 0:
            if not None in [i.shopoptional for i in vw]:
                # in this case, we have a simple job -- load our saved
                # defaults
                dic = {}
                for i in vw:
                    if i.shopoptional == 2: dic[i.ingkey] = True
                    else: dic[i.ingkey] = False
                return dic
            # otherwise, we ask our user
            oid = OptionalIngDialog(vw, prefs, mult)
            retval = oid.run()
            if retval:
                return retval
            else:
                raise de.UserCancelError("Option Dialog cancelled!")
Example #6
0
 def foreach(model,path,iter,recs):
     debug("foreach(model,path,iter,recs):",5)
     try:
         rec=model.get_value(iter,0)
         recs.append(rec)
     except:
         debug("DEBUG: There was a problem with iter: %s path: %s"%(iter,path),1)
Example #7
0
 def rtree_edited_cb (self, renderer, path_string, text, colnum, attribute):
     debug("rtree_edited_cb (self, renderer, path_string, text, colnum, attribute):",5)
     indices = path_string.split(':')
     path = tuple( map(int, indices))
     store = self.rectree.get_model()
     iter = store.get_iter(path)
     if not iter: return
     #self.rmodel.set_value(iter, colnum, text)
     rec=self.get_rec_from_iter(iter)
     if attribute=='category':
         val = ", ".join(self.rd.get_cats(rec))
     else:
         val = "%s"%getattr(rec,attribute)
     if val!=text:
         # only bother with this if the value has actually changed!
         self.rd.undoable_modify_rec(rec,
                                     {attribute:text},
                                     self.history,
                                     get_current_rec_method=lambda *args: self.get_selected_recs_from_rec_tree()[0],
                                     )
         self.update_modified_recipe(rec,attribute,text)
     # for metakit, which isn't autocomitting very nicely...        
     #self.rmodel.row_changed(path,iter)
     self.rmodel.update_iter(iter)
     self.rd.save()
Example #8
0
 def foreach(model,path,iter,recs):
     debug("foreach(model,path,iter,recs):",5)
     try:
         recs.append(model[path][0])
         #recs.append(self.get_rec_from_iter(iter))
     except:
         debug("DEBUG: There was a problem with iter: %s path: %s"%(iter,path),1)
Example #9
0
 def convert_fancy(self, u1, u2, item=None, density=None):
     simple = self.convert_simple(u1, u2, self.conv_table)
     if simple:
         return simple
     # otherwise, we need to grab use a density table
     debug("using density data")
     return self.convert_w_density(u1, u2, item=item, density=density)
Example #10
0
 def rtree_edited_cb(self, renderer, path_string, text, colnum, attribute):
     debug(
         "rtree_edited_cb (self, renderer, path_string, text, colnum, attribute):",
         5)
     indices = path_string.split(':')
     path = tuple(map(int, indices))
     store = self.rectree.get_model()
     iter = store.get_iter(path)
     if not iter: return
     #self.rmodel.set_value(iter, colnum, text)
     rec = self.get_rec_from_iter(iter)
     if attribute == 'category':
         val = ", ".join(self.rd.get_cats(rec))
     else:
         val = "%s" % getattr(rec, attribute)
     if val != text:
         # only bother with this if the value has actually changed!
         self.rd.undoable_modify_rec(
             rec,
             {attribute: text},
             self.history,
             get_current_rec_method=lambda *args: self.
             get_selected_recs_from_rec_tree()[0],
         )
         self.update_modified_recipe(rec, attribute, text)
     # for metakit, which isn't autocomitting very nicely...
     #self.rmodel.row_changed(path,iter)
     self.rmodel.update_iter(iter)
     self.rd.save()
Example #11
0
 def create_ingTree (self, widget, model):
     debug("create_ingTree (self, widget, model):",5)
     #self.slTree = gtk.TreeView(self.slMod)
     tree=widget
     tree.set_model(model)
     ## add multiple selections
     tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
     ## adding drag and drop functionality
     targets = [('GOURMET_SHOPPER_SW', gtk.TARGET_SAME_WIDGET, 0),
                ('GOURMET_SHOPPER', gtk.TARGET_SAME_APP, 1),
                ('text/plain',0,2),
                ('STRING',0,3),
                ('STRING',0,4),
                ('COMPOUND_TEXT',0,5),
                ('text/unicode',0,6),]
     tree.drag_source_set(gtk.gdk.BUTTON1_MASK, targets,
                          gtk.gdk.ACTION_COPY | gtk.gdk.ACTION_MOVE)
     tree.enable_model_drag_dest(targets,
                                 gtk.gdk.ACTION_COPY | gtk.gdk.ACTION_MOVE)
     tree.connect('drag_begin', self.on_drag_begin)
     tree.connect('drag_data_get', self.on_drag_data_get)
     tree.connect('drag_data_received', self.on_drag_data_received)
     tree.connect('drag_motion', self.on_drag_motion)
     tree.connect('drag_drop', self.on_drag_drop)
     renderer = gtk.CellRendererText()
     for n,t in [[0,'Item'],[1,'Amount']]:
         col = gtk.TreeViewColumn(t,renderer,text=n)
         col.set_resizable(True)
         tree.append_column(col)
     tree.expand_all()
     tree.show()
     return tree
Example #12
0
 def foreach(model,path,iter,recs):
     debug("foreach(model,path,iter,recs):",5)
     try:
         rec=model.get_value(iter,0)
         recs.append(rec)
     except:
         debug("DEBUG: There was a problem with iter: %s path: %s"%(iter,path),1)
Example #13
0
 def create_ingTree(self, widget, model):
     debug("create_ingTree (self, widget, model):", 5)
     # self.slTree = gtk.TreeView(self.slMod)
     tree = widget
     tree.set_model(model)
     ## add multiple selections
     tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
     ## adding drag and drop functionality
     targets = [
         ('GOURMET_SHOPPER_SW', gtk.TARGET_SAME_WIDGET, 0),
         ('GOURMET_SHOPPER', gtk.TARGET_SAME_APP, 1),
         ('text/plain', 0, 2),
         ('STRING', 0, 3),
         ('STRING', 0, 4),
         ('COMPOUND_TEXT', 0, 5),
         ('text/unicode', 0, 6),
     ]
     tree.drag_source_set(gtk.gdk.BUTTON1_MASK, targets,
                          gtk.gdk.ACTION_COPY | gtk.gdk.ACTION_MOVE)
     tree.enable_model_drag_dest(targets,
                                 gtk.gdk.ACTION_COPY | gtk.gdk.ACTION_MOVE)
     tree.connect('drag_begin', self.on_drag_begin)
     tree.connect('drag_data_get', self.on_drag_data_get)
     tree.connect('drag_data_received', self.on_drag_data_received)
     tree.connect('drag_motion', self.on_drag_motion)
     tree.connect('drag_drop', self.on_drag_drop)
     renderer = gtk.CellRendererText()
     for n, t in [[0, 'Item'], [1, 'Amount']]:
         col = gtk.TreeViewColumn(t, renderer, text=n)
         col.set_resizable(True)
         tree.append_column(col)
     tree.expand_all()
     tree.show()
     return tree
Example #14
0
    def addRec (self, rec, mult, includes={}):
        debug("addRec (self, rec, mult, includes={}):",5)
        """Add recipe to our list, assuming it's not already there.
        includes is a dictionary of optional items we want to include/exclude."""
        self.recs[rec.id]=(rec,mult)
        self.includes[rec.id]=includes
	self.reset()
Example #15
0
    def adjust_unit (self, amt, unit, item=None, favor_current_unit=True, preferred_unit_groups=[]):

        """Return the most readable equivalent of amount and unit for item ITM

        amt - our amount
        unit - our current unit
        item - the item (in case it makes a difference -- currently not implemented)
        favor_current_item - a flag; if True (default) we give our current unit a slight
                             preference, to avoid changing the unit if unnecessary.
        Here we do our best to provide readable units, so that the user is presented
        with 1/2 cup rather than 8 tablespoons, for example.
        """
        if not amt: return amt,unit
        try:
            u = self.unit_dict[unit]
            ugroup,n = defaults.unit_group_lookup[u]
        except KeyError:
            return amt,unit
        else:
            units=defaults.UNIT_GROUPS[ugroup]                
            if preferred_unit_groups:
                if ugroup not in preferred_unit_groups:
                    for ug in preferred_unit_groups:
                        conv = self.converter(u,defaults.UNIT_GROUPS[ug][0][0])
                        if conv:
                            units = defaults.UNIT_GROUPS[ug]
                            amt = conv * amt
                            u = unit = defaults.UNIT_GROUPS[ug][0][0]
                            break
                        else:
                            continue
            ret_readability = self.readability_score(amt,unit)
            if favor_current_unit: ret_readability += 1
            ret_amt = amt
            ret_unit = unit
            ret_distance = 0
            n1 = 0
            for u2,rng in units:
                conv = self.converter(u,u2)
                if not conv:
                    continue
                new_amt = conv * amt
                readability = self.readability_score(new_amt,u2)
                debug('%s %s, Readability = %s'%(new_amt,u2,readability),6)
                use_us = False
                if readability > ret_readability:
                    use_us = True
                elif readability == ret_readability and abs(n-n1) < ret_distance:
                    use_us = True
                if use_us:
                    ret_amt = new_amt
                    ret_distance = abs(n-n1)
                    ret_unit = u2
                    ret_readability = readability
                n1 += 1
            debug('adjust unit called with %s %s, returning %s %s (R:%s)'%(amt,unit,ret_amt,ret_unit,
                                                                           ret_readability),
                  3)
            return ret_amt,ret_unit
Example #16
0
    def adjust_unit (self, amt, unit, item=None, favor_current_unit=True, preferred_unit_groups=[]):

        """Return the most readable equivalent of amount and unit for item ITM

        amt - our amount
        unit - our current unit
        item - the item (in case it makes a difference -- currently not implemented)
        favor_current_item - a flag; if True (default) we give our current unit a slight
                             preference, to avoid changing the unit if unnecessary.
        Here we do our best to provide readable units, so that the user is presented
        with 1/2 cup rather than 8 tablespoons, for example.
        """
        if not amt: return amt,unit
        try:
            u = self.unit_dict[unit]
            ugroup,n = defaults.unit_group_lookup[u]
        except KeyError:
            return amt,unit
        else:
            units=defaults.UNIT_GROUPS[ugroup]                
            if preferred_unit_groups:
                if ugroup not in preferred_unit_groups:
                    for ug in preferred_unit_groups:
                        conv = self.converter(u,defaults.UNIT_GROUPS[ug][0][0])
                        if conv:
                            units = defaults.UNIT_GROUPS[ug]
                            amt = conv * amt
                            u = unit = defaults.UNIT_GROUPS[ug][0][0]
                            break
                        else:
                            continue
            ret_readability = self.readability_score(amt,unit)
            if favor_current_unit: ret_readability += 1
            ret_amt = amt
            ret_unit = unit
            ret_distance = 0
            n1 = 0
            for u2,rng in units:
                conv = self.converter(u,u2)
                if not conv:
                    continue
                new_amt = conv * amt
                readability = self.readability_score(new_amt,u2)
                debug('%s %s, Readability = %s'%(new_amt,u2,readability),6)
                use_us = False
                if readability > ret_readability:
                    use_us = True
                elif readability == ret_readability and abs(n-n1) < ret_distance:
                    use_us = True
                if use_us:
                    ret_amt = new_amt
                    ret_distance = abs(n-n1)
                    ret_unit = u2
                    ret_readability = readability
                n1 += 1
            debug('adjust unit called with %s %s, returning %s %s (R:%s)'%(amt,unit,ret_amt,ret_unit,
                                                                           ret_readability),
                  3)
            return ret_amt,ret_unit
Example #17
0
 def selection_changedCB (self, *args):
     """We pass along true or false to selection_changed
     to say whether there is a selection or not."""
     debug("selection_changed (self, *args):",5)
     v=self.rectree.get_selection().get_selected_rows()[1]
     if v: selected=True
     else: selected=False
     self.selection_changed(v)
Example #18
0
 def grabIngsFromRecs (self, recs, start=[]):
     debug("grabIngsFromRecs (self, recs):",5)
     """Handed an array of (rec . mult)s, we combine their ingredients.
     recs may be IDs or objects."""
     self.lst = start[0:]
     for rec,mult in recs:
         self.lst.extend(self.grabIngFromRec(rec,mult=mult))
     return self.organize_list(self.lst)
Example #19
0
 def selection_changedCB(self, *args):
     """We pass along true or false to selection_changed
     to say whether there is a selection or not."""
     debug("selection_changed (self, *args):", 5)
     v = self.rectree.get_selection().get_selected_rows()[1]
     if v: selected = True
     else: selected = False
     self.selection_changed(v)
Example #20
0
 def toggle_ing_cb(self, cellrenderertoggle, path, *args):
     debug("toggle_ing_cb (self, cellrenderertoggle, path, *args):", 5)
     crt = cellrenderertoggle
     iter = self.mod.get_iter(path)
     val = self.mod.get_value(iter, 4)
     newval = not val
     self.ret[self.mod.get_value(iter, 0).ingkey] = newval
     self.mod.set_value(iter, 4, newval)
Example #21
0
 def reset_search(self, *args):
     debug("reset_search (self, *args):", 5)
     self.srchLimitLabel.set_text(self.srchLimitDefaultText)
     self.srchLimitText = self.srchLimitDefaultText
     self.srchLimitBar.hide()
     self.searches = self.default_searches[0:]
     self.last_search = {}  # reset search so we redo it
     self.search()
Example #22
0
 def toggle_ing_cb (self, cellrenderertoggle, path, *args):
     debug("toggle_ing_cb (self, cellrenderertoggle, path, *args):",5)
     crt=cellrenderertoggle
     iter=self.mod.get_iter(path)
     val = self.mod.get_value(iter,4)
     newval = not val
     self.ret[self.mod.get_value(iter,0).ingkey]=newval
     self.mod.set_value(iter,4,newval)
 def change_encoding (self):
     if self.cursor_already_set:
         im=self.buffer.get_insert()
         ti=self.buffer.get_iter_at_mark(im)
         offset=ti.get_offset()
     self.tv.set_buffer(self.encoding_buffers[self.ret])
     self.buffer = self.encoding_buffers[self.ret]
     debug('changed text to encoding %s'%self.ret,0)        
Example #24
0
 def change_encoding(self):
     if self.cursor_already_set:
         im = self.buffer.get_insert()
         ti = self.buffer.get_iter_at_mark(im)
         offset = ti.get_offset()
     self.tv.set_buffer(self.encoding_buffers[self.ret])
     self.buffer = self.encoding_buffers[self.ret]
     debug('changed text to encoding %s' % self.ret, 0)
Example #25
0
 def reset_search (self, *args):
     debug("reset_search (self, *args):",5)
     self.srchLimitLabel.set_text(self.srchLimitDefaultText)
     self.srchLimitText=self.srchLimitDefaultText
     self.srchLimitBar.hide()
     self.searches = self.default_searches[0:]
     self.last_search={} # reset search so we redo it
     self.search()
Example #26
0
 def grabIngsFromRecs(self, recs, start=[]):
     debug("grabIngsFromRecs (self, recs):", 5)
     """Handed an array of (rec . mult)s, we combine their ingredients.
     recs may be IDs or objects."""
     self.lst = start[0:]
     for rec, mult in recs:
         self.lst.extend(self.grabIngFromRec(rec, mult=mult))
     return self.organize_list(self.lst)
Example #27
0
 def create_rmodel (self):
     debug("create_rmodel (self):",5)
     mod = gtk.TreeStore(gobject.TYPE_PYOBJECT, gobject.TYPE_STRING, gobject.TYPE_STRING)
     for r,mult in self.recs.values():
         iter = mod.append(None)
         mod.set_value(iter,0,r)
         mod.set_value(iter,1,r.title)
         mod.set_value(iter,2,convert.float_to_frac(mult))
     return mod
Example #28
0
 def save (self, *args):
     debug("save (self, *args):",5)
     self.doSave(de.select_file(_("Save Shopping List As..."),
                                filename=os.path.join(os.path.expanduser("~"),
                                                      "%s %s"%(_('Shopping List'),
                                                               time.strftime("%x").replace("/","-"),
                                                               )),
                                action=gtk.FILE_CHOOSER_ACTION_SAVE,
                                ))
Example #29
0
 def create_rmodel (self):
     debug("create_rmodel (self):",5)
     mod = gtk.TreeStore(gobject.TYPE_PYOBJECT, gobject.TYPE_STRING, gobject.TYPE_STRING)
     for r,mult in self.recs.values():
         iter = mod.append(None)
         mod.set_value(iter,0,r)
         mod.set_value(iter,1,r.title)
         mod.set_value(iter,2,convert.float_to_frac(mult))
     return mod
Example #30
0
 def save (self, *args):
     debug("save (self, *args):",5)
     self.doSave(de.select_file(_("Save Shopping List As..."),
                                filename=os.path.join(os.path.expanduser("~"),
                                                      "%s %s"%(_('Shopping List'),
                                                               time.strftime("%x").replace("/","-"),
                                                               )),
                                action=gtk.FILE_CHOOSER_ACTION_SAVE,
                                ))
Example #31
0
 def rem_selection_from_pantry (self, *args):
     """Add selected items to shopping list."""
     debug("rem_selection_from_pantry (self, *args):",5)
     self.tv = self.pTree
     self.ssave=te.selectionSaver(self.slTree,1)
     self.pssave=te.selectionSaver(self.pTree,1)
     for k in self.get_selected_ingredients():
         self.sh.remove_from_pantry(k)
     self.resetSL()
     self.pssave.restore_selections(tv=self.slTree)
Example #32
0
 def rem_selection_from_pantry(self, *args):
     """Add selected items to shopping list."""
     debug("rem_selection_from_pantry (self, *args):", 5)
     self.tv = self.pTree
     self.ssave = te.selectionSaver(self.slTree, 1)
     self.pssave = te.selectionSaver(self.pTree, 1)
     for k in self.get_selected_ingredients():
         self.sh.remove_from_pantry(k)
     self.resetSL()
     self.pssave.restore_selections(tv=self.slTree)
Example #33
0
 def visibility_fun (self, model, iter):
     try:
         if (model.get_value(iter,0) and
             not model.get_value(iter,0).deleted and
             model.get_value(iter, 0).id in self.visible):
             return True
         else: return False
     except:
         debug('something bizaare just happened in visibility_fun',1)
         return False
Example #34
0
 def popup_pan_menu(self, tv, event=None, *args):
     debug("popup_pan_menu (self, tv, *args):", 5)
     self.tv = tv
     if not event:
         event = gtk.get_current_event()
     t = (event and hasattr(event, 'time') and getattr(event, 'time') or 0)
     btn = (event and hasattr(event, 'button') and getattr(event, 'button')
            or 0)
     self.panpop.popup(None, None, None, btn, t)
     return True
Example #35
0
 def visibility_fun (self, model, iter):
     try:
         if (model.get_value(iter,0) and
             not model.get_value(iter,0).deleted and
             model.get_value(iter, 0).id in self.visible):
             return True
         else: return False
     except:
         debug('something bizaare just happened in visibility_fun',1)
         return False
Example #36
0
 def add_selection_to_pantry(self, *args):
     """Add selected items to pantry."""
     debug("add_selection_to_pantry (self, *args):", 5)
     self.tv = self.slTree
     self.ssave = te.selectionSaver(self.slTree, 1)
     self.pssave = te.selectionSaver(self.pTree, 1)
     kk = self.get_selected_ingredients()
     for k in kk:
         self.sh.add_to_pantry(k)
     self.resetSL()
     self.ssave.restore_selections(tv=self.pTree)
Example #37
0
 def add_selection_to_pantry (self, *args):
     """Add selected items to pantry."""
     debug("add_selection_to_pantry (self, *args):",5)
     self.tv = self.slTree
     self.ssave=te.selectionSaver(self.slTree,1)
     self.pssave=te.selectionSaver(self.pTree,1)
     kk = self.get_selected_ingredients()
     for k in kk:
         self.sh.add_to_pantry(k)
     self.resetSL()
     self.ssave.restore_selections(tv=self.pTree)
Example #38
0
 def popup_pan_menu (self, tv, event=None, *args):
     debug("popup_pan_menu (self, tv, *args):",5)
     self.tv = tv
     if not event:
         event = gtk.get_current_event()
     t = (event and hasattr(event,'time') and getattr(event,'time')
             or 0)
     btn = (event and hasattr(event,'button') and getattr(event,'button')
            or 0)
     self.panpop.popup(None,None,None,btn,t)
     return True
Example #39
0
 def resetSL(self):
     debug("resetSL (self):", 5)
     if not hasattr(self, 'cats_setup') or not self.cats_setup:
         self.setup_category_ui()
     self.data, self.pantry = self.organize_list(self.lst)
     self.slMod = self.createIngModel(self.data)
     self.pMod = self.createIngModel(self.pantry)
     self.slTree.set_model(self.slMod)
     self.pTree.set_model(self.pMod)
     # self.rectree.set_model(self.create_rmodel())
     self.slTree.expand_all()
     self.pTree.expand_all()
Example #40
0
    def resetSL (self):
        debug("resetSL (self):",5)
	if not hasattr(self,'cats_setup') or not self.cats_setup:
	    self.setup_category_ui()
        self.data,self.pantry = self.organize_list(self.lst)
        self.slMod = self.createIngModel(self.data)
        self.pMod = self.createIngModel(self.pantry)
        self.slTree.set_model(self.slMod)
        self.pTree.set_model(self.pMod)
        #self.rectree.set_model(self.create_rmodel())
        self.slTree.expand_all()
        self.pTree.expand_all()
Example #41
0
    def build_converter_dictionary(self, table=None, density=False):
        # first, make a list of all units in our dictionaries
        if not density:
            convert = self.convert_simple
        else:

            def convert(u1, u2):
                # Ignore anything that doesn't need density
                if self.convert_simple(u1, u2):
                    return None
                return self.convert_w_density(u1, u2, density=1)

        units = []
        if not table:
            table = self.conv_table
        # else:
        # print "We were handed a table: ",table
        for u1, u2 in filter(lambda x: len(x) == 2, table.keys()):
            if u1 not in units:
                units.append(u1)
            if u2 not in units:
                units.append(u2)
        # print 'done looping through list'
        for u in units:
            # print 'grabbing possible conversions for ',u
            debug("unit=%s" % u)
            d = self.possible_conversions(u, dict=table)
            to_expand = d.keys()
            # keep a list of what we've expanded
            expanded = []
            while len(to_expand) >= 1:
                itm = to_expand.pop()
                if itm not in expanded:
                    # debug('Expanding %s'%itm)
                    factor = convert(itm, u)
                    # debug('There are %s %s in a %s'%(factor,u,itm))
                    d2 = self.possible_conversions(itm)
                    if factor:
                        for k, v in d2.items():
                            if not convert(u, k):
                                # debug('and there are %s %s in a %s'%(v,itm,k))
                                conversion = float(v) * float(factor)
                                # If we're doing density, we want to
                                # make sure we always have our tuples
                                # (volume,density)
                                if density and itm not in [key[0] for key in table.keys()]:
                                    table[(u, k)] = float(1) / conversion
                                else:
                                    table[(k, u)] = conversion
                            if k not in expanded and k not in to_expand and k != itm and k != u:
                                to_expand.append(k)
                    expanded.append(itm)
Example #42
0
 def getSelectedRecs (self):
     """Return each recipe in list"""
     def foreach(model,path,iter,recs):
         debug("foreach(model,path,iter,recs):",5)
         try:
             rec=model.get_value(iter,0)
             recs.append(rec)
         except:
             debug("DEBUG: There was a problem with iter: %s path: %s"%(iter,path),1)
     recs=[]
     self.rectree.get_selection().selected_foreach(foreach,recs)
     debug("%s selected recs: %s"%(len(recs),recs),3)
     return recs
Example #43
0
 def getSelectedRecs (self):
     """Return each recipe in list"""
     def foreach(model,path,iter,recs):
         debug("foreach(model,path,iter,recs):",5)
         try:
             rec=model.get_value(iter,0)
             recs.append(rec)
         except:
             debug("DEBUG: There was a problem with iter: %s path: %s"%(iter,path),1)
     recs=[]
     self.rectree.get_selection().selected_foreach(foreach,recs)
     debug("%s selected recs: %s"%(len(recs),recs),3)
     return recs
Example #44
0
    def build_converter_dictionary(self, table=None, density=False):
        # first, make a list of all units in our dictionaries
        if not density:
            convert = self.convert_simple
        else:

            def convert(u1, u2):
                # Ignore anything that doesn't need density
                if self.convert_simple(u1, u2): return None
                return self.convert_w_density(u1, u2, density=1)

        units = []
        if not table:
            table = self.conv_table
        #else:
        #print "We were handed a table: ",table
        for u1, u2 in filter(lambda x: len(x) == 2, table.keys()):
            if u1 not in units: units.append(u1)
            if u2 not in units: units.append(u2)
        #print 'done looping through list'
        for u in units:
            #print 'grabbing possible conversions for ',u
            debug('unit=%s' % u)
            d = self.possible_conversions(u, dict=table)
            to_expand = d.keys()
            # keep a list of what we've expanded
            expanded = []
            while len(to_expand) >= 1:
                itm = to_expand.pop()
                if itm not in expanded:
                    #debug('Expanding %s'%itm)
                    factor = convert(itm, u)
                    #debug('There are %s %s in a %s'%(factor,u,itm))
                    d2 = self.possible_conversions(itm)
                    if factor:
                        for k, v in d2.items():
                            if not convert(u, k):
                                #debug('and there are %s %s in a %s'%(v,itm,k))
                                conversion = float(v) * float(factor)
                                # If we're doing density, we want to
                                # make sure we always have our tuples
                                # (volume,density)
                                if density and itm not in [
                                        key[0] for key in table.keys()
                                ]:
                                    table[(u, k)] = float(1) / conversion
                                else:
                                    table[(k, u)] = conversion
                            if k not in expanded and k not in to_expand and k != itm and k != u:
                                to_expand.append(k)
                    expanded.append(itm)
Example #45
0
 def createIngModel(self, data):
     debug("createIngModel (self, data):", 5)
     """Data is a list of lists, where each item is [ing amt]"""
     mod = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_STRING)
     for c, lst in data:
         catiter = mod.append(None)
         mod.set_value(catiter, 0, c)
         for i in lst:
             ing = i[0]
             amt = i[1]
             iter = mod.append(catiter)
             mod.set_value(iter, 0, ing)
             mod.set_value(iter, 1, amt)
     return mod
Example #46
0
 def createIngModel (self, data):
     debug("createIngModel (self, data):",5)
     """Data is a list of lists, where each item is [ing amt]"""
     mod = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_STRING)
     for c,lst in data:
         catiter = mod.append(None)
         mod.set_value(catiter, 0, c)
         for i in lst:
             ing = i[0]
             amt = i[1]
             iter = mod.append(catiter)
             mod.set_value(iter, 0, ing)
             mod.set_value(iter, 1, amt)
     return mod
 def __init__ (self,file,encodings=None):
     CheckEncoding.__init__(self,file,encodings)
     encs=self.get_encodings()
     if encs:
         if len(encs.keys()) > 1:
             encoding = getEncoding(encodings=encs)
         else:
             encoding = encs.keys()[0]
         self.enc = encoding
         self.lines = encs[self.enc].splitlines()
         debug('reading file %s as encoding %s'%(file, self.enc))
         self.lines = [l.encode() for l in self.lines]
     else:
         raise Exception("Cannot decode file %s" % file)
Example #48
0
 def load_plugin_directories (self):
     """Look through plugin directories for plugins.
     """
     self.available_plugin_sets = {}
     for d in self.plugin_directories:
         debug('Loading plugins from %s'%os.path.realpath(d),1)
         plugins = glob.glob(os.path.join(d,'*.gourmet-plugin'))
         for ppath in plugins:
             debug('Found %s'%ppath,1)
             plugin_set = PluginSet(ppath)
             if self.available_plugin_sets.has_key(plugin_set.module):
                 print 'Ignoring duplicate plugin ',plugin_set.module,'found in ',ppath
             else:
                 self.available_plugin_sets[plugin_set.module] = plugin_set
Example #49
0
 def __init__(self, file, encodings=None):
     CheckEncoding.__init__(self, file, encodings)
     encs = self.get_encodings()
     if encs:
         if len(encs.keys()) > 1:
             encoding = getEncoding(encodings=encs)
         else:
             encoding = encs.keys()[0]
         self.enc = encoding
         self.lines = encs[self.enc].splitlines()
         debug('reading file %s as encoding %s' % (file, self.enc))
         self.lines = [l.encode() for l in self.lines]
     else:
         raise Exception("Cannot decode file %s" % file)
Example #50
0
 def initialize_categories (self):
     """We treat things like flour as categories, usually
     designated as "flour, all purpose" or "flour, whole wheat". We
     look for this sort of thing, assuming the noun, descriptor
     format has been followed previously. With our handy list, we
     will more easily be able to guess correctly that barley flour
     should be flour, barley"""
     debug("Start initialize_categories",10)
     self.cats = []
     for k in self.rm.get_unique_values('ingkey',self.rm.ingredients_table,deleted=False):
         fnd=k.find(',')
         if fnd != -1:
             self.cats.append(k[0:fnd])
     debug("End initialize_categories",10)
Example #51
0
 def get_key (self,txt, certainty=0.61):
     """Grab a single key. This is simply a best guess at the
     right key for an item (we can't be sure -- if we could be,
     we wouldn't need a key system in the first place!"""
     debug("Start get_key %s"%str,10)
     if not txt: return ''
     txt = snip_notes(txt)
     result = self.look_for_key(txt)
     if result and result[0][0] and result[0][1] > certainty:
         k=result[0][0]
     else:
         k=self.generate_key(txt)
     debug("End get_key",10)
     return k
Example #52
0
    def __init__(self, inglist):
        """We expect a list of tuples/lists, each of which contains
        amount, unit, key [[amt,un,key],[amt,un,key],...]

        amount can be either a single number or a tuple
        2,3, etc., in which case it is a range.
        """
        ## First, we create a dictionary from our list (keyed by ingredient)
        ## each value in the dict. is a list of values. We'll try to add these
        ## as best as we can.
        self.dic = {}
        self.default_pantry = [
            _('flour, all purpose'),
            _('sugar'),
            _('salt'),
            _('black pepper, ground'),
            _('ice'),
            _('water'),
            _('oil, vegetable'),
            _('oil, olive')
        ]
        self.init_pantry()
        self.mypantry = {}
        for a, u, k in inglist:
            if self.pantry.has_key(k) and self.pantry[k]:
                #print "%s is in pantry" %k
                dic = self.mypantry
            else:
                dic = self.dic
            try:
                a = float(a)
            except:
                if type(a) != tuple:
                    debug(
                        "Warning, can't make sense of amount %s; reading as None"
                        % a, 0)
                    a = None
            if dic.has_key(k):
                dic[k].append([a, u])
            else:
                dic[k] = [[a, u]]
        self.init_converter()
        for ing, amts in self.dic.items():
            self.dic[ing] = self.combine_ingredient(ing, amts)
        for ing, amts in self.mypantry.items():
            self.mypantry[ing] = self.combine_ingredient(ing, amts)
        self.init_orgdic()
        self.init_ingorder_dic()
        self.init_catorder_dic()
Example #53
0
 def limit_search (self, *args):
     debug("limit_search (self, *args):",5)
     self.search() # make sure we've done the search...
     self.searches.append(self.last_search)
     last_col = self.last_search['column']
     self.srchLimitBar.show()
     if last_col != _('anywhere'):
         newtext = ' ' + _('%s in %s')%(self.srchentry.get_text(),last_col)
     else:
         newtext = ' ' + self.srchentry.get_text()
     if self.srchLimitDefaultText!=self.srchLimitLabel.get_text():
         newtext = ',' + newtext
     self.srchLimitText="%s%s"%(self.srchLimitLabel.get_text(),newtext)
     self.srchLimitLabel.set_markup("<i>%s</i>"%self.srchLimitText)
     self.srchentry.set_text("")
Example #54
0
 def limit_search (self, *args):
     debug("limit_search (self, *args):",5)
     self.search() # make sure we've done the search...
     self.searches.append(self.last_search)
     last_col = self.last_search['column']
     self.srchLimitBar.show()
     if last_col != _('anywhere'):
         newtext = ' ' + _('%s in %s')%(self.srchentry.get_text(),last_col)
     else:
         newtext = ' ' + self.srchentry.get_text()
     if self.srchLimitDefaultText!=self.srchLimitLabel.get_text():
         newtext = ',' + newtext
     self.srchLimitText="%s%s"%(self.srchLimitLabel.get_text(),newtext)
     self.srchLimitLabel.set_markup("<i>%s</i>"%self.srchLimitText)
     self.srchentry.set_text("")
Example #55
0
    def create_slTree (self):
        debug("create_slTree (self, data):",5)
        self.slMod = self.createIngModel(self.data)
	self.slTree = self.create_ingTree(gtk.TreeView(),
					  self.slMod)
	self.slTree.show()
        self.slTree.connect('popup-menu',self.popup_ing_menu)
        def slTree_popup_cb (tv, event):
            debug("slTree_popup_cb (tv, event):",5)
            if event.button==3 or event.type == gtk.gdk._2BUTTON_PRESS:
                self.popup_ing_menu(tv,event)
                return True
        self.slTree.connect('button-press-event',slTree_popup_cb)
        self.slTree.get_selection().connect('changed',self.slTree_sel_changed_cb)
        # reset the first time
        self.slTree_sel_changed_cb(self.slTree.get_selection())
Example #56
0
 def get_selected_recs_from_rec_tree (self):
     debug("get_selected_recs_from_rec_tree (self):",5)
     def foreach(model,path,iter,recs):
         debug("foreach(model,path,iter,recs):",5)
         try:
             recs.append(model[path][0])
             #recs.append(self.get_rec_from_iter(iter))
         except:
             debug("DEBUG: There was a problem with iter: %s path: %s"%(iter,path),1)
     recs=[]
     sel = self.rectree.get_selection()
     if sel:
         sel.selected_foreach(foreach,recs)
         return recs
     else:
         return []