4 # mirabilos <thorsten.glaser@teckids.org>
6 # Provided that these terms and disclaimer and all copyright notices
7 # are retained or reproduced in an accompanying document, permission
8 # is granted to deal in this work without restriction, including un‐
9 # limited rights to use, publicly perform, distribute, sell, modify,
10 # merge, give away, or sublicence.
12 # This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
13 # the utmost extent permitted by applicable law, neither express nor
14 # implied; without malicious intent or gross negligence. In no event
15 # may a licensor, author or contributor be held liable for indirect,
16 # direct, other damage, loss, or other issues arising in any way out
17 # of dealing in the work, even if advised of the possibility of such
18 # damage or existence of a defect, except proven that it results out
19 # of said person’s immediate fault when using the work as intended.
21 # Shell library for easy display of a progress bar
24 # – before: init_progress_bar $n
25 # – $n times: draw_progress_bar
26 # – after: done_progress_bar
28 # init_progress_bar trashes the EXIT and SIGWINCH traps, which later
29 # are cleared, again, by done_progress_bar.
31 # global variables used by this library
37 # args: $1 = number of draw_progress_bar calls to make up 100%
38 function init_progress_bar {
39 global -i _cnt_progress_bar=$1 _cur_progress_bar=0
40 global -i nlin_progress_bar=$LINES isin_progress_bar=1
42 trap 'done_progress_bar' EXIT
43 trap 'sigwinch_progress_bar' WINCH
44 # newline; up one line (to ensure we are not in the last line);
45 # save position; set scrolling region; restore position
46 print -n "\\n\\e[A\\e7\\e[1;$((# nlin_progress_bar - 1))r\\e8"
49 function sigwinch_progress_bar {
50 (( isin_progress_bar )) || return 0
52 # get new terminal size
53 nlin_progress_bar=$LINES
54 # newline; up one line (to ensure we are not in the last line);
55 # save position; set scrolling region; restore position
56 print -n "\\n\\e[A\\e7\\e[1;$((# nlin_progress_bar - 1))r\\e8"
59 function done_progress_bar {
60 (( isin_progress_bar )) || return 0
61 # save position; clear scrolling region;
62 # go to last line; delete line; restore position
63 print "\\e7\\e[0;0r\\e[$nlin_progress_bar;0H\\e[M\\e8"
69 function draw_progress_bar {
70 local bar num w=$COLUMNS
72 ((# num = (++_cur_progress_bar * w * 8) / _cnt_progress_bar ))
73 while ((# num >= 8 )); do
86 # fill complete line, right-align completion percentage display
87 local -R$w spc="$((# _cur_progress_bar * 100 / _cnt_progress_bar))%"
88 # elide percentage when it stops fitting
89 ((# (_cur_progress_bar * w / _cnt_progress_bar) > (w - 4) )) && spc=
90 # save position; go to last line; set colours;
91 # output a line full of spaces (and completion percentage);
92 # jump to first column; output bar (line præfix); restore position
93 print -n -- "\\e7\\e[$nlin_progress_bar;0H\\e[0;1;33;44m$spc\\r$bar\\e8"