aboutsummaryrefslogtreecommitdiff
path: root/src/saffron_widget.c
blob: 85b2013474fbf43894c718440076c82db5935f08 (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
58
59
#include <SDL3/SDL.h>
#include <stdlib.h>
#include <saffron_widget.h>
#include <saffron_api.h>
#include <saffron_window.h>

SaffronWidget* saffron_widget_new(void) {
	/* This function is a generic primitive for creating widgets. You wouldn't want to do this manually unless you're a lunatic. It is meant to be wrapped around by other functions that change the default parameters, for example, what sane person makes a widget 0x0x0x0? you LUNATIC! */
	SaffronWidget* widget = malloc(sizeof(SaffronWidget));

	widget->x = 0;
	widget->y = 0;
	widget->w = 0;
	widget->h = 0;

	widget->draw = NULL;
	widget->on_click = NULL;

	widget->parent = NULL;
	widget->children = NULL;
	widget->child_count = 0;

	return widget;
}

void saffron_widget_free(SaffronWidget *widget) {
	/* follow-up to my previous comment:
	 * yeah it is the caller's responsibility to check 
	 * for undefined behaviour but this one line will save
	 * so much time down the line */
	if (!widget) return;

	for (int i = 0; i < widget->child_count; i++) {
		saffron_widget_free(widget->children[i]);
	}

	free(widget->children);
	free(widget);
}

void saffron_widget_draw(SaffronWidget* widget, SDL_Renderer *renderer) {
	if (!widget) return;

	if (widget->draw) {
		widget->draw(widget, renderer);
	}

	for (int i = 0; i < widget->child_count; i++) {
		saffron_widget_draw(widget->children[i], renderer);
	}
}

void saffron_widget_add_child(SaffronWidget *parent, SaffronWidget *child) {
	child->parent = parent;
	parent->children = realloc(parent->children, sizeof(SaffronWidget*) * (parent->child_count + 1));
	parent->children[parent->child_count] = child;
	parent->child_count++;
}