-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtestcolors
executable file
·109 lines (98 loc) · 2.78 KB
/
testcolors
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
#!/usr/bin/env sh
# vim: ft=sh ts=4 sw=4 sts=4 et :
# This file echoes a bunch of 24-bit color codes
# to the terminal to demonstrate its functionality.
# The foreground escape sequence is ^[38;2;<r>;<g>;<b>m
# The background escape sequence is ^[48;2;<r>;<g>;<b>m
# <r> <g> <b> range from 0 to 255 inclusive.
# The escape sequence ^[0m returns output to default
set_bg() {
printf '\x1b[48;2;%s;%s;%sm' "$1" "$2" "$3"
}
reset_output() {
printf '\x1b[0m\n'
}
# Get terminal width, default to 80 if unable to determine
get_width() {
if command -v tput >/dev/null 2>&1; then
tput cols
elif command -v stty >/dev/null 2>&1; then
stty size | cut -d' ' -f2
else
echo 80
fi
}
# Calculate how many lines needed for the gradient
get_lines() {
width=$(get_width)
lines=$((256 / width + (256 % width > 0)))
[ "$lines" -lt 1 ] && lines=1
echo "$lines"
}
rainbow() {
h=$(($1 / 43))
f=$(($1 - 43 * h))
t=$((f * 255 / 43))
q=$((255 - t))
if [ "$h" -eq 0 ]; then
echo "255 $t 0"
elif [ "$h" -eq 1 ]; then
echo "$q 255 0"
elif [ "$h" -eq 2 ]; then
echo "0 255 $t"
elif [ "$h" -eq 3 ]; then
echo "0 $q 255"
elif [ "$h" -eq 4 ]; then
echo "$t 0 255"
elif [ "$h" -eq 5 ]; then
echo "255 0 $q"
else
# Execution should never reach here
echo "0 0 0"
fi
}
# Draw a gradient strip with given color components
# $1: r component (0 or 1)
# $2: g component (0 or 1)
# $3: b component (0 or 1)
# $4: use rainbow colors if 1
draw_gradient() {
width=$(get_width)
lines=$(get_lines)
colors_per_line=$((256 / lines))
chars_per_line=$((256 / lines + (256 % lines > 0)))
line=0
while [ $line -lt $lines ]; do
start=$((line * colors_per_line))
end=$((start + colors_per_line))
[ $line -eq $((lines - 1)) ] && end=256
i=$start
count=0
while [ $count -lt $chars_per_line ]; do
if [ $i -lt $end ] && [ $i -lt 256 ]; then
if [ "$4" = "1" ]; then
set_bg $(rainbow $i)
else
set_bg $(($1 * i)) $(($2 * i)) $(($3 * i))
fi
i=$((i + 1))
else
# Pad with last color if needed
if [ "$4" = "1" ]; then
set_bg $(rainbow $((end - 1)))
else
set_bg $(($1 * (end - 1))) $(($2 * (end - 1))) $(($3 * (end - 1)))
fi
fi
printf " "
count=$((count + 1))
done
reset_output
line=$((line + 1))
done
}
# Draw all gradients
draw_gradient 1 0 0 0 # red
draw_gradient 0 1 0 0 # green
draw_gradient 0 0 1 0 # blue
draw_gradient 0 0 0 1 # rainbow