summaryrefslogtreecommitdiff
path: root/textscreen/txt_label.c
blob: 32610f9eddbb5a88d11bdc454d936c7a93e37e3c (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <string.h>

#include "txt_label.h"
#include "txt_io.h"
#include "txt_main.h"
#include "txt_window.h"

static void TXT_LabelSizeCalc(TXT_UNCAST_ARG(label), int *w, int *h)
{
    TXT_CAST_ARG(txt_label_t, label);

    *w = label->w;
    *h = label->h;
}

static void TXT_LabelDrawer(TXT_UNCAST_ARG(label), int w, int selected)
{
    TXT_CAST_ARG(txt_label_t, label);
    int i;
    int origin_x, origin_y;

    TXT_BGColor(TXT_COLOR_BLUE, 0);
    TXT_FGColor(TXT_COLOR_BRIGHT_WHITE);

    TXT_GetXY(&origin_x, &origin_y);

    for (i=0; i<label->h; ++i)
    {
        TXT_GotoXY(origin_x, origin_y + i);
        TXT_DrawString(label->lines[i]);
    }
}

static void TXT_LabelDestructor(TXT_UNCAST_ARG(label))
{
    TXT_CAST_ARG(txt_label_t, label);

    free(label->label);
    free(label->lines);
}

txt_widget_class_t txt_label_class =
{
    TXT_LabelSizeCalc,
    TXT_LabelDrawer,
    NULL,
    TXT_LabelDestructor,
};

void TXT_SetLabel(txt_label_t *label, char *value)
{
    char *p;
    int y;

    // Free back the old label

    free(label->label);
    free(label->lines);

    // Set the new value 

    label->label = strdup(value);

    // Work out how many lines in this label

    label->h = 1;

    for (p = value; *p != '\0'; ++p)
    {
        if (*p == '\n')
        {
            ++label->h;
        }
    }

    // Split into lines

    label->lines = malloc(sizeof(char *) * label->h);
    label->lines[0] = label->label;
    y = 1;
    
    for (p = label->label; *p != '\0'; ++p)
    {
        if (*p == '\n')
        {
            label->lines[y] = p + 1;
            *p = '\0';
            ++y;
        }
    }

    label->w = 0;

    for (y=0; y<label->h; ++y)
    {
        if (strlen(label->lines[y]) > label->w)
            label->w = strlen(label->lines[y]);
    }
}

txt_label_t *TXT_NewLabel(char *text)
{
    txt_label_t *label;

    label = malloc(sizeof(txt_label_t));

    TXT_InitWidget(label, &txt_label_class);
    label->widget.selectable = 0;
    label->label = NULL;
    label->lines = NULL;

    TXT_SetLabel(label, text);

    return label;
}