Debian Codegraph @

DisplayCAL/lib/agw/pygauge.py

raw
1 # ---------------------------------------------------------------------------- #
2 # PYGAUGE wxPython IMPLEMENTATION
3 #
4 # Mark Reed, @ 28 Jul 2010
5 # Latest Revision: 27 Dec 2012, 21.00 GMT
6 #
7 # TODO List
8 #
9 # 1. Indeterminate mode (see wx.Gauge)
10 # 2. Vertical bar
11 # 3. Bitmap support (bar, background)
12 # 4. UpdateFunction - Pass a function to PyGauge which will be called every X
13 # milliseconds and the value will be updated to the returned value.
14 # 5. Currently the full gradient is drawn from 0 to value.
15 # Perhaps the gradient should be drawn from 0 to range and clipped at 0 to value.
16 # 6. Add a label?
17 #
18 # For All Kind Of Problems, Requests Of Enhancements And Bug Reports,
19 # Please Write To The:
20 #
21 # wxPython Mailing List!!!
22 #
23 # Tags: phoenix-port, unittest, documented, py3-port
24 #
25 # End Of Comments
26 # ---------------------------------------------------------------------------- #
27
28 """:class:`~wx.lib.agw.pygauge.PyGauge` is a generic :class:`Gauge` implementation.
29
30 Description
31 ===========
32
33 :class:`PyGauge` supports the determinate mode functions as :class:`Gauge` and
34 adds an :meth:`~PyGauge.Update` function which takes a value and a time parameter.
35 The `value` is added to the current value over a period of `time` milliseconds.
36
37
38 Usage
39 =====
40
41 Usage example::
42
43 import wx
44 import wx.lib.agw.pygauge as PG
45
46 class MyFrame(wx.Frame):
47
48 def __init__(self, parent):
49
50 wx.Frame.__init__(self, parent, -1, "PyGauge Demo")
51
52 panel = wx.Panel(self)
53
54 gauge1 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
55 gauge1.SetValue(80)
56 gauge1.SetBackgroundColour(wx.WHITE)
57 gauge1.SetBorderColor(wx.BLACK)
58
59 gauge2 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
60 gauge2.SetValue([20, 80])
61 gauge2.SetBarColor([wx.Colour(162, 255, 178), wx.Colour(159, 176, 255)])
62 gauge2.SetBackgroundColour(wx.WHITE)
63 gauge2.SetBorderColor(wx.BLACK)
64 gauge2.SetBorderPadding(2)
65 gauge2.Update([30, 0], 2000)
66
67 gauge3 = PG.PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
68 gauge3.SetValue(50)
69 gauge3.SetBarColor(wx.GREEN)
70 gauge3.SetBackgroundColour(wx.WHITE)
71 gauge3.SetBorderColor(wx.BLACK)
72
73 sizer = wx.BoxSizer(wx.VERTICAL)
74 sizer.Add(gauge1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 20)
75 sizer.Add(gauge2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 20)
76 sizer.Add(gauge3, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 20)
77
78 panel.SetSizer(sizer)
79 sizer.Layout()
80
81
82 # our normal wxApp-derived class, as usual
83
84 app = wx.App(0)
85
86 frame = MyFrame(None)
87 app.SetTopWindow(frame)
88 frame.Show()
89
90 app.MainLoop()
91
92
93 Supported Platforms
94 ===================
95
96 :class:`PyGauge` has been tested on the following platforms:
97 * Windows (Windows XP, Windows 7).
98
99
100 License And Version
101 ===================
102
103 :class:`PyGauge` is distributed under the wxPython license.
104
105 :class:`PyGauge` has been kindly contributed to the AGW library by Mark Reed.
106
107 Latest Revision: Andrea Gavana @ 27 Dec 2012, 21.00 GMT
108
109 Version 0.1
110
111 """
112
113 from __future__ import annotations
114
115 import copy
116
117 import wx
118
119
120 class PyGauge(wx.Window):
121 """This class provides a visual alternative for :class:`Gauge`.
122
123 It currently only support determinate mode (see :meth:`PyGauge.SetValue()
124 <PyGauge.SetValue>` and :meth:`PyGauge.SetRange() <PyGauge.SetRange>`).
125
126 Args:
127 parent (wx.Window): The parent window. Must not be ``None``.
128 id (int): window identifier. A value of -1 indicates a default value.
129 range_ (int): The maximum value of the gauge. Must be greater than 0.
130 If set to 0, an exception will be raised.
131 pos (wx.Point): The control position. A value of (-1, -1) indicates a
132 default position, chosen by either the windowing system or
133 wxPython, depending on platform.
134 size (tuple[int, int]): The control size. A value of (-1, -1) indicates
135 a default size, chosen by either the windowing system or wxPython,
136 depending on platform.
137 style (int): The underlying :class:`wx.Window` window style.
138 """
139
140 def __init__(
141 self,
142 parent: wx.Window,
143 id: int = wx.ID_ANY, # noqa: A002
144 range_: int = 100,
145 pos: wx.Point = wx.DefaultPosition,
146 size: tuple[int, int] = (-1, 30),
147 style: int = 0,
148 ) -> None:
149 wx.Window.__init__(self, parent, id, pos, size, style)
150
151 self._size = size
152
153 self._border_colour = None
154 self._barColour = self._barColourSorted = [wx.Colour(212, 228, 255)]
155 self._barGradient = self._barGradientSorted = None
156
157 self._border_padding = 0
158 self._range = range_
159 self._value = [0]
160 self._valueSorted = [0]
161
162 self._timerId = wx.NewIdRef()
163 self._timer = None
164
165 self._drawIndicatorText = False
166
167 self.Bind(wx.EVT_PAINT, self.OnPaint)
168 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
169 self.Bind(wx.EVT_TIMER, self.OnTimer)
170
171 def DoGetBestSize(self) -> wx.Size: # noqa: N802
172 """Get the size which best suits :class:`PyGauge`.
173
174 For a control, it would be the minimal size which doesn't truncate the control,
175 for a panel - the same size as it would have after a call to `Fit()`.
176
177 Note:
178 Overridden from :class:`wx.Window`.
179 """
180 return wx.Size(self._size[0], self._size[1])
181
182 def GetBorderColour(self) -> None | wx.Colour: # noqa: N802
183 """Return the :class:`PyGauge` border colour."""
184 return self._border_colour
185
186 def SetBorderColour(self, colour: wx.Colour) -> None: # noqa: N802
187 """Set the :class:`PyGauge` border colour.
188
189 Args:
190 colour (wx.Colour): an instance of :class:`wx.Colour`.
191 """
192 self._border_colour = colour
193
194 SetBorderColor = SetBorderColour
195 GetBorderColor = GetBorderColour
196
197 def GetBarColour(self) -> wx.Colour: # noqa: N802
198 """Return the :class:`PyGauge` main bar colour."""
199 return self._barColour[0]
200
201 def SetBarColour(self, colour: wx.Colour) -> None: # noqa: N802
202 """Set the :class:`PyGauge` main bar colour.
203
204 Args:
205 colour (wx.Colour): A :class:`wx.Colour` instance.
206 """
207 if not isinstance(colour, list):
208 self._barColour = [colour]
209 else:
210 self._barColour = list(colour)
211
212 self.SortForDisplay()
213
214 SetBarColor = SetBarColour
215 GetBarColor = GetBarColour
216
217 def GetBarGradient(self) -> None | tuple: # noqa: N802
218 """Return a tuple containing the gradient start and end colours."""
219 if self._barGradient is None:
220 return None
221
222 return self._barGradient[0]
223
224 def SetBarGradient(self, gradient: tuple[wx.Colour, wx.Colour]) -> None: # noqa: N802
225 """Set the bar gradient.
226
227 Args:
228 gradient (tuple[wx.Colour, wx.Colour]): A tuple containing the
229 gradient start and end colours.
230
231 Note:
232 This overrides the bar colour previously set with
233 :meth:`PyGauge.SetBarColour`.
234 """
235 if not isinstance(gradient, list):
236 self._barGradient = [gradient]
237 else:
238 self._barGradient = list(gradient)
239
240 self.SortForDisplay()
241
242 def GetBorderPadding(self) -> int: # noqa: N802
243 """Get the border padding.
244
245 Returns:
246 int: Pixels between the border and the progress bar.
247 """
248 return self._border_padding
249
250 def SetBorderPadding(self, padding: int) -> None: # noqa: N802
251 """Set the border padding.
252
253 Args:
254 padding (int): pixels between the border and the progress bar.
255 """
256 self._border_padding = padding
257
258 def GetRange(self) -> int: # noqa: N802
259 """Return the maximum value of the gauge.
260
261 Returns:
262 int: The maximum value of the gauge.
263 """
264 return self._range
265
266 def SetRange(self, range: int) -> None: # noqa: A002, N802
267 """Set the range of the gauge.
268
269 The gauge length is its value as a proportion of the range.
270
271 Args:
272 range (int): The maximum value of the gauge.
273 """
274 if range <= 0:
275 raise Exception("ERROR:\n Gauge range must be greater than 0.")
276
277 self._range = range
278
279 def GetValue(self) -> int: # noqa: N802
280 """Return the current position of the gauge."""
281 return self._value[0]
282
283 def SetValue(self, value: float | list[float]) -> None: # noqa: N802
284 """Set the current position of the gauge.
285
286 Args:
287 value: an integer specifying the current position of the gauge.
288 """
289 if not isinstance(value, list):
290 self._value = [value]
291 else:
292 self._value = list(value)
293
294 self.SortForDisplay()
295
296 for v in self._value:
297 if v < 0 or v > self._range:
298 raise Exception("ERROR:\n Gauge value must be between 0 and its range.")
299
300 def OnEraseBackground(self, event: wx.EraseEvent) -> None: # noqa: N802
301 """Handle the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`PyGauge`.
302
303 Args:
304 event (wx.EraseEvent): An :class:`EraseEvent` event to be processed.
305
306 Note:
307 This method is intentionally empty to reduce flicker.
308 """
309
310 def OnPaint(self, event: wx.PaintEvent) -> None: # noqa: N802
311 """Handle the ``wx.EVT_PAINT`` event for :class:`PyGauge`.
312
313 Args:
314 event (wx.PaintEvent): a :class:`PaintEvent` event to be processed.
315 """
316 dc = wx.BufferedPaintDC(self)
317 rect = self.GetClientRect()
318
319 dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
320 dc.Clear()
321 colour = self.GetBackgroundColour()
322 dc.SetBrush(wx.Brush(colour))
323 dc.SetPen(wx.Pen(colour))
324 dc.DrawRectangle(rect)
325
326 if self._border_colour:
327 dc.SetPen(wx.Pen(self.GetBorderColour()))
328 dc.DrawRectangle(rect)
329 pad = 1 + self.GetBorderPadding()
330 rect.Deflate(pad, pad)
331
332 if self.GetBarGradient():
333 for i, gradient in enumerate(self._barGradientSorted):
334 c1, c2 = gradient
335 w = rect.width * (float(self._valueSorted[i]) / self._range)
336 r = copy.copy(rect)
337 r.width = int(w)
338 dc.GradientFillLinear(r, c1, c2, wx.EAST)
339 else:
340 for i, colour in enumerate(self._barColourSorted):
341 dc.SetBrush(wx.Brush(colour))
342 dc.SetPen(wx.Pen(colour))
343 w = rect.width * (float(self._valueSorted[i]) / self._range)
344 r = copy.copy(rect)
345 r.width = int(w)
346 dc.DrawRectangle(r)
347
348 if not self._drawIndicatorText:
349 return
350
351 dc.SetFont(self._drawIndicatorText_font)
352 dc.SetTextForeground(self._drawIndicatorText_colour)
353 draw_value = self._valueSorted[i]
354
355 if self._drawIndicatorText_drawPercent:
356 draw_value = (float(self._valueSorted[i]) * 100) / self._range
357
358 draw_string = self._drawIndicatorText_formatString.format(draw_value)
359 rect = self.GetClientRect()
360 (text_width, text_height, descent, extra_leading) = dc.GetFullTextExtent(
361 draw_string
362 )
363 text_y_pos = (rect.height - text_height) // 2
364
365 if text_height > rect.height:
366 text_y_pos = 0 - descent + extra_leading
367
368 text_x_pos = (rect.width - text_width) // 2
369
370 if text_width > rect.width:
371 text_x_pos = 0
372
373 dc.DrawText(draw_string, text_x_pos, text_y_pos)
374
375 def SetDrawValue( # noqa: N802
376 self,
377 draw: bool = True,
378 draw_percent: bool = True,
379 font: None | wx.Font = None,
380 colour: wx.Colour = wx.BLACK,
381 format_string: None | str = None,
382 ) -> None:
383 """Enable or disable drawing of value/percentage on the gauge.
384
385 Args:
386 draw (bool): a boolean value, which if ``True`` tells to start
387 drawing value or percentage. If set to ``False`` nothing will
388 be drawn and other parameters will be ignored.
389 draw_percent (bool): a boolean value which indicates that a percent
390 should be drawn instead of value passed in :meth:`SetValue`.
391 font (wx.Font): a font with which indication should be drawn,
392 if ``None``, then ``wx.NORMAL_FONT`` will be used.
393 Usually text would be displayed centered in the control,
394 but if the text font is too large to be displayed
395 (either in width or height) the corresponding coordinate will
396 be set to zero.
397 colour (wx.Colour): the colour with which indication should be
398 drawn, if ``None`` then ``wx.BLACK`` will be used.
399 format_string (Nont | str): a string specifying format of the
400 indication (should have one and only one number placeholder).
401 If set to ``None``, will use ``{:.0f}`` format string for
402 values and ``{:.0f}%`` format string for percentages.
403
404 Note:
405 format_string will override addition of percent sign (after value)
406 even if `drawPercent` is ``True``.
407
408 .. versionadded:: 0.9.7
409 """
410 if not draw:
411 # Will not draw anything unless this is True
412 self._drawIndicatorText = False
413 return
414
415 self._drawIndicatorText = True
416 self._drawIndicatorText_drawPercent = draw_percent
417
418 if font is None or not isinstance(font, wx.Font):
419 self._drawIndicatorText_font = wx.NORMAL_FONT
420 else:
421 self._drawIndicatorText_font = font
422
423 if colour is None or not isinstance(colour, wx.Colour):
424 self._drawIndicatorText_colour = wx.BLACK
425 else:
426 self._drawIndicatorText_colour = colour
427
428 if format_string is not None:
429 error_occurred = True
430 try:
431 # This is to test if format string is valid.
432 # If not, it will be replaced with default one.
433 format_string.format(12.345)
434 error_occurred = False
435 except Exception as e:
436 print(f"We have exception: {e}")
437
438 if error_occurred:
439 format_string = None
440
441 # Here formatString is either valid formatting string,
442 # or None in case of error or None passed
443 if format_string is None:
444 if self._drawIndicatorText_drawPercent:
445 self._drawIndicatorText_formatString = "{:.0f}%"
446 else:
447 self._drawIndicatorText_formatString = "{:.0f}"
448 else:
449 self._drawIndicatorText_formatString = format_string
450
451 def OnTimer(self, event: wx.TimerEvent) -> None: # noqa: N802
452 """Handle the ``wx.EVT_TIMER`` event for :class:`PyGauge`.
453
454 Args:
455 event (wx.TimerEvent): a :class:`TimerEvent` event to be processed.
456 """
457 if self._timerId != event.GetId():
458 return
459
460 stop_timer = True
461 for i, _ in enumerate(self._value):
462 self._value[i] += self._update_step[i]
463
464 if self._update_step[i] > 0:
465 if self._value[i] > self._update_value[i]:
466 self._value[i] = self._update_value[i]
467 else:
468 stop_timer = False
469 elif self._value[i] < self._update_value[i]:
470 self._value[i] = self._update_value[i]
471 else:
472 stop_timer = False
473
474 if stop_timer:
475 self._timer.Stop()
476
477 self.SortForDisplay()
478
479 self.Refresh()
480
481 def Update(self, value: list[float], time: float = 0) -> None: # noqa: N802
482 """Update the gauge by adding `value` to it over `time` milliseconds.
483
484 The `time` parameter **must** be a multiple of 50 milliseconds.
485
486 Args:
487 value (list[float]): The value to be added to the gauge.
488 time (float): The length of time in milliseconds that it will take
489 to move the gauge.
490 """
491 if not isinstance(value, list):
492 value = [value]
493
494 if len(value) != len(self._value):
495 raise Exception("ERROR:\n len(value) != len(self.GetValue())")
496
497 self._update_value = []
498 self._update_step = []
499 for i, v in enumerate(self._value):
500 if value[i] + v <= 0 or value[i] + v > self._range:
501 raise Exception(
502 "ERROR:\n Gauge value must be between 0 and its range. "
503 )
504
505 self._update_value.append(value[i] + v)
506 self._update_step.append(float(value[i]) / (time / 50.0))
507
508 # print(self._update_)
509
510 if not self._timer:
511 self._timer = wx.Timer(self, self._timerId)
512
513 self._timer.Start(100)
514
515 def SortForDisplay(self) -> None: # noqa: N802
516 """Sort things so we draw the longest bar first."""
517 if self.GetBarGradient():
518 tmp = sorted(zip(self._value, self._barGradient), key=lambda x: x[0])
519 tmp.reverse()
520 a, b = list(zip(*tmp))
521 self._valueSorted = list(a)
522 self._barGradientSorted = list(b)
523 else:
524 tmp = sorted(zip(self._value, self._barColour), key=lambda x: x[0])
525 tmp.reverse()
526 a, b = list(zip(*tmp))
527 self._valueSorted = list(a)
528 self._barColourSorted = list(b)
529
530
531 if __name__ == "__main__":
532 import wx
533
534 class MyFrame(wx.Frame):
535 """A simple frame to test the :class:`PyGauge` class.
536
537 Args:
538 parent (wx.Window): The parent window for this frame.
539 """
540
541 def __init__(self, parent: wx.Window) -> None:
542 wx.Frame.__init__(self, parent, -1, "PyGauge Demo")
543
544 panel = wx.Panel(self)
545
546 gauge1 = PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
547 gauge1.SetValue(80)
548 gauge1.SetBackgroundColour(wx.WHITE)
549 gauge1.SetBorderColor(wx.BLACK)
550
551 gauge2 = PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
552 gauge2.SetValue([20, 80])
553 gauge2.SetBarColor([wx.Colour(162, 255, 178), wx.Colour(159, 176, 255)])
554 gauge2.SetBackgroundColour(wx.WHITE)
555 gauge2.SetBorderColor(wx.BLACK)
556 gauge2.SetBorderPadding(2)
557 gauge2.Update([30, 0], 2000)
558
559 gauge3 = PyGauge(panel, -1, size=(100, 25), style=wx.GA_HORIZONTAL)
560 gauge3.SetValue(50)
561 gauge3.SetBarColor(wx.GREEN)
562 gauge3.SetBackgroundColour(wx.WHITE)
563 gauge3.SetBorderColor(wx.BLACK)
564
565 sizer = wx.BoxSizer(wx.VERTICAL)
566 sizer.Add(gauge1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 20)
567 sizer.Add(gauge2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 20)
568 sizer.Add(gauge3, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 20)
569
570 panel.SetSizer(sizer)
571 sizer.Layout()
572
573 # our normal wxApp-derived class, as usual
574
575 app = wx.App(0)
576
577 frame = MyFrame(None)
578 app.SetTopWindow(frame)
579 frame.Show()
580
581 app.MainLoop()