]> git.ipfire.org Git - thirdparty/newt.git/blame - scale.c
0.52.24
[thirdparty/newt.git] / scale.c
CommitLineData
139f06bc 1#include <slang.h>
eaf8dbd3 2#include <stdlib.h>
3#include <string.h>
4
5#include "newt.h"
6#include "newt_pr.h"
7
8struct scale {
9 long long fullValue;
10 int charsSet;
5505c898 11 unsigned int percentage;
099b22e5
ML
12 int csEmpty;
13 int csFull;
eaf8dbd3 14};
15
16static void scaleDraw(newtComponent co);
17
18static struct componentOps scaleOps = {
19 scaleDraw,
20 newtDefaultEventHandler,
21 NULL,
8f52cd47 22 newtDefaultPlaceHandler,
23 newtDefaultMappedHandler,
eaf8dbd3 24} ;
25
26newtComponent 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;
c101e99e 33 co->destroyCallback = NULL;
eaf8dbd3 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;
8fab9b13 42 co->isMapped = 0;
eaf8dbd3 43
44 sc->fullValue = fullValue;
45 sc->charsSet = 0;
5505c898 46 sc->percentage = 0;
099b22e5
ML
47 sc->csEmpty = NEWT_COLORSET_EMPTYSCALE;
48 sc->csFull = NEWT_COLORSET_FULLSCALE;
eaf8dbd3 49
50 return co;
51}
52
649a0152 53void newtScaleSet(newtComponent co, unsigned long long amount) {
eaf8dbd3 54 struct scale * sc = co->data;
5505c898 55 int newPercentage;
53179ae3 56
c3db22aa 57 if (amount >= sc->fullValue) {
6f481af2 58 newPercentage = 100;
c3db22aa 59 sc->charsSet = co->width;
60 } else if (sc->fullValue >= -1ULL / (100 > co->width ? 100 : co->width)) {
61 /* avoid overflow on large numbers */
62 sc->charsSet = amount / (sc->fullValue / co->width);
63 newPercentage = amount / (sc->fullValue / 100);
64 } else {
65 sc->charsSet = (amount * co->width) / sc->fullValue;
66 newPercentage = (amount * 100) / sc->fullValue;
67 }
53179ae3 68
5505c898 69 if (newPercentage != sc->percentage) {
6f481af2 70 sc->percentage = newPercentage;
71 scaleDraw(co);
53179ae3 72 }
eaf8dbd3 73}
74
099b22e5
ML
75void newtScaleSetColors(newtComponent co, int empty, int full) {
76 struct scale * sc = co->data;
77
78 sc->csEmpty = empty;
79 sc->csFull = full;
80 scaleDraw(co);
81}
82
eaf8dbd3 83static void scaleDraw(newtComponent co) {
84 struct scale * sc = co->data;
85 int i;
5505c898 86 int xlabel = (co->width-4) /2;
87 char percent[10];
88
8fab9b13 89 if (!co->isMapped) return;
eaf8dbd3 90
91 newtGotorc(co->top, co->left);
92
5505c898 93 sprintf(percent, "%3d%%", sc->percentage);
eaf8dbd3 94
099b22e5 95 SLsmg_set_color(sc->csFull);
5505c898 96
97 for (i = 0; i < co->width; i++) {
98 if (i == sc->charsSet)
099b22e5 99 SLsmg_set_color(sc->csEmpty);
5505c898 100 if (i >= xlabel && i < xlabel+4)
101 SLsmg_write_char(percent[i-xlabel]);
102 else
103 SLsmg_write_char(' ');
104 }
4e667865 105 /* put cursor at beginning of text for better accessibility */
106 newtGotorc(co->top, co->left + xlabel);
eaf8dbd3 107}