gui_element_button.c 2.6 KB

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