def handle(self, event, values): if event == '-VIEWER-PRINT-': if self.model.get('activeRecipe') == None: sg.PopupError("No recipe selected!", title="No Recipe") return True return True elif event == '-VIEWER-EXPORT-': if self.model.get('activeRecipe') == None: sg.PopupError("No recipe selected!", title="No Recipe") return True self.exportModal(self.model.get('activeRecipe')) return True elif event == '-VIEWER-SHARE-': if self.model.get('activeRecipe') == None: sg.PopupError("No recipe selected!", title="No Recipe") return True # self.model.get('activeRecipe').outputToTxt(self.model.get('prefs', 'recipeFolder') + 'text.txt') return True elif event == '-VIEWER-EDIT-': # navigate to editor tab if self.model.get('activeRecipe') == None: sg.PopupError("No recipe selected!", title="No Recipe") return True self.model.set('active_view', value='-EDITOR-') return True elif event == '-VIEWER-MULTBY-': if self.model.get('activeRecipe') == None: sg.PopupError("No recipe selected!", title="No Recipe") self.multby.update('1') return True self.fillFields( recipe(copyme=self.model.get('activeRecipe')) * float(values['-VIEWER-MULTBY-'])) return True return False
def handle(self, event, values): if event == '-VIEW-RECIPE-': # recipe is saved then sent to viewer self.saveFields() # self.recipe_modal(self.getFields()) rec = self.getFields() self.model.set('activeRecipe', value=rec) self.model.set('active_view', value='-VIEWER-') return True elif event == '-SAVE-RECIPE-': self.saveFields() return True elif event == '-DELETE-RECIPE-': if self.model.get('activeRecipe') == None: sg.PopupError("No recipe selected!", title="No Recipe") return True # delete recipe and return to table view self.delete() self.model.set('active_view', value='-TABLE-') self.model.notifyOberservers() return True elif event == '-NEW-RECIPE-': # self.clearFields() # print('clear recipe called') if len(self.model.window[self.recFields['Title']].get()) > 0 and\ sg.popup_yes_no('Would you like to save before clearing?', title='Save?'): self.saveFields() self.model.set('activeRecipe', value=recipe()) return True elif event == '-INGREDIENT-SBUTTON-': self.getIngResults(values['-INGREDIENT-SBOX-']) return True elif event == self.recIngKey: ing = ingredient( self.model.get('newRecipe').ingredients[values[self.recIngKey] [0]]) self.ingredient_modal(ing) elif event == '-ADD-INGREDIENT-': # print(values) amount = values['-AMOUNT-'] if '/' in amount: matcher = recipeEditorController.mixed_number.match(amount) whole = float( matcher.group(1)) if len(matcher.group(1)) > 0 else 0 amount = f'{whole + eval(matcher.group(2))}{matcher.group(3)}' try: float(amount.split(' ')[0]) except ValueError: sg.PopupError("amount given in incorrect form!") return True self.addIng(values[self.ingTableKey][0], amount) return True elif event == self.ingTableKey: self.add_ing_modal(values[self.ingTableKey][0]) self.model.notifyOberservers('newRecipe') return False
def mainLoop(self, window=None): # if given window, use that window for this function # and restore the old window at the end self.model.beginNotify() if window: windowBackup = self.window self.window = window if not self.window: raise Exception( "mainLoop called on MainController with no window specified!") # do stuff logger.debug('Main Loop Started') while True: event, values = self.window.read() logger.debug(f'event was {event}') # logger.debug(f'value is {values}') if event == sg.WIN_CLOSED or event == 'Exit': break if self.model.get("controllers", values['-TABS-']).handle(event, values): continue elif event == 'Preferences': # self.window.disable() self.prefEditor() # self.window.enable() elif event == 'Import Recipe': # import recipe recipe_files = sg.popup_get_file('Enter a recipe file...', multiple_files=True) if not recipe_files: continue recipe_files = recipe_files.split(';') for file in recipe_files: new_rec = recipe(file=file) if self.model.get('RecipeAPI').exists(new_rec): if sg.popup_yes_no( "This recipe already exists, do you want to overwrite it?", title="Overwrite?"): # save to db self.model.get('RecipeAPI').delete(new_rec) self.model.get('RecipeAPI').save(new_rec) else: self.model.get('RecipeAPI').save(new_rec) self.model.get('views')['-TABLE-'].Select() self.model.notifyOberservers('recipe import') # self.model.get('views')['-TABLE-'].refreshRecipeTable() elif event == 'Import Database': # import database pass self.window.close() if window: self.window = windowBackup
def recipes(self, first=0, last=None, count=1): """A function that returns a custom number of rows from recipes Input: first - int, number of the first row, default: 0 last - int, number of the last row count - int, number of rows to get, default: 1 NOTE: if last is specified, count is overwritten Output: array of recipe rows, with length of count""" if last: count = last - first res = self.db.cur.execute( f"SELECT * FROM recipes LIMIT {first}, {count}") return [recipe(i) for i in res]
def getFields(self): """Function that records all the information in the fields and returns a recipe object. Input: self.recFields: dictionary of all the recipe fields Output: recipe: recipe created from all the fields """ # result object, it is a temp holder for the information res = {} # iterate over recFields, field is string name of field being analyzed, # value is the actual text/entry itself for field in recipe.pretty_fields: if field == "Total Time": res["Total Time"] = res["Prep Time"] + res["Cook Time"] continue value = self.model.window[self.recFields[field]] if field == "Directions": # get info text = value.get() # data preprocessing, three things going on # text.split('\n') returns list of lines in textbox # list comprehension goes over the list and removes empty strings # then the list is stringed # res[field] = str([val for val in text.split('\n') if len(val) > 0]) res[field] = [val for val in text.split('\n') if len(val) > 0] elif field == "Ingredients": # text = value.get() # only the first two things happen here # temp = [val for val in text.split('\n') if len(val.strip()) > 0] # Additionally, the tuples are interpreted here, # then the whole thing is stringified # res[field] = [ingredient(s) for s in temp] res[field] = self.model.get('newRecipe').ingredients # for ing in res[field]: # if len(ing) != 3: # sg.PopupError(f'There is an error with the following ingredient, please delete it and re-add it: {ing}', title="Error!") # return None else: # else, it's an entry box res[field] = value.get() # create the recipe, the list comprehension is to put the dictionary in order # return recipe([res[key] for key in recipe.pretty_fields]) return recipe(res) if len(res['Title']) > 0 else None
def search(self, query, sortby=None): logger.debug(f'searching db for {query}') query = database.db_clean(query) # res = self.db.cur.execute("SELECT * FROM recipes WHERE name LIKE '%'||?||'%'", (query,)) command = f"SELECT * FROM recipes WHERE title LIKE ?" if not sortby in ['None', None]: sortby = sortby.lower() sortby = sortby.replace(' ', '_') command += f' ORDER BY ?' # print(command) res = self.db.cur.execute(command, ('%' + query + '%', sortby)) else: res = self.db.cur.execute(command, ('%' + query + '%', )) # self.unpack(res) return [recipe(i) for i in res]
def refreshView(self, model, key): if key == "activeRecipe": if model.get('activeRecipe') == None: self.clearFields() self.model.set("newRecipe", value=recipe(), notify=False) self.disable() else: self.fillFields(self.model.get('activeRecipe')) self.enable() self.model.set("newRecipe", value=self.model.get('activeRecipe'), notify=False) elif key == "active_view": if self.model.get("active_view") == "-EDITOR-": self.Select() elif key == "newRecipe": self.refreshTable()
def handle(self, event, values): if self.search.handle(event, values): return True if event == self.tableKey: # click on table, event to be handled by main # self.master.switchTabs('-EDITOR-') # self.master.deferHandle('-EDITOR-', 'fill', values) # self.model.get('views', ('-VIEWER-').Select() self.model.set('active_view', value='-VIEWER-') self.model.set('activeRecipe', value=self.model.get("tabData", "-TABLE-", "tableData")[values['-RECIPE-TABLE-'][0]]) return True elif event == '-RECIPE-SBUTTON-': self.searchdb(values['-RECIPE-SBOX-'], sortby=values['-TABLE-SORT-']) return True elif event == '-ADDNEW-': self.model.set('activeRecipe', value=recipe()) self.model.set('active_view', value='-EDITOR-') return True return False
def lookup(self, name='', source='', rec=None, recID=None): """Accepts either a name and source, or a recipe in the third slot""" if rec: name = rec.title source = rec.source elif recID: fields = recID.split(recipe.id_delimiter) name = fields[0] source = fields[1] if len(fields) > 1 else '' logger.debug(f'checking for {name} by {source}') if source == None: res = list( self.db.cur.execute( f"SELECT * FROM recipes WHERE title='{name}'")) else: res = list( self.db.cur.execute( f"SELECT * FROM recipes WHERE title='{name}' AND source='{source}'" )) return recipe(res[0]) if len(res) > 0 else None