aboutsummaryrefslogtreecommitdiff
path: root/src/saffron_button.c
blob: b7db2045bc64e707106696ac60923a61e26da1bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <SDL3/SDL.h>
#include <stdlib.h>
#include <saffron.h>

static void saffron_button_draw(SaffronWidget* widget, SDL_Renderer* renderer) {
	SaffronButton* btn = (SaffronButton*)widget;

	SaffronTheme* theme = widget->theme;
	if (!theme) return;
	SaffronColor bg = theme->bg;
	SaffronColor tertiary = theme->tertiary;
	SDL_SetRenderDrawColor(renderer, bg.r, bg.g, bg.b, bg.a);
	SDL_FRect rect = {widget->x, widget->y, widget->w, widget->h};
	SDL_RenderFillRect(renderer, &rect);

	SDL_SetRenderDrawColor(renderer, tertiary.r, tertiary.g, tertiary.b, tertiary.a);
	SDL_RenderRect(renderer, &rect);
}

static void saffron_button_onclick(SaffronWidget* self) {
	SaffronButton* btn = (SaffronButton*)self;
	btn->callback(btn);
}

SaffronButton* saffron_button_new(bool enabled, void (*callback)(SaffronButton* self), int width, int height) {
	SaffronButton* button = malloc(sizeof(SaffronButton));
	if (!button) return NULL;

	SaffronBox* box = saffron_box_new(SAFFRON_ORIENTATION_HORIZONTAL, SAFFRON_HALIGN_CENTER, SAFFRON_VALIGN_CENTER, 5, 5, 0, width, height);
	if (!box) {
		free(button);
		return NULL;
	}

	memcpy(&button->base, box, sizeof(SaffronBox));
	free(box);

	SaffronWidget* widget = (SaffronWidget*)button;
	// We set it to type BOX because the layout engine needs to treat it as one: I'll remove the BUTTON enum later or make the layout engine check for both
	widget->type = SAFFRON_WIDGET_BOX;
	widget->draw = saffron_button_draw;
	widget->on_click = saffron_button_onclick;
	widget->children = NULL;
	widget->child_count = 0;

	button->callback = callback;
	button->enabled = enabled;

	return button;
}

SaffronButton* saffron_button_new_with_text(SaffronText* text, bool enabled, void (*callback)(SaffronButton* self), int width, int height) {
	SaffronButton* button = saffron_button_new(enabled, callback, width, height);
	saffron_widget_add_child((SaffronWidget*)button, (SaffronWidget*)text);

	return button;
}