Debian Codegraph @

s_tui/sturwid/complex_bar_graph.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 # Copyright (C) 2017-2025 Alex Manuskin, Gil Tsuker
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
18
19 """ScalableBarGraph Class extends urwid.BarGraph so that
20 the current size of the bar graph is also obtainable
21 get_size() - returns the tuple (row, col)
22 """
23
24 import urwid
25
26
27 class ScalableBarGraph(urwid.BarGraph):
28 """Scale the graph according to screen size"""
29
30 _size = (0, 0)
31
32 def render(self, size, focus=False):
33 canvas = super().render(size, focus)
34 new_size = (int(canvas.rows()), int(canvas.cols()))
35 old_size = self._size
36 # check if to raise *on_resize* event
37 if new_size != old_size:
38 self.on_resize(new_size)
39 self._size = new_size
40 return canvas
41
42 def calculate_bar_widths(self, size, bardata):
43 """
44 Return a list of bar widths, one for each bar in data.
45
46 If self.bar_width is None this implementation will stretch
47 the bars across the available space specified by maxcol.
48 """
49 maxcol, _ = size
50
51 if self.bar_width is not None:
52 return [self.bar_width] * min(len(bardata), int(maxcol / self.bar_width))
53
54 if len(bardata) >= maxcol:
55 return [1] * maxcol
56
57 widths = []
58 grow = maxcol
59 remain = len(bardata)
60 for _ in bardata:
61 w = int(float(grow) / remain + 0.5)
62 widths.append(w)
63 grow -= w
64 remain -= 1
65 return widths
66
67 def get_size(self):
68 return self._size
69
70 def on_resize(self, new_size):
71 pass # place folder for any future implantation
72
73 @staticmethod
74 def _create_na_placeholder():
75 """Create a placeholder widget showing 'N/A' for unavailable sensors"""
76 na_text = urwid.Text("N/A", align="center")
77 na_filler = urwid.Filler(na_text, valign="middle")
78 # Wrap in LineBox for visual frame (optional, can be removed if too busy)
79 na_placeholder = urwid.LineBox(na_filler)
80 return na_placeholder
81
82
83 class LabeledBarGraphVector(urwid.WidgetPlaceholder):
84 """Add option to add labels for X and Y axes"""
85
86 def __init__(
87 self, title, sub_title_list, y_label, bar_graph_vector, visible_graph_list
88 ):
89 for bar_graph in bar_graph_vector:
90 if not isinstance(bar_graph, ScalableBarGraph):
91 raise Exception("graph vector items must be ScalableBarGraph")
92 if not self.check_label(y_label):
93 raise Exception("Y label must be a valid label")
94
95 self.visible_graph_list = visible_graph_list
96 self.bar_graph_vector = []
97 self.set_graph(bar_graph_vector)
98
99 self.y_label_and_graphs = urwid.WidgetPlaceholder(urwid.Columns([])) # type: ignore[arg-type]
100 self.y_label = []
101 self.set_y_label(y_label)
102
103 list_w = urwid.ListBox(urwid.SimpleFocusListWalker([]))
104 self.title = urwid.WidgetPlaceholder(list_w) # type: ignore[arg-type]
105 self.sub_title_list = sub_title_list
106 self.set_title(title)
107
108 self.sensor_available = [True] * len(bar_graph_vector)
109
110 super().__init__(urwid.Pile([])) # type: ignore[arg-type]
111 self.set_visible_graphs(visible_graph_list)
112
113 def set_title(self, title):
114 if not title:
115 return
116 title_text_w = urwid.Text(title, align="center")
117 list_w = urwid.SimpleFocusListWalker([title_text_w])
118 self.title.original_widget = urwid.ListBox(list_w)
119
120 def set_y_label(self, y_label):
121 if not y_label:
122 text = urwid.Text("1")
123 pile = urwid.Pile([urwid.ListBox([text])])
124 self.y_label = ("fixed", 1, pile) # type: ignore[assignment]
125 return
126
127 str_y_label = [str(i) for i in y_label]
128 y_label_nums = str_y_label[1:]
129 y_list_walker = [(1, urwid.ListBox([urwid.Text(str_y_label[0])]))]
130
131 for num in y_label_nums:
132 y_list_walker = [urwid.ListBox([urwid.Text(num)]), *y_list_walker]
133
134 y_list_walker = urwid.Pile(y_list_walker, focus_item=0)
135 y_scale_len = len(max(str_y_label, key=len))
136
137 self.y_label = ("fixed", y_scale_len, y_list_walker) # type: ignore[assignment]
138
139 def set_visible_graphs(self, visible_graph_list=None):
140 """Show a column of the graph selected for display"""
141 if visible_graph_list is None:
142 visible_graph_list = self.visible_graph_list
143
144 vline = urwid.AttrMap(urwid.SolidFill("|"), "line")
145
146 graph_vector_column_list = []
147 for idx, (state, graph, sub_title) in enumerate(
148 zip(visible_graph_list, self.bar_graph_vector, self.sub_title_list)
149 ):
150 if state:
151 text_w = urwid.Text(sub_title, align="center")
152 sub_title_widget = urwid.ListBox([text_w])
153
154 # Use placeholder if sensor is unavailable
155 if idx < len(self.sensor_available) and not self.sensor_available[idx]:
156 display_widget = ScalableBarGraph._create_na_placeholder()
157 else:
158 display_widget = graph
159
160 graph_a = [
161 ("fixed", 1, sub_title_widget), # type: ignore[list-item]
162 ("weight", 1, display_widget), # type: ignore[list-item]
163 ]
164 graph_and_title = urwid.Pile(graph_a)
165 graph_vector_column_list.append(("weight", 1, graph_and_title)) # type: ignore[arg-type]
166 graph_vector_column_list.append(("fixed", 1, vline)) # type: ignore[arg-type]
167
168 # if all sub graph are disabled
169 if not graph_vector_column_list:
170 self.visible_graph_list = visible_graph_list
171 self.original_widget = urwid.Pile([]) # type: ignore[arg-type]
172 return
173
174 # remove the last vertical line separator
175 graph_vector_column_list.pop()
176
177 y_label_a = ("weight", 1, urwid.Columns(graph_vector_column_list)) # type: ignore[var-type]
178 y_label_and_graphs = [self.y_label, y_label_a]
179 column_w = urwid.Columns(y_label_and_graphs, dividechars=1) # type: ignore[arg-type]
180 y_label_and_graphs_widget = urwid.WidgetPlaceholder(column_w) # type: ignore[arg-type]
181
182 init_widget = urwid.Pile(
183 [("fixed", 1, self.title), ("weight", 1, y_label_and_graphs_widget)] # type: ignore[list-item]
184 )
185
186 self.visible_graph_list = visible_graph_list
187 self.original_widget = init_widget
188
189 def set_graph(self, graph_vector):
190 self.bar_graph_vector = graph_vector
191
192 @staticmethod
193 def check_label(label):
194 return (len(label) >= 2 and None not in label) or not label or label is None