5 #include "system/stacktrace.h"
7 #include "system/nth_alloc.h"
8 #include "system/str.h"
9 #include "math/point.h"
10 #include "game/sprite_font.h"
12 #include "./list_selector.h"
17 const Sprite_font *sprite_font;
21 const char *selected_item;
24 ListSelector *create_list_selector(const Sprite_font *sprite_font,
35 ListSelector *list_selector = PUSH_LT(lt, nth_alloc(sizeof(ListSelector)), free);
36 if (list_selector == NULL) {
39 list_selector->lt = lt;
41 list_selector->sprite_font = sprite_font;
42 list_selector->items = items;
43 list_selector->count = count;
44 list_selector->cursor = 0;
45 list_selector->selected_item = NULL;
50 void destroy_list_selector(ListSelector *list_selector)
52 trace_assert(list_selector);
53 RETURN_LT0(list_selector->lt);
56 int list_selector_render(const ListSelector *list_selector,
57 SDL_Renderer *renderer,
62 trace_assert(list_selector);
63 trace_assert(renderer);
65 for (size_t i = 0; i < list_selector->count; ++i) {
66 const Vec current_position = vec_sum(
68 vec(0.0f, (float) i * ((float) FONT_CHAR_HEIGHT * font_scale.y + padding_bottom)));
70 if (sprite_font_render_text(
71 list_selector->sprite_font,
75 rgba(1.0f, 1.0f, 1.0f, 1.0f),
76 list_selector->items[i]) < 0) {
80 if (i == list_selector->cursor) {
81 SDL_Rect boundary_box = rect_for_sdl(
82 sprite_font_boundary_box(
83 list_selector->sprite_font,
86 list_selector->items[i]));
87 if (SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255) < 0) {
91 if (SDL_RenderDrawRect(renderer, &boundary_box) < 0) {
100 Vec list_selector_size(const ListSelector *list_selector,
102 float padding_bottom)
104 trace_assert(list_selector);
106 Vec result = vec(0.0f, 0.0f);
108 for (size_t i = 0; i < list_selector->count; ++i) {
109 Rect boundary_box = sprite_font_boundary_box(
110 list_selector->sprite_font,
113 list_selector->items[i]);
115 result.x = fmaxf(result.x, boundary_box.w);
116 result.y += boundary_box.y + padding_bottom;
122 int list_selector_update(ListSelector *list_selector, float delta_time)
124 trace_assert(list_selector);
130 int list_selector_event(ListSelector *list_selector, const SDL_Event *event)
132 trace_assert(list_selector);
135 switch (event->type) {
137 switch (event->key.keysym.sym) {
139 if (list_selector->cursor > 0) {
140 list_selector->cursor--;
144 if (list_selector->cursor < list_selector->count - 1) {
145 list_selector->cursor++;
149 list_selector->selected_item = list_selector->items[list_selector->cursor];
158 const char *list_selector_selected(const ListSelector *list_selector)
160 trace_assert(list_selector);
161 return list_selector->selected_item;
164 void list_selector_clean_selection(ListSelector *list_selector)
166 trace_assert(list_selector);
167 list_selector->selected_item = NULL;