widget_element_button.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "widget_element_i.h"
  2. #include <gui/elements.h>
  3. typedef struct {
  4. GuiButtonType button_type;
  5. FuriString* text;
  6. ButtonCallback callback;
  7. void* context;
  8. } GuiButtonModel;
  9. static void gui_button_draw(Canvas* canvas, WidgetElement* element) {
  10. furi_assert(canvas);
  11. furi_assert(element);
  12. GuiButtonModel* model = element->model;
  13. canvas_set_color(canvas, ColorBlack);
  14. canvas_set_font(canvas, FontSecondary);
  15. if(model->button_type == GuiButtonTypeLeft) {
  16. elements_button_left(canvas, furi_string_get_cstr(model->text));
  17. } else if(model->button_type == GuiButtonTypeRight) {
  18. elements_button_right(canvas, furi_string_get_cstr(model->text));
  19. } else if(model->button_type == GuiButtonTypeCenter) {
  20. elements_button_center(canvas, furi_string_get_cstr(model->text));
  21. }
  22. }
  23. static bool gui_button_input(InputEvent* event, WidgetElement* element) {
  24. GuiButtonModel* model = element->model;
  25. bool consumed = false;
  26. if(model->callback == NULL) return consumed;
  27. if((model->button_type == GuiButtonTypeLeft) && (event->key == InputKeyLeft)) {
  28. model->callback(model->button_type, event->type, model->context);
  29. consumed = true;
  30. } else if((model->button_type == GuiButtonTypeRight) && (event->key == InputKeyRight)) {
  31. model->callback(model->button_type, event->type, model->context);
  32. consumed = true;
  33. } else if((model->button_type == GuiButtonTypeCenter) && (event->key == InputKeyOk)) {
  34. model->callback(model->button_type, event->type, model->context);
  35. consumed = true;
  36. }
  37. return consumed;
  38. }
  39. static void gui_button_free(WidgetElement* gui_button) {
  40. furi_assert(gui_button);
  41. GuiButtonModel* model = gui_button->model;
  42. furi_string_free(model->text);
  43. free(gui_button->model);
  44. free(gui_button);
  45. }
  46. WidgetElement* widget_element_button_create(
  47. GuiButtonType button_type,
  48. const char* text,
  49. ButtonCallback callback,
  50. void* context) {
  51. // Allocate and init model
  52. GuiButtonModel* model = malloc(sizeof(GuiButtonModel)); //-V773
  53. model->button_type = button_type;
  54. model->callback = callback;
  55. model->context = context;
  56. model->text = furi_string_alloc_set(text);
  57. // Allocate and init Element
  58. WidgetElement* gui_button = malloc(sizeof(WidgetElement));
  59. gui_button->parent = NULL;
  60. gui_button->input = gui_button_input;
  61. gui_button->draw = gui_button_draw;
  62. gui_button->free = gui_button_free;
  63. gui_button->model = model;
  64. return gui_button;
  65. }