From 072f42236fb0d2509608a3ad345df2c5cf71f8dd Mon Sep 17 00:00:00 2001 From: P. J. McDermott Date: Wed, 04 Aug 2021 19:58:00 -0400 Subject: tk: Reduce initialization boilerplate code --- (limited to 'src') diff --git a/src/tk/button.c b/src/tk/button.c index c7d0c5f..0db91a9 100644 --- a/src/tk/button.c +++ b/src/tk/button.c @@ -103,12 +103,7 @@ mftk_button_new(TTF_Font *font, const char *text, SDL_Color *text_color, struct mftk_widget *w; struct mftk_button *b; - if ((w = mftk_widget_new(sizeof(*b))) == NULL) return NULL; - b = (struct mftk_button *) w; - w->layout = &_mftk_button_layout; - w->event = &_mftk_button_event; - w->render = &_mftk_button_render; - w->destroy = &_mftk_button_destroy; + mftk_widget_init(w, b, button); b->label = mftk_label_new(font, text, text_color, renderer); if (b->label == NULL) { diff --git a/src/tk/grid.c b/src/tk/grid.c index 4f09928..5994929 100644 --- a/src/tk/grid.c +++ b/src/tk/grid.c @@ -142,12 +142,7 @@ mftk_grid_new(int rows, int cols, int row_spacing, int col_spacing, ...) int r; int c; - if ((w = mftk_widget_new(sizeof(*g))) == NULL) return NULL; - g = (struct mftk_grid *) w; - w->layout = &_mftk_grid_layout; - w->event = &_mftk_grid_event; - w->render = &_mftk_grid_render; - w->destroy = &_mftk_grid_destroy; + mftk_widget_init(w, g, grid); g->children = calloc(rows * cols, sizeof(*g->children)); if (g->children == NULL) { diff --git a/src/tk/label.c b/src/tk/label.c index e9ae38c..ec4400a 100644 --- a/src/tk/label.c +++ b/src/tk/label.c @@ -85,12 +85,7 @@ mftk_label_new(TTF_Font *font, const char *text, SDL_Color *color, const char *c; int glyph_max_y; - if ((w = mftk_widget_new(sizeof(*l))) == NULL) return NULL; - l = (struct mftk_label *) w; - w->layout = &_mftk_label_layout; - w->event = &_mftk_label_event; - w->render = &_mftk_label_render; - w->destroy = &_mftk_label_destroy; + mftk_widget_init(w, l, label); surface = TTF_RenderUTF8_Blended(font, text, *color); if (surface == NULL) { diff --git a/src/tk/widget.h b/src/tk/widget.h index 2336388..ae81553 100644 --- a/src/tk/widget.h +++ b/src/tk/widget.h @@ -36,4 +36,17 @@ struct mftk_widget { struct mftk_widget * mftk_widget_new(size_t size); +#define mftk_widget_init(w, t_w, name) \ + do { \ + w = mftk_widget_new(sizeof(struct mftk_##name)); \ + if (w == NULL) { \ + return NULL; \ + }; \ + w->layout = &_mftk_##name##_layout; \ + w->event = &_mftk_##name##_event; \ + w->render = &_mftk_##name##_render; \ + w->destroy = &_mftk_##name##_destroy; \ + t_w = (struct mftk_##name *) w; \ + } while (0) + #endif /* MFTK_WIDGET_H_ */ -- cgit v0.9.1