]> git.ipfire.org Git - thirdparty/newt.git/blob - scale.c
allowing changing colors in individual labels, scrollbars, entries, scales
[thirdparty/newt.git] / scale.c
1 #include <slang.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 #include "newt.h"
6 #include "newt_pr.h"
7
8 struct scale {
9 long long fullValue;
10 int charsSet;
11 unsigned int percentage;
12 int csEmpty;
13 int csFull;
14 };
15
16 static void scaleDraw(newtComponent co);
17
18 static struct componentOps scaleOps = {
19 scaleDraw,
20 newtDefaultEventHandler,
21 NULL,
22 newtDefaultPlaceHandler,
23 newtDefaultMappedHandler,
24 } ;
25
26 newtComponent newtScale(int left, int top, int width, long long fullValue) {
27 newtComponent co;
28 struct scale * sc;
29
30 co = malloc(sizeof(*co));
31 sc = malloc(sizeof(struct scale));
32 co->data = sc;
33 co->destroyCallback = NULL;
34
35 co->ops = &scaleOps;
36
37 co->height = 1;
38 co->width = width;
39 co->top = top;
40 co->left = left;
41 co->takesFocus = 0;
42
43 sc->fullValue = fullValue;
44 sc->charsSet = 0;
45 sc->percentage = 0;
46 sc->csEmpty = NEWT_COLORSET_EMPTYSCALE;
47 sc->csFull = NEWT_COLORSET_FULLSCALE;
48
49 return co;
50 }
51
52 void newtScaleSet(newtComponent co, unsigned long long amount) {
53 struct scale * sc = co->data;
54 int newPercentage;
55
56 if (amount >= sc->fullValue) {
57 newPercentage = 100;
58 sc->charsSet = co->width;
59 } else if (sc->fullValue >= -1ULL / (100 > co->width ? 100 : co->width)) {
60 /* avoid overflow on large numbers */
61 sc->charsSet = amount / (sc->fullValue / co->width);
62 newPercentage = amount / (sc->fullValue / 100);
63 } else {
64 sc->charsSet = (amount * co->width) / sc->fullValue;
65 newPercentage = (amount * 100) / sc->fullValue;
66 }
67
68 if (newPercentage != sc->percentage) {
69 sc->percentage = newPercentage;
70 scaleDraw(co);
71 }
72 }
73
74 void newtScaleSetColors(newtComponent co, int empty, int full) {
75 struct scale * sc = co->data;
76
77 sc->csEmpty = empty;
78 sc->csFull = full;
79 scaleDraw(co);
80 }
81
82 static void scaleDraw(newtComponent co) {
83 struct scale * sc = co->data;
84 int i;
85 int xlabel = (co->width-4) /2;
86 char percent[10];
87
88 if (co->top == -1) return;
89
90 newtGotorc(co->top, co->left);
91
92 sprintf(percent, "%3d%%", sc->percentage);
93
94 SLsmg_set_color(sc->csFull);
95
96 for (i = 0; i < co->width; i++) {
97 if (i == sc->charsSet)
98 SLsmg_set_color(sc->csEmpty);
99 if (i >= xlabel && i < xlabel+4)
100 SLsmg_write_char(percent[i-xlabel]);
101 else
102 SLsmg_write_char(' ');
103 }
104 /* put cursor at beginning of text for better accessibility */
105 newtGotorc(co->top, co->left + xlabel);
106 }