Files
frontend-dev/frontend/views/recipes/recipe_selection.py

100 lines
3.3 KiB
Python

from typing import Tuple
from ..base import View
from ..button_interface import ButtonInterface
from ..list_select import ListItem, ListView, CarouselView
from .recipe_manager import RecipeManager
from PIL import ImageDraw, Image
def _make_text_item(text):
"""ListItem that renders as plain text (forwards kwargs such as font_size)."""
return ListItem(lambda draw, pos, fill, t=text, **kw: draw.text(pos, str(t), fill=fill, **kw))
class RecipeSelection(View, ButtonInterface):
@property
def recipes(self):
return self.recipe_manager.recipes
def __init__(self, parent, im_size, center,
recipe_manager: RecipeManager = None,
edit_recipe_command=None,
run_recipe_command=None,
deactivate_command=None):
self.deactivate_command = deactivate_command
self.recipe_manager = recipe_manager
self.edit_recipe_command = edit_recipe_command
self.run_recipe_command = run_recipe_command
self.item_list = CarouselView(render_height=124)
# self.item_list = ListView(x_offset=40, max_visible=5)
self._rebuild_items()
super().__init__(parent, im_size, center)
def _rebuild_items(self):
"""Rebuild list items from current recipes."""
old_index = self.item_list.selected_index
items = [_make_text_item(r) for r in self.recipes]
items.append(_make_text_item('+'))
self.item_list.items = items
self.item_list.selected_index = min(old_index, len(items) - 1)
def update_weight(self, weight: float) -> Image.Image:
im = self.bkg_im.copy()
draw = ImageDraw.Draw(im)
self._rebuild_items()
self.item_list.render(draw, y_start=10)
return im
def left_press(self):
self.item_list.select_previous()
def left_long_press(self):
self.item_list.selected_index = 0
self.deactivate_command()
def right_press(self):
self.item_list.select_next()
def right_long_press(self):
idx = self.item_list.selected_index
if idx < len(self.recipes):
# run selected recipe
if self.run_recipe_command:
self.run_recipe_command(idx)
elif idx == len(self.recipes):
# add new recipe
self.edit_recipe_command()
def both_long_press(self):
idx = self.item_list.selected_index
if idx < len(self.recipes):
self.edit_recipe_command(idx)
def has_button(self) -> Tuple[bool, bool, bool, bool]:
return True, True, True, True
def render_left_press(self, draw, x, y):
draw.regular_polygon((x, y+2, 5), 3, fill='black')
def render_left_long_press(self, draw, x, y):
draw.text((x, y-5), 'Back', fill='black')
def render_right_press(self, draw, x, y):
draw.regular_polygon((x, y+4, 5), 3, fill='black', rotation=180)
def render_right_long_press(self, draw, x, y):
idx = self.item_list.selected_index
if idx < len(self.recipes):
draw.text((x - 15, y-5), 'Run', fill='black')
else:
draw.text((x - 15, y-5), 'Add', fill='black')
def render_both_long_press(self, draw, x, y):
idx = self.item_list.selected_index
if idx < len(self.recipes):
draw.text((x - 10, y - 5), 'Edit', fill='black')