gui: Make $first a local variable of _get_subtree().
[gsu.git] / gui
1 #!/bin/bash
2
3 if [[ "$(type -t _gsu_setup)" != "function" ]]; then
4 gsu_dir=${gsu_dir:-${BASH_SOURCE[0]%/*}}
5 . $gsu_dir/common || exit 1
6 _gsu_setup
7 fi
8
9 _gsu_node_name_pattern='[a-zA-Z_]'
10
11 _get_geometry()
12 {
13 local x y
14 result="$(stty size)"
15 if (($? != 0)); then
16 gsu_msg "fatal: could not get terminal geometry"
17 exit 1
18 fi
19 x="${result#* }"
20 y="${result%% *}"
21 (($x > 190)) && x=190
22 result="$y $x"
23 }
24
25 gsu_inputbox()
26 {
27 local g text="$1" init="$2"
28
29 _get_geometry
30 g="$result"
31 result="$(dialog --inputbox "$text" $g "$init" 3>&1 1>&2 2>&3 3>&-)"
32 ret="$?"
33 }
34
35 gsu_textbox()
36 {
37 local file="$1"
38
39 _get_geometry
40 dialog --textbox "$file" $result
41 }
42
43 # dialog segfaults if message is too long. Hence we always use a temporary file
44 gsu_msgbox()
45 {
46 local tmp="$(mktemp gsu_msgbox.XXXXXXXXXX)"
47
48 if (($? != 0)); then
49 dialog --msgbox "mktemp error" 0 0
50 return
51 fi
52 echo "$1" > "$tmp"
53 gsu_textbox "$tmp"
54 rm -f "$tmp"
55 }
56
57 _gsu_menu()
58 {
59 local header="${1:-root}"
60 local items="$2"
61 local i state opts num=0
62
63 _get_geometry
64 opts="$result 16"
65 for i in $items; do
66 let num++
67 opts+=" $i $num"
68 done
69 result="$(dialog --menu "$gsu_banner_txt ($header)" $opts 3>&1 1>&2 2>&3 3>&-)"
70 ret="$?"
71 }
72
73 _get_level()
74 {
75 local tmp="${1%%$_gsu_node_name_pattern*}"
76 result="${#tmp}"
77 }
78
79 _get_subtree()
80 {
81 local tree="$1" root="${2%/}"
82 local first TAB=' '
83
84 first="$(grep -n "$TAB\{1,\}$root/" <<< "$tree")"
85 [[ -z "$first" ]] && return
86
87 line_num="${first%%:*}"
88 _get_level "${first#*:}"
89 level="$result"
90
91 #echo "line: $line_num, root: $root, indent level: $level"
92 result="$(sed -e "1,${line_num}d;" <<< "$tree" \
93 | sed -e "/^$TAB\{1,$level\}$_gsu_node_name_pattern/,\$d" \
94 | sed -e "/^$TAB\{$(($level + 2))\}/d")"
95 ret="$level"
96 }
97
98 _get_root_nodes()
99 {
100 local tree="$1" TAB=' '
101
102 result="$(grep "^${TAB}${_gsu_node_name_pattern}" <<< "$tree")"
103 }
104
105 _browse()
106 {
107 local header="$1" old_header
108 local tree="$2" subtree="$3"
109
110 while :; do
111 _gsu_menu "$header" "$subtree"
112 (($ret != 0)) && return
113 [[ -z "$result" ]] && return
114 if [[ "${result%/}" != "$result" ]]; then
115 old_header="$header"
116 header="$result"
117 _get_subtree "$tree" "$header"
118 _browse "$header" "$tree" "$result"
119 header="$old_header"
120 continue
121 fi
122 eval ${gsu_name}_$result
123 done
124 }
125
126 gsu_gui()
127 {
128 local tree="$1" subtree
129
130 type -t dialog &> /dev/null
131 if (($? != 0)); then
132 gsu_msg "dialog executable not found"
133 exit 1
134 fi
135 _get_root_nodes "$tree"
136 subtree="$result"
137 _browse "main menu" "$tree" "$subtree"
138 }