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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
|
#!/usr/bin/env python
#
# Urwid graphics example program
# Copyright (C) 2004-2011 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example demonstrating use of the BarGraph widget and creating a
floating-window appearance. Also shows use of alarms to create timed
animation.
"""
from __future__ import annotations
import math
import time
import typing
import urwid
UPDATE_INTERVAL = 0.2
def sin100(x):
"""
A sin function that returns values between 0 and 100 and repeats
after x == 100.
"""
return 50 + 50 * math.sin(x * math.pi / 50)
class GraphModel:
"""
A class responsible for storing the data that will be displayed
on the graph, and keeping track of which mode is enabled.
"""
data_max_value = 100
def __init__(self):
data = [
("Saw", list(range(0, 100, 2)) * 2),
("Square", [0] * 30 + [100] * 30),
("Sine 1", [sin100(x) for x in range(100)]),
("Sine 2", [(sin100(x) + sin100(x * 2)) / 2 for x in range(100)]),
("Sine 3", [(sin100(x) + sin100(x * 3)) / 2 for x in range(100)]),
]
self.modes = []
self.data = {}
for m, d in data:
self.modes.append(m)
self.data[m] = d
def get_modes(self):
return self.modes
def set_mode(self, m) -> None:
self.current_mode = m
def get_data(self, offset, r):
"""
Return the data in [offset:offset+r], the maximum value
for items returned, and the offset at which the data
repeats.
"""
lines = []
d = self.data[self.current_mode]
while r:
offset %= len(d)
segment = d[offset : offset + r]
r -= len(segment)
offset += len(segment)
lines += segment
return lines, self.data_max_value, len(d)
class GraphView(urwid.WidgetWrap):
"""
A class responsible for providing the application's interface and
graph display.
"""
palette: typing.ClassVar[tuple[str, str, str, ...]] = [
("body", "black", "light gray", "standout"),
("header", "white", "dark red", "bold"),
("screen edge", "light blue", "dark cyan"),
("main shadow", "dark gray", "black"),
("line", "black", "light gray", "standout"),
("bg background", "light gray", "black"),
("bg 1", "black", "dark blue", "standout"),
("bg 1 smooth", "dark blue", "black"),
("bg 2", "black", "dark cyan", "standout"),
("bg 2 smooth", "dark cyan", "black"),
("button normal", "light gray", "dark blue", "standout"),
("button select", "white", "dark green"),
("line", "black", "light gray", "standout"),
("pg normal", "white", "black", "standout"),
("pg complete", "white", "dark magenta"),
("pg smooth", "dark magenta", "black"),
]
graph_samples_per_bar = 10
graph_num_bars = 5
graph_offset_per_second = 5
def __init__(self, controller):
self.controller = controller
self.started = True
self.start_time = None
self.offset = 0
self.last_offset = None
super().__init__(self.main_window())
def get_offset_now(self):
if self.start_time is None:
return 0
if not self.started:
return self.offset
tdelta = time.time() - self.start_time
return int(self.offset + (tdelta * self.graph_offset_per_second))
def update_graph(self, force_update=False):
o = self.get_offset_now()
if o == self.last_offset and not force_update:
return False
self.last_offset = o
gspb = self.graph_samples_per_bar
r = gspb * self.graph_num_bars
d, max_value, repeat = self.controller.get_data(o, r)
lines = []
for n in range(self.graph_num_bars):
value = sum(d[n * gspb : (n + 1) * gspb]) / gspb
# toggle between two bar types
if n & 1:
lines.append([0, value])
else:
lines.append([value, 0])
self.graph.set_data(lines, max_value)
# also update progress
if (o // repeat) & 1:
# show 100% for first half, 0 for second half
if o % repeat > repeat // 2:
prog = 0
else:
prog = 1
else:
prog = float(o % repeat) / repeat
self.animate_progress.current = prog
return True
def on_animate_button(self, button):
"""Toggle started state and button text."""
if self.started: # stop animation
button.base_widget.set_label("Start")
self.offset = self.get_offset_now()
self.started = False
self.controller.stop_animation()
else:
button.base_widget.set_label("Stop")
self.started = True
self.start_time = time.time()
self.controller.animate_graph()
def on_reset_button(self, w):
self.offset = 0
self.start_time = time.time()
self.update_graph(True)
def on_mode_button(self, button, state):
"""Notify the controller of a new mode setting."""
if state:
# The new mode is the label of the button
self.controller.set_mode(button.get_label())
self.last_offset = None
def on_mode_change(self, m):
"""Handle external mode change by updating radio buttons."""
for rb in self.mode_buttons:
if rb.base_widget.label == m:
rb.base_widget.set_state(True, do_callback=False)
break
self.last_offset = None
def on_unicode_checkbox(self, w, state):
self.graph = self.bar_graph(state)
self.graph_wrap._w = self.graph
self.animate_progress = self.progress_bar(state)
self.animate_progress_wrap._w = self.animate_progress
self.update_graph(True)
def main_shadow(self, w):
"""Wrap a shadow and background around widget w."""
bg = urwid.AttrMap(urwid.SolidFill("▒"), "screen edge")
shadow = urwid.AttrMap(urwid.SolidFill(" "), "main shadow")
bg = urwid.Overlay(
shadow,
bg,
align=urwid.LEFT,
width=urwid.RELATIVE_100,
valign=urwid.TOP,
height=urwid.RELATIVE_100,
left=3,
right=1,
top=2,
bottom=1,
)
w = urwid.Overlay(
w,
bg,
align=urwid.LEFT,
width=urwid.RELATIVE_100,
valign=urwid.TOP,
height=urwid.RELATIVE_100,
left=2,
right=3,
top=1,
bottom=2,
)
return w
def bar_graph(self, smooth=False):
satt = None
if smooth:
satt = {(1, 0): "bg 1 smooth", (2, 0): "bg 2 smooth"}
w = urwid.BarGraph(["bg background", "bg 1", "bg 2"], satt=satt)
return w
def button(self, t, fn):
w = urwid.Button(t, fn)
w = urwid.AttrMap(w, "button normal", "button select")
return w
def radio_button(self, g, label, fn):
w = urwid.RadioButton(g, label, False, on_state_change=fn)
w = urwid.AttrMap(w, "button normal", "button select")
return w
def progress_bar(self, smooth=False):
if smooth:
return urwid.ProgressBar("pg normal", "pg complete", 0, 1, "pg smooth")
return urwid.ProgressBar("pg normal", "pg complete", 0, 1)
def exit_program(self, w):
raise urwid.ExitMainLoop()
def graph_controls(self):
modes = self.controller.get_modes()
# setup mode radio buttons
self.mode_buttons = []
group = []
for m in modes:
rb = self.radio_button(group, m, self.on_mode_button)
self.mode_buttons.append(rb)
# setup animate button
self.animate_button = self.button("", self.on_animate_button)
self.on_animate_button(self.animate_button)
self.offset = 0
self.animate_progress = self.progress_bar()
animate_controls = urwid.GridFlow(
[
self.animate_button,
self.button("Reset", self.on_reset_button),
],
9,
2,
0,
urwid.CENTER,
)
if urwid.get_encoding_mode() == "utf8":
unicode_checkbox = urwid.CheckBox("Enable Unicode Graphics", on_state_change=self.on_unicode_checkbox)
else:
unicode_checkbox = urwid.Text("UTF-8 encoding not detected")
self.animate_progress_wrap = urwid.WidgetWrap(self.animate_progress)
lines = [
urwid.Text("Mode", align=urwid.CENTER),
*self.mode_buttons,
urwid.Divider(),
urwid.Text("Animation", align=urwid.CENTER),
animate_controls,
self.animate_progress_wrap,
urwid.Divider(),
urwid.LineBox(unicode_checkbox),
urwid.Divider(),
self.button("Quit", self.exit_program),
]
w = urwid.ListBox(urwid.SimpleListWalker(lines))
return w
def main_window(self):
self.graph = self.bar_graph()
self.graph_wrap = urwid.WidgetWrap(self.graph)
vline = urwid.AttrMap(urwid.SolidFill("│"), "line")
c = self.graph_controls()
w = urwid.Columns([(urwid.WEIGHT, 2, self.graph_wrap), (1, vline), c], dividechars=1, focus_column=2)
w = urwid.Padding(w, urwid.LEFT, left=1)
w = urwid.AttrMap(w, "body")
w = urwid.LineBox(w)
w = urwid.AttrMap(w, "line")
w = self.main_shadow(w)
return w
class GraphController:
"""
A class responsible for setting up the model and view and running
the application.
"""
def __init__(self):
self.animate_alarm = None
self.model = GraphModel()
self.view = GraphView(self)
# use the first mode as the default
mode = self.get_modes()[0]
self.model.set_mode(mode)
# update the view
self.view.on_mode_change(mode)
self.view.update_graph(True)
def get_modes(self):
"""Allow our view access to the list of modes."""
return self.model.get_modes()
def set_mode(self, m) -> None:
"""Allow our view to set the mode."""
self.model.set_mode(m)
self.view.update_graph(True)
def get_data(self, offset, data_range):
"""Provide data to our view for the graph."""
return self.model.get_data(offset, data_range)
def main(self):
self.loop = urwid.MainLoop(self.view, self.view.palette)
self.loop.run()
def animate_graph(self, loop=None, user_data=None):
"""update the graph and schedule the next update"""
self.view.update_graph()
self.animate_alarm = self.loop.set_alarm_in(UPDATE_INTERVAL, self.animate_graph)
def stop_animation(self):
"""stop animating the graph"""
if self.animate_alarm:
self.loop.remove_alarm(self.animate_alarm)
self.animate_alarm = None
def main():
GraphController().main()
if __name__ == "__main__":
main()
|