| 1 |
# --------------------------------------------------------------------------- # |
| 2 |
# FLOATSPIN Control wxPython IMPLEMENTATION |
| 3 |
# Python Code By: |
| 4 |
# |
| 5 |
# Andrea Gavana, @ 16 Nov 2005 |
| 6 |
# Latest Revision: 03 Jan 2014, 23.00 GMT |
| 7 |
# |
| 8 |
# Modifications for DisplayCAL: |
| 9 |
# - Select text on focus |
| 10 |
# - Always accept "," (comma) as decimal point |
| 11 |
# - Only call SyncSpinToText if TextCtrl value has actually changed |
| 12 |
# - Set value to min/max if not in range |
| 13 |
# - Use a different method for tab traversal because the original code didn't |
| 14 |
# work under wxGTK |
| 15 |
# - If CMD or CTRL are held, don't block keycodes that are not allowed (fixes |
| 16 |
# copy/paste/select all keyboard shortcuts not working) |
| 17 |
# - Do default action if return key is pressed (currently only works if the |
| 18 |
# default item is a button) |
| 19 |
# - Fix children not reflecting enabled state under wxMac |
| 20 |
# |
| 21 |
# TODO List/Caveats |
| 22 |
# |
| 23 |
# 1. Ay Idea? |
| 24 |
# |
| 25 |
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please |
| 26 |
# Write To Me At: |
| 27 |
# |
| 28 |
# [email protected] |
| 29 |
# [email protected] |
| 30 |
# |
| 31 |
# Or, Obviously, To The wxPython Mailing List!!! |
| 32 |
# |
| 33 |
# |
| 34 |
# End Of Comments |
| 35 |
# --------------------------------------------------------------------------- # |
| 36 |
""":class:`FloatSpin` implements a floating point :class:`SpinCtrl`. |
| 37 |
|
| 38 |
Description |
| 39 |
=========== |
| 40 |
|
| 41 |
:class:`FloatSpin` implements a floating point :class:`SpinCtrl`. It is built using a |
| 42 |
custom :class:`PyControl`, composed by a :class:`TextCtrl` and a :class:`SpinButton`. In |
| 43 |
order to correctly handle floating points numbers without rounding errors or non-exact |
| 44 |
floating point representations, :class:`FloatSpin` uses the great :class:`FixedPoint` |
| 45 |
class from Tim Peters. |
| 46 |
|
| 47 |
What you can do: |
| 48 |
|
| 49 |
- Set the number of representative digits for your floating point numbers; |
| 50 |
- Set the floating point format (``%f``, ``%F``, ``%e``, ``%E``, ``%g``, ``%G``); |
| 51 |
- Set the increment of every ``EVT_FLOATSPIN`` event; |
| 52 |
- Set minimum, maximum values for :class:`FloatSpin` as well as its range; |
| 53 |
- Change font and colour for the underline :class:`TextCtrl`. |
| 54 |
|
| 55 |
|
| 56 |
Usage |
| 57 |
===== |
| 58 |
|
| 59 |
Usage example:: |
| 60 |
|
| 61 |
import wx |
| 62 |
import wx.lib.agw.floatspin as FS |
| 63 |
|
| 64 |
class MyFrame(wx.Frame): |
| 65 |
|
| 66 |
def __init__(self, parent): |
| 67 |
|
| 68 |
wx.Frame.__init__(self, parent, -1, "FloatSpin Demo") |
| 69 |
|
| 70 |
panel = wx.Panel(self) |
| 71 |
|
| 72 |
floatspin = FS.FloatSpin(panel, -1, pos=(50, 50), min_val=0, max_val=1, |
| 73 |
increment=0.01, value=0.1, agw_style=FS.FS_LEFT) |
| 74 |
floatspin.SetFormat("%f") |
| 75 |
floatspin.SetDigits(2) |
| 76 |
|
| 77 |
|
| 78 |
# our normal wxApp-derived class, as usual |
| 79 |
|
| 80 |
app = wx.App(0) |
| 81 |
|
| 82 |
frame = MyFrame(None) |
| 83 |
app.SetTopWindow(frame) |
| 84 |
frame.Show() |
| 85 |
|
| 86 |
app.MainLoop() |
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
Events |
| 91 |
====== |
| 92 |
|
| 93 |
:class:`FloatSpin` catches 3 different types of events: |
| 94 |
|
| 95 |
1) Spin events: events generated by spinning up/down the spinbutton; |
| 96 |
2) Char events: playing with up/down arrows of the keyboard increase/decrease |
| 97 |
the value of :class:`FloatSpin`; |
| 98 |
3) Mouse wheel event: using the wheel will change the value of :class:`FloatSpin`. |
| 99 |
|
| 100 |
In addition, there are some other functionalities: |
| 101 |
|
| 102 |
- It remembers the initial value as a default value, call meth:~FloatSpin.SetToDefaultValue`, or |
| 103 |
press ``Esc`` to return to it; |
| 104 |
- ``Shift`` + arrow = 2 * increment (or ``Shift`` + mouse wheel); |
| 105 |
- ``Ctrl`` + arrow = 10 * increment (or ``Ctrl`` + mouse wheel); |
| 106 |
- ``Alt`` + arrow = 100 * increment (or ``Alt`` + mouse wheel); |
| 107 |
- Combinations of ``Shift``, ``Ctrl``, ``Alt`` increment the :class:`FloatSpin` value by the |
| 108 |
product of the factors; |
| 109 |
- ``PgUp`` & ``PgDn`` = 10 * increment * the product of the ``Shift``, ``Ctrl``, ``Alt`` |
| 110 |
factors; |
| 111 |
- ``Space`` sets the control's value to it's last valid state. |
| 112 |
|
| 113 |
|
| 114 |
Window Styles |
| 115 |
============= |
| 116 |
|
| 117 |
This class supports the following window styles: |
| 118 |
|
| 119 |
=============== =========== ================================================== |
| 120 |
Window Styles Hex Value Description |
| 121 |
=============== =========== ================================================== |
| 122 |
``FS_READONLY`` 0x1 Sets :class:`FloatSpin` as read-only control. |
| 123 |
``FS_LEFT`` 0x2 Horizontally align the underlying :class:`TextCtrl` on the left. |
| 124 |
``FS_CENTRE`` 0x4 Horizontally align the underlying :class:`TextCtrl` on center. |
| 125 |
``FS_RIGHT`` 0x8 Horizontally align the underlying :class:`TextCtrl` on the right. |
| 126 |
=============== =========== ================================================== |
| 127 |
|
| 128 |
|
| 129 |
Events Processing |
| 130 |
================= |
| 131 |
|
| 132 |
This class processes the following events: |
| 133 |
|
| 134 |
================= ================================================== |
| 135 |
Event Name Description |
| 136 |
================= ================================================== |
| 137 |
``EVT_FLOATSPIN`` Emitted when the user changes the value of :class:`FloatSpin`, either with the mouse or with the keyboard. |
| 138 |
================= ================================================== |
| 139 |
|
| 140 |
|
| 141 |
License And Version |
| 142 |
=================== |
| 143 |
|
| 144 |
:class:`FloatSpin` control is distributed under the wxPython license. |
| 145 |
|
| 146 |
Latest revision: Andrea Gavana @ 03 Jan 2014, 23.00 GMT |
| 147 |
|
| 148 |
Version 0.9 |
| 149 |
|
| 150 |
|
| 151 |
Backward Incompatibilities |
| 152 |
========================== |
| 153 |
|
| 154 |
Modifications to allow `min_val` or `max_val` to be ``None`` done by: |
| 155 |
|
| 156 |
James Bigler, |
| 157 |
SCI Institute, University of Utah, |
| 158 |
March 14, 2007 |
| 159 |
|
| 160 |
:note: Note that the changes I made will break backward compatibility, |
| 161 |
because I changed the constructor's parameters from `min` / `max` to |
| 162 |
`min_val` / `max_val` to be consistent with the other functions and to |
| 163 |
eliminate any potential confusion with the built in `min` and `max` |
| 164 |
functions. |
| 165 |
|
| 166 |
You specify open ranges like this (you can equally do this in the |
| 167 |
constructor):: |
| 168 |
|
| 169 |
SetRange(min_val=1, max_val=None) # [1, ] |
| 170 |
SetRange(min_val=None, max_val=0) # [ , 0] |
| 171 |
|
| 172 |
or no range:: |
| 173 |
|
| 174 |
SetRange(min_val=None, max_val=None) # [ , ] |
| 175 |
|
| 176 |
""" # noqa: E501 |
| 177 |
|
| 178 |
from __future__ import annotations |
| 179 |
|
| 180 |
import locale |
| 181 |
import re |
| 182 |
from math import ceil, floor |
| 183 |
|
| 184 |
import wx |
| 185 |
|
| 186 |
# Set The Styles For The Underline wx.TextCtrl |
| 187 |
FS_READONLY = 1 |
| 188 |
""" Sets :class:`FloatSpin` as read-only control. """ |
| 189 |
FS_LEFT = 2 |
| 190 |
""" Horizontally align the underlying :class:`TextCtrl` on the left. """ |
| 191 |
FS_CENTRE = 4 |
| 192 |
""" Horizontally align the underlying :class:`TextCtrl` on center. """ |
| 193 |
FS_RIGHT = 8 |
| 194 |
""" Horizontally align the underlying :class:`TextCtrl` on the right. """ |
| 195 |
|
| 196 |
# Define The FloatSpin Event |
| 197 |
wxEVT_FLOATSPIN = wx.NewEventType() # noqa: N816 |
| 198 |
|
| 199 |
|
| 200 |
EVT_FLOATSPIN = wx.PyEventBinder(wxEVT_FLOATSPIN, 1) |
| 201 |
"""Emitted when the user changes the value of :class:`FloatSpin`, either with the mouse |
| 202 |
or with the keyboard. |
| 203 |
""" |
| 204 |
|
| 205 |
|
| 206 |
class FloatSpinEvent(wx.PyCommandEvent): |
| 207 |
"""This event will be sent when a ``EVT_FLOATSPIN`` event is mapped in the parent. |
| 208 |
|
| 209 |
Args: |
| 210 |
eventType (int): the event type; |
| 211 |
eventId (int, optional): The event identifier; |
| 212 |
n_old_sel (int, optional): The old selection. |
| 213 |
n_sel (int, optional): The current selection; |
| 214 |
""" |
| 215 |
|
| 216 |
def __init__( |
| 217 |
self, |
| 218 |
eventType: int, # noqa: N803 |
| 219 |
eventId: int = 1, # noqa: N803 |
| 220 |
n_sel: int = -1, |
| 221 |
n_old_sel: int = -1, |
| 222 |
) -> None: |
| 223 |
wx.PyCommandEvent.__init__(self, eventType, eventId) |
| 224 |
self._eventType = eventType |
| 225 |
|
| 226 |
def SetPosition(self, pos: int) -> None: # noqa: N802 |
| 227 |
"""Set event position. |
| 228 |
|
| 229 |
Args: |
| 230 |
pos (int): An integer specifying the event position. |
| 231 |
""" |
| 232 |
self._position = pos |
| 233 |
|
| 234 |
def GetPosition(self) -> int: # noqa: N802 |
| 235 |
"""Return event position. |
| 236 |
|
| 237 |
Returns: |
| 238 |
int: The event position. |
| 239 |
""" |
| 240 |
return self._position |
| 241 |
|
| 242 |
|
| 243 |
class FloatTextCtrl(wx.TextCtrl): |
| 244 |
"""A class which holds a :class:`TextCtrl`. |
| 245 |
|
| 246 |
This is one of the two building blocks of :class:`FloatSpin`. |
| 247 |
|
| 248 |
Args: |
| 249 |
parent: The :class:`FloatTextCtrl` parent. |
| 250 |
id: an identifier for the control: a value of -1 is taken to mean a |
| 251 |
default. |
| 252 |
value: default text value. |
| 253 |
pos: the control position. A value of (-1, -1) indicates a default |
| 254 |
position, chosen by either the windowing system or wxPython, |
| 255 |
depending on platform. |
| 256 |
size: the control size. A value of (-1, -1) indicates a default size, |
| 257 |
chosen by either the windowing system or wxPython, depending on |
| 258 |
platform. |
| 259 |
style: the window style; |
| 260 |
validator: the window validator; |
| 261 |
name: the window name. |
| 262 |
""" |
| 263 |
|
| 264 |
def __init__( |
| 265 |
self, |
| 266 |
parent: wx.Window, |
| 267 |
id: id = wx.ID_ANY, # noqa: A002 |
| 268 |
value: None | str | float | FixedPoint = "", |
| 269 |
pos: wx.Point = wx.DefaultPosition, |
| 270 |
size: wx.Size = wx.DefaultSize, |
| 271 |
style: int = wx.TE_NOHIDESEL | wx.TE_PROCESS_ENTER, |
| 272 |
validator: wx.Validator = wx.DefaultValidator, |
| 273 |
name: str = wx.TextCtrlNameStr, |
| 274 |
) -> None: |
| 275 |
wx.TextCtrl.__init__(self, parent, id, value, pos, size, style, validator, name) |
| 276 |
|
| 277 |
self._parent = parent |
| 278 |
self._selection = (-1, -1) |
| 279 |
self._value = value |
| 280 |
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy) |
| 281 |
self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) |
| 282 |
self.Bind(wx.EVT_SET_FOCUS, self.OnFocus) |
| 283 |
self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus) |
| 284 |
|
| 285 |
def OnDestroy(self, event: wx.WindowDestroyEvent) -> int: # noqa: N802 |
| 286 |
"""Handle the ``wx.EVT_WINDOW_DESTROY`` event for :class:`FloatTextCtrl`. |
| 287 |
|
| 288 |
Note: This method tries to correctly handle the control destruction |
| 289 |
under MSW. |
| 290 |
|
| 291 |
Args: |
| 292 |
event (wx.WindowDestroyEvent): A :class:`WindowDestroyEvent` event |
| 293 |
to be processed. |
| 294 |
|
| 295 |
Returns: |
| 296 |
int: Returns 0 to indicate that the event has been processed. |
| 297 |
""" |
| 298 |
if self._parent: |
| 299 |
self._parent._textctrl = None |
| 300 |
self._parent = None |
| 301 |
return 0 |
| 302 |
|
| 303 |
def OnKeyDown(self, event: wx.KeyEvent) -> None: # noqa: N802 |
| 304 |
"""Handle the ``wx.EVT_KEYDOWN`` event for :class:`FloatTextCtrl`. |
| 305 |
|
| 306 |
Args: |
| 307 |
event (wx.KeyEvent): A :class:`KeyEvent` event to be processed. |
| 308 |
""" |
| 309 |
if self._parent: |
| 310 |
self._parent.OnKeyDown(event) |
| 311 |
|
| 312 |
def OnFocus(self, event: wx.FocusEvent) -> None: # noqa: N802 |
| 313 |
"""Handle the ``wx.EVT_SET_FOCUS`` event for :class:`FloatTextCtrl`. |
| 314 |
|
| 315 |
Args: |
| 316 |
event (wx.FocusEvent): A :class:`FocusEvent` event to be processed. |
| 317 |
""" |
| 318 |
self._value = self.Value |
| 319 |
self.RestoreSelection() |
| 320 |
event.Skip() |
| 321 |
|
| 322 |
def OnKillFocus(self, event: wx.FocusEvent) -> None: # noqa: N802 |
| 323 |
"""Handle the ``wx.EVT_KILL_FOCUS`` event for :class:`FloatTextCtrl`. |
| 324 |
|
| 325 |
Args: |
| 326 |
event: A :class:`FocusEvent` event to be processed. |
| 327 |
|
| 328 |
Note: |
| 329 |
This method synchronizes the :class:`SpinButton` and the |
| 330 |
:class:`TextCtrl` when focus is lost. |
| 331 |
""" |
| 332 |
self._selection = self.GetSelection() |
| 333 |
if self._parent and self.Value != self._value: |
| 334 |
self._parent.SyncSpinToText(True) |
| 335 |
self.SetSelection(0, 0) |
| 336 |
|
| 337 |
event.Skip() |
| 338 |
|
| 339 |
def RestoreSelection(self) -> None: # noqa: N802 |
| 340 |
"""Restore the selection under Mac OS X. |
| 341 |
|
| 342 |
Select all under other platforms (consistent with default wx.TextCtrl |
| 343 |
behaviour). |
| 344 |
""" |
| 345 |
if "__WXMAC__" in wx.PlatformInfo and self._selection != (-1, -1): |
| 346 |
self.SetSelection(*self._selection) |
| 347 |
else: |
| 348 |
self.SelectAll() |
| 349 |
|
| 350 |
|
| 351 |
class FloatSpin(wx.PyControl): |
| 352 |
"""Implements a floating point :class:`SpinCtrl`. |
| 353 |
|
| 354 |
This Is The Main Class Implementation |
| 355 |
|
| 356 |
It is built using a custom :class:`PyControl`, composed by a |
| 357 |
:class:`TextCtrl` and a :class:`SpinButton`. In order to correctly handle |
| 358 |
floating points numbers without rounding errors or non-exact floating point |
| 359 |
representations, :class:`FloatSpin` uses the great :class:`FixedPoint` |
| 360 |
class from Tim Peters. |
| 361 |
""" |
| 362 |
|
| 363 |
_spinwidth = 0 |
| 364 |
|
| 365 |
def __init__( |
| 366 |
self, |
| 367 |
parent: wx.Window, |
| 368 |
id: int = wx.ID_ANY, # noqa: A002 |
| 369 |
pos: wx.Point = wx.DefaultPosition, |
| 370 |
size: tuple[int, int] = (130, -1), |
| 371 |
style: int = 0, |
| 372 |
value: None | str | float | FixedPoint = 0.0, |
| 373 |
min_val: None | str | float | FixedPoint = None, |
| 374 |
max_val: None | str | float | FixedPoint = None, |
| 375 |
increment: float = 1.0, |
| 376 |
digits: int = -1, |
| 377 |
agw_style: int = FS_LEFT, |
| 378 |
name: str = "FloatSpin", |
| 379 |
) -> None: |
| 380 |
"""Default class constructor. |
| 381 |
|
| 382 |
Args: |
| 383 |
parent (FloatSpin): The :class:`FloatSpin` parent. |
| 384 |
id (int): An identifier for the control: a value of -1 is taken to |
| 385 |
mean a default. |
| 386 |
pos: The control position. A value of (-1, -1) indicates a default |
| 387 |
position, chosen by either the windowing system or wxPython, |
| 388 |
depending on platform. |
| 389 |
size: The control size. A value of (-1, -1) indicates a default |
| 390 |
size, chosen by either the windowing system or wxPython, |
| 391 |
depending on platform; |
| 392 |
style: The window style. |
| 393 |
value: The current value for :class:`FloatSpin`. |
| 394 |
min_val: The minimum value, ignored if ``None``. |
| 395 |
max_val: the maximum value, ignored if ``None``. |
| 396 |
increment: the increment for every :class:`FloatSpinEvent` event. |
| 397 |
digits: number of representative digits for your floating point numbers. |
| 398 |
agw_style: one of the following bits: |
| 399 |
|
| 400 |
=============== =========== ================================================== |
| 401 |
Window Styles Hex Value Description |
| 402 |
=============== =========== ================================================== |
| 403 |
``FS_READONLY`` 0x1 Sets :class:`FloatSpin` as read-only control. |
| 404 |
``FS_LEFT`` 0x2 Horizontally align the underlying :class:`TextCtrl` on the left. |
| 405 |
``FS_CENTRE`` 0x4 Horizontally align the underlying :class:`TextCtrl` on center. |
| 406 |
``FS_RIGHT`` 0x8 Horizontally align the underlying :class:`TextCtrl` on the right. |
| 407 |
=============== =========== ================================================== |
| 408 |
|
| 409 |
name (str): The window name. |
| 410 |
""" # noqa: E501 |
| 411 |
wx.PyControl.__init__( |
| 412 |
self, |
| 413 |
parent, |
| 414 |
id, |
| 415 |
pos, |
| 416 |
size, |
| 417 |
style | wx.NO_BORDER | wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN, |
| 418 |
wx.DefaultValidator, |
| 419 |
name, |
| 420 |
) |
| 421 |
|
| 422 |
# Don't call SetRange here, because it will try to modify |
| 423 |
# self._value whose value doesn't exist yet. |
| 424 |
self.SetRangeDontClampValue(min_val, max_val) |
| 425 |
self._value = self.ClampValue(FixedPoint(str(value), 20)) |
| 426 |
self._defaultvalue = self._value |
| 427 |
self._increment = FixedPoint(str(increment), 20) |
| 428 |
self._spinmodifier = FixedPoint(str(1.0), 20) |
| 429 |
self._digits = digits |
| 430 |
self._snapticks = False |
| 431 |
self._spinbutton = None |
| 432 |
self._ignore_spin_event = False |
| 433 |
self._textctrl = None |
| 434 |
self._spinctrl_bestsize = wx.Size(-999, -999) |
| 435 |
self._enabled = True |
| 436 |
|
| 437 |
# start Philip Semanchuk addition |
| 438 |
# The textbox & spin button are drawn slightly differently |
| 439 |
# depending on the platform. The difference is most pronounced |
| 440 |
# under OS X. |
| 441 |
if "__WXMAC__" in wx.PlatformInfo: |
| 442 |
self._gap = 8 |
| 443 |
self._spin_top = 3 |
| 444 |
self._text_left = 4 |
| 445 |
self._text_top = 4 |
| 446 |
elif "__WXMSW__" in wx.PlatformInfo: |
| 447 |
self._gap = 1 |
| 448 |
self._spin_top = 0 |
| 449 |
self._text_left = 0 |
| 450 |
self._text_top = 0 |
| 451 |
else: |
| 452 |
# GTK |
| 453 |
self._gap = 1 if "gtk3" in wx.PlatformInfo else -1 |
| 454 |
self._spin_top = 0 |
| 455 |
self._text_left = 0 |
| 456 |
self._text_top = 0 |
| 457 |
# end Philip Semanchuk addition |
| 458 |
|
| 459 |
self.SetLabel(name) |
| 460 |
self.SetForegroundColour(parent.GetForegroundColour()) |
| 461 |
|
| 462 |
width = size[0] |
| 463 |
height = size[1] |
| 464 |
best_size = self.DoGetBestSize() |
| 465 |
|
| 466 |
width = best_size.GetWidth() if width == -1 else width |
| 467 |
height = best_size.GetHeight() if height == -1 else height |
| 468 |
|
| 469 |
self._validkeycode = [43, 44, 45, 46, 69, 101] |
| 470 |
self._validkeycode.extend(list(range(48, 58))) |
| 471 |
self._validkeycode.extend( |
| 472 |
[ |
| 473 |
wx.WXK_BACK, |
| 474 |
wx.WXK_DELETE, |
| 475 |
wx.WXK_LEFT, |
| 476 |
wx.WXK_RIGHT, |
| 477 |
wx.WXK_NUMPAD0, |
| 478 |
wx.WXK_NUMPAD1, |
| 479 |
wx.WXK_NUMPAD2, |
| 480 |
wx.WXK_NUMPAD3, |
| 481 |
wx.WXK_NUMPAD4, |
| 482 |
wx.WXK_NUMPAD5, |
| 483 |
wx.WXK_NUMPAD6, |
| 484 |
wx.WXK_NUMPAD7, |
| 485 |
wx.WXK_NUMPAD8, |
| 486 |
wx.WXK_NUMPAD9, |
| 487 |
wx.WXK_NUMPAD_ADD, |
| 488 |
wx.WXK_NUMPAD_DECIMAL, |
| 489 |
wx.WXK_NUMPAD_SEPARATOR, |
| 490 |
wx.WXK_NUMPAD_SUBTRACT, |
| 491 |
] |
| 492 |
) |
| 493 |
|
| 494 |
self._spinbutton = wx.SpinButton( |
| 495 |
self, |
| 496 |
wx.ID_ANY, |
| 497 |
wx.DefaultPosition, |
| 498 |
size=(-1, height), |
| 499 |
style=wx.SP_ARROW_KEYS | wx.SP_VERTICAL | wx.SP_WRAP, |
| 500 |
) |
| 501 |
self._spinbutton.SetRange(-(2**32) / 2.0, 2**32 / 2.0 - 1) |
| 502 |
self._spinbutton.AcceptsFocusFromKeyboard = lambda: False |
| 503 |
if "gtk3" in wx.PlatformInfo: |
| 504 |
if not FloatSpin._spinwidth: |
| 505 |
spin = wx.SpinCtrl(self, -1) |
| 506 |
text = wx.TextCtrl(self, -1) |
| 507 |
FloatSpin._spinwidth = spin.Size[0] - text.Size[0] + 11 |
| 508 |
spin.Destroy() |
| 509 |
text.Destroy() |
| 510 |
self._spinbutton.MaxSize = FloatSpin._spinwidth, height |
| 511 |
|
| 512 |
txtstyle = wx.TE_NOHIDESEL | wx.TE_PROCESS_ENTER |
| 513 |
|
| 514 |
if agw_style & FS_RIGHT: |
| 515 |
txtstyle = txtstyle | wx.TE_RIGHT |
| 516 |
elif agw_style & FS_CENTRE: |
| 517 |
txtstyle = txtstyle | wx.TE_CENTER |
| 518 |
|
| 519 |
txtstyle = ( |
| 520 |
(txtstyle | wx.TE_READONLY) if (agw_style & FS_READONLY) else txtstyle |
| 521 |
) |
| 522 |
|
| 523 |
self._textctrl = FloatTextCtrl( |
| 524 |
self, |
| 525 |
wx.ID_ANY, |
| 526 |
"", |
| 527 |
wx.DefaultPosition, |
| 528 |
(width - self._spinbutton.GetSize().GetWidth(), height), |
| 529 |
txtstyle, |
| 530 |
) |
| 531 |
|
| 532 |
# start Philip Semanchuk addition |
| 533 |
# Setting the textctrl's size in the ctor also sets its min size. |
| 534 |
# But the textctrl is entirely controlled by the parent floatspin |
| 535 |
# control and should accept whatever size its parent dictates, so |
| 536 |
# here we tell it to forget its min size. |
| 537 |
self._textctrl.SetMinSize(wx.DefaultSize) |
| 538 |
# Setting the spin buttons's size in the ctor also sets its min size. |
| 539 |
# Under OS X that results in a rendering artifact because spin buttons |
| 540 |
# are a little shorter than textboxes. |
| 541 |
# Setting the min size to the default allows OS X to draw the spin |
| 542 |
# button correctly. However, Windows and KDE take the call to |
| 543 |
# SetMinSize() as a cue to size the spin button taller than the |
| 544 |
# textbox, so we avoid the call there. |
| 545 |
if "__WXMAC__" in wx.PlatformInfo: |
| 546 |
self._spinbutton.SetMinSize(wx.DefaultSize) |
| 547 |
# end Philip Semanchuk addition |
| 548 |
|
| 549 |
self._mainsizer = wx.BoxSizer(wx.HORIZONTAL) |
| 550 |
# Ensure the spin button is shown, and the text widget takes |
| 551 |
# all remaining free space |
| 552 |
self._mainsizer.Add(self._textctrl, 1) |
| 553 |
if "gtk3" in wx.PlatformInfo: |
| 554 |
self._mainsizer.Add((self._gap, 1), 0) |
| 555 |
self._mainsizer.Add(self._spinbutton, 0) |
| 556 |
self.SetSizer(self._mainsizer) |
| 557 |
self._mainsizer.Layout() |
| 558 |
|
| 559 |
self.SetFormat() |
| 560 |
|
| 561 |
if not (agw_style & FS_READONLY): |
| 562 |
self.Bind(wx.EVT_SPIN_UP, self.OnSpinUp) |
| 563 |
self.Bind(wx.EVT_SPIN_DOWN, self.OnSpinDown) |
| 564 |
self._spinbutton.Bind(wx.EVT_LEFT_DOWN, self.OnSpinMouseDown) |
| 565 |
self._spinbutton.Bind(wx.EVT_LEFT_UP, self.OnSpinMouseUp) |
| 566 |
|
| 567 |
self._textctrl.Bind(wx.EVT_TEXT_ENTER, self.OnTextEnter) |
| 568 |
self._textctrl.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel) |
| 569 |
self._spinbutton.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel) |
| 570 |
|
| 571 |
self.Bind(wx.EVT_SET_FOCUS, self.OnFocus) |
| 572 |
|
| 573 |
if "gtk3" not in wx.PlatformInfo: |
| 574 |
self.Bind(wx.EVT_SIZE, self.OnSize) |
| 575 |
|
| 576 |
if hasattr(self, "SetBestSize"): |
| 577 |
# Not Phoenix |
| 578 |
# start Philip Semanchuk move |
| 579 |
self.SetBestSize((width, height)) |
| 580 |
# end Philip Semanchuk move |
| 581 |
|
| 582 |
def OnDestroy(self, event: wx.WindowDestroyEvent) -> int: # noqa: N802 |
| 583 |
"""Handle the ``wx.EVT_WINDOW_DESTROY`` event for :class:`FloatSpin`. |
| 584 |
|
| 585 |
Note: This method tries to correctly handle the control destruction |
| 586 |
under MSW. |
| 587 |
|
| 588 |
Args: |
| 589 |
event (wx.WindowDestroyEvent): A :class:`WindowDestroyEvent` event |
| 590 |
to be processed. |
| 591 |
|
| 592 |
Returns: |
| 593 |
int: Returns 0 to indicate that the event has been processed. |
| 594 |
""" |
| 595 |
# Null This Since MSW Sends KILL_FOCUS On Deletion |
| 596 |
if self._textctrl: |
| 597 |
self._textctrl._parent = None |
| 598 |
self._textctrl.Destroy() |
| 599 |
self._textctrl = None |
| 600 |
|
| 601 |
self._spinbutton.Destroy() |
| 602 |
self._spinbutton = None |
| 603 |
|
| 604 |
return 0 |
| 605 |
|
| 606 |
def DoGetBestSize(self) -> wx.Size: # noqa: N802 |
| 607 |
"""Get the size which best suits the window: for a control. |
| 608 |
|
| 609 |
It would be the minimal size which doesn't truncate the control, for a |
| 610 |
panel - the same size as it would have after a call to `Fit()`. |
| 611 |
|
| 612 |
:note: Overridden from :class:`PyControl`. |
| 613 |
""" |
| 614 |
if self._spinctrl_bestsize.x == -999: |
| 615 |
spin = wx.SpinCtrl(self, -1) |
| 616 |
self._spinctrl_bestsize = spin.GetBestSize() |
| 617 |
|
| 618 |
# oops something went wrong, set to reasonable value |
| 619 |
if self._spinctrl_bestsize.GetWidth() < 20: |
| 620 |
self._spinctrl_bestsize.SetWidth(95) |
| 621 |
if self._spinctrl_bestsize.GetHeight() < 10: |
| 622 |
self._spinctrl_bestsize.SetHeight(22) |
| 623 |
|
| 624 |
spin.Destroy() |
| 625 |
|
| 626 |
return self._spinctrl_bestsize |
| 627 |
|
| 628 |
def DoSendEvent(self) -> None: # noqa: N802 |
| 629 |
"""Send the event to the parent.""" |
| 630 |
event = wx.CommandEvent(wx.wxEVT_COMMAND_SPINCTRL_UPDATED, self.GetId()) |
| 631 |
event.SetEventObject(self) |
| 632 |
event.SetInt(int(self._value + 0.5)) |
| 633 |
|
| 634 |
if self._textctrl: |
| 635 |
event.SetString(self._textctrl.GetValue()) |
| 636 |
|
| 637 |
self.GetEventHandler().ProcessEvent(event) |
| 638 |
|
| 639 |
event_out = FloatSpinEvent(wxEVT_FLOATSPIN, self.GetId()) |
| 640 |
event_out.SetPosition(int(self._value + 0.5)) |
| 641 |
event_out.SetEventObject(self) |
| 642 |
self.GetEventHandler().ProcessEvent(event_out) |
| 643 |
|
| 644 |
def Disable(self) -> None: # noqa: N802 |
| 645 |
"""Disable the child controls. This is needed under wxMac.""" |
| 646 |
self.Enable(False) |
| 647 |
|
| 648 |
def Enable(self, enable: bool = True) -> None: # noqa: N802 |
| 649 |
"""Enable the child controls. This is needed under wxMac. |
| 650 |
|
| 651 |
Args: |
| 652 |
enable (bool, optional): If ``True``, the control is enabled, |
| 653 |
otherwise it is disabled. Defaults to ``True``. |
| 654 |
""" |
| 655 |
wx.PyControl.Enable(self, enable) |
| 656 |
self._enabled = enable |
| 657 |
|
| 658 |
if self._textctrl: |
| 659 |
self._textctrl.Enable(enable) |
| 660 |
self._spinbutton.Enable(enable) |
| 661 |
|
| 662 |
@property |
| 663 |
def Enabled(self) -> bool: # noqa: N802 |
| 664 |
"""Return whether the control is enabled or not. |
| 665 |
|
| 666 |
Returns: |
| 667 |
bool: ``True`` if the control is enabled, ``False`` otherwise. |
| 668 |
""" |
| 669 |
return self._enabled |
| 670 |
|
| 671 |
@Enabled.setter |
| 672 |
def Enabled(self, enable: bool = True) -> None: # noqa: N802 |
| 673 |
"""Set whether the control is enabled or not. |
| 674 |
|
| 675 |
Args: |
| 676 |
enable (bool, optional): If ``True``, the control is enabled, |
| 677 |
otherwise it is disabled. |
| 678 |
""" |
| 679 |
self.Enable(enable) |
| 680 |
|
| 681 |
def IsEnabled(self) -> bool: # noqa: N802 |
| 682 |
"""Return whether the control is enabled or not. |
| 683 |
|
| 684 |
Returns: |
| 685 |
bool: ``True`` if the control is enabled, ``False`` otherwise. |
| 686 |
""" |
| 687 |
return self._enabled |
| 688 |
|
| 689 |
def OnSpinMouseDown(self, event: wx.MouseEvent) -> None: # noqa: N802 |
| 690 |
"""Handle the ``wx.EVT_LEFT_DOWN`` event for :class:`FloatSpin`. |
| 691 |
|
| 692 |
Note: |
| 693 |
This method works on the underlying :class:`SpinButton`. |
| 694 |
|
| 695 |
Args: |
| 696 |
event (wx.MouseEvent): a :class:`MouseEvent` event to be processed. |
| 697 |
|
| 698 |
""" |
| 699 |
modifier = FixedPoint(str(1.0), 20) |
| 700 |
if event.ShiftDown(): |
| 701 |
modifier = modifier * 2.0 |
| 702 |
if event.ControlDown(): |
| 703 |
modifier = modifier * 10.0 |
| 704 |
if event.AltDown(): |
| 705 |
modifier = modifier * 100.0 |
| 706 |
|
| 707 |
self._spinmodifier = modifier |
| 708 |
|
| 709 |
self._ignore_spin_event = False |
| 710 |
event.Skip() |
| 711 |
|
| 712 |
def OnSpinMouseUp(self, event: wx.MouseEvent) -> None: # noqa: N802 |
| 713 |
"""Handle the ``wx.EVT_LEFT_UP`` event for :class:`FloatSpin`. |
| 714 |
|
| 715 |
Note: |
| 716 |
This method works on the underlying :class:`SpinButton`. |
| 717 |
|
| 718 |
Args: |
| 719 |
event (wx.MouseEvent): a :class:`MouseEvent` event to be processed. |
| 720 |
|
| 721 |
""" |
| 722 |
if self._textctrl: |
| 723 |
if "__WXMSW__" in wx.PlatformInfo: |
| 724 |
self._textctrl.SetFocus() |
| 725 |
self._textctrl.SelectAll() |
| 726 |
elif "__WXMAC__" not in wx.PlatformInfo: |
| 727 |
self._textctrl.SetFocus() |
| 728 |
self._textctrl.SetSelection(0, 0) |
| 729 |
|
| 730 |
self._ignore_spin_event = False |
| 731 |
event.Skip() |
| 732 |
|
| 733 |
def OnSpinUp(self, event: wx.SpinEvent) -> None: # noqa: N802 |
| 734 |
"""Handle the ``wx.EVT_SPIN_UP`` event for :class:`FloatSpin`. |
| 735 |
|
| 736 |
Args: |
| 737 |
event (wx.SpinEvent): a :class:`SpinEvent` event to be processed. |
| 738 |
""" |
| 739 |
if self._ignore_spin_event: |
| 740 |
self._ignore_spin_event = False |
| 741 |
return |
| 742 |
|
| 743 |
if self._textctrl and self._textctrl.IsModified(): |
| 744 |
self.SyncSpinToText(False) |
| 745 |
|
| 746 |
if self.InRange(self._value + self._increment * self._spinmodifier): |
| 747 |
self._value = self._value + self._increment * self._spinmodifier |
| 748 |
elif self._max is not None: |
| 749 |
self._value = self._max |
| 750 |
self.SetValue(self._value) |
| 751 |
if "__WXMAC__" in wx.PlatformInfo: |
| 752 |
self._textctrl.SelectAll() |
| 753 |
self.DoSendEvent() |
| 754 |
|
| 755 |
def OnSpinDown(self, event: wx.SpinEvent) -> None: # noqa: N802 |
| 756 |
"""Handle the ``wx.EVT_SPIN_DOWN`` event for :class:`FloatSpin`. |
| 757 |
|
| 758 |
Args: |
| 759 |
event (wx.SpinEvent): a :class:`SpinEvent` event to be processed. |
| 760 |
""" |
| 761 |
if self._ignore_spin_event: |
| 762 |
self._ignore_spin_event = False |
| 763 |
return |
| 764 |
|
| 765 |
if self._textctrl and self._textctrl.IsModified(): |
| 766 |
self.SyncSpinToText(False) |
| 767 |
|
| 768 |
if self.InRange(self._value - self._increment * self._spinmodifier): |
| 769 |
self._value = self._value - self._increment * self._spinmodifier |
| 770 |
elif self._min is not None: |
| 771 |
self._value = self._min |
| 772 |
self.SetValue(self._value) |
| 773 |
if "__WXMAC__" in wx.PlatformInfo: |
| 774 |
self._textctrl.SelectAll() |
| 775 |
self.DoSendEvent() |
| 776 |
|
| 777 |
def OnTextEnter(self, event: wx.KeyEvent) -> None: # noqa: N802 |
| 778 |
"""Handle the ``wx.EVT_TEXT_ENTER`` event for :class:`FloatSpin`. |
| 779 |
|
| 780 |
Note: |
| 781 |
This method works on the underlying :class:`TextCtrl`. |
| 782 |
|
| 783 |
Args: |
| 784 |
event (wx.KeyEvent): a :class:`KeyEvent` event to be processed. |
| 785 |
""" |
| 786 |
self.SyncSpinToText(True) |
| 787 |
event.Skip() |
| 788 |
|
| 789 |
def OnKeyDown(self, event: wx.KeyEvent) -> None: # noqa: N802 |
| 790 |
"""Handle the ``wx.EVT_KEYDOWN`` event for :class:`FloatSpin`. |
| 791 |
|
| 792 |
Note: |
| 793 |
This method works on the underlying :class:`TextCtrl`. |
| 794 |
|
| 795 |
Args: |
| 796 |
event (wx.KeyEvent): a :class:`KeyEvent` event to be processed. |
| 797 |
""" |
| 798 |
modifier = FixedPoint(str(1.0), 20) |
| 799 |
if event.ShiftDown(): |
| 800 |
modifier = modifier * 2.0 |
| 801 |
if event.ControlDown(): |
| 802 |
modifier = modifier * 10.0 |
| 803 |
if event.AltDown(): |
| 804 |
modifier = modifier * 100.0 |
| 805 |
|
| 806 |
keycode = event.GetKeyCode() |
| 807 |
|
| 808 |
if keycode == wx.WXK_UP: |
| 809 |
self._handle_wxk_up_key(modifier) |
| 810 |
elif keycode == wx.WXK_DOWN: |
| 811 |
self._handle_wxk_down_key(modifier) |
| 812 |
elif keycode == wx.WXK_PAGEUP: |
| 813 |
self._handle_wxk_pageup_key(modifier) |
| 814 |
elif keycode == wx.WXK_PAGEDOWN: |
| 815 |
self._handle_wxk_pagedown_key(modifier) |
| 816 |
elif keycode == wx.WXK_SPACE: |
| 817 |
self._handle_wxk_space_key(event) |
| 818 |
elif keycode == wx.WXK_ESCAPE: |
| 819 |
self._handle_wxk_escape_key() |
| 820 |
elif keycode == wx.WXK_TAB: |
| 821 |
# The original event code doesn't work under wxGTK |
| 822 |
focus_next_keyboard_focusable_control(event.EventObject) |
| 823 |
elif keycode in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER): |
| 824 |
self._handle_wxk_return_key() |
| 825 |
else: |
| 826 |
self._handle_wxk_default_key(event, keycode) |
| 827 |
|
| 828 |
def _handle_wxk_up_key(self, modifier: FixedPoint) -> None: |
| 829 |
"""Handle the ``wx.WXK_UP`` key event for :class:`FloatSpin`. |
| 830 |
|
| 831 |
Args: |
| 832 |
modifier (FixedPoint): The modifier to apply to the increment. |
| 833 |
""" |
| 834 |
if self._textctrl and self._textctrl.IsModified(): |
| 835 |
self.SyncSpinToText(False) |
| 836 |
|
| 837 |
self.SetValue(self._value + self._increment * modifier) |
| 838 |
self.DoSendEvent() |
| 839 |
|
| 840 |
def _handle_wxk_down_key(self, modifier: FixedPoint) -> None: |
| 841 |
"""Handle the ``wx.WXK_DOWN`` key event for :class:`FloatSpin`. |
| 842 |
|
| 843 |
Args: |
| 844 |
modifier (FixedPoint): The modifier to apply to the increment. |
| 845 |
""" |
| 846 |
if self._textctrl and self._textctrl.IsModified(): |
| 847 |
self.SyncSpinToText(False) |
| 848 |
|
| 849 |
self.SetValue(self._value - self._increment * modifier) |
| 850 |
self.DoSendEvent() |
| 851 |
|
| 852 |
def _handle_wxk_pageup_key(self, modifier: FixedPoint) -> None: |
| 853 |
"""Handle the ``wx.WXK_PAGEUP`` key event for :class:`FloatSpin`. |
| 854 |
|
| 855 |
Args: |
| 856 |
modifier (FixedPoint): The modifier to apply to the increment. |
| 857 |
""" |
| 858 |
if self._textctrl and self._textctrl.IsModified(): |
| 859 |
self.SyncSpinToText(False) |
| 860 |
|
| 861 |
self.SetValue(self._value + 10.0 * self._increment * modifier) |
| 862 |
self.DoSendEvent() |
| 863 |
|
| 864 |
def _handle_wxk_pagedown_key(self, modifier: FixedPoint) -> None: |
| 865 |
"""Handle the ``wx.WXK_PAGEDOWN`` key event for :class:`FloatSpin`. |
| 866 |
|
| 867 |
Args: |
| 868 |
modifier (FixedPoint): The modifier to apply to the increment. |
| 869 |
""" |
| 870 |
if self._textctrl and self._textctrl.IsModified(): |
| 871 |
self.SyncSpinToText(False) |
| 872 |
|
| 873 |
self.SetValue(self._value - 10.0 * self._increment * modifier) |
| 874 |
self.DoSendEvent() |
| 875 |
|
| 876 |
def _handle_wxk_space_key(self, event: wx.KeyEvent) -> None: |
| 877 |
"""Handle the ``wx.WXK_SPACE`` key event for :class:`FloatSpin`. |
| 878 |
|
| 879 |
Args: |
| 880 |
event (wx.KeyEvent): A :class:`KeyEvent` event to be processed. |
| 881 |
""" |
| 882 |
self.SetValue(self._value) |
| 883 |
if self._textctrl: |
| 884 |
self._textctrl.SelectAll() |
| 885 |
event.Skip(False) |
| 886 |
|
| 887 |
def _handle_wxk_escape_key(self) -> None: |
| 888 |
"""Handle the ``wx.WXK_ESCAPE`` key event for :class:`FloatSpin`.""" |
| 889 |
self.SetToDefaultValue() |
| 890 |
if self._textctrl: |
| 891 |
self._textctrl.SelectAll() |
| 892 |
self.DoSendEvent() |
| 893 |
|
| 894 |
def _handle_wxk_return_key(self) -> None: |
| 895 |
"""Handle the ``wx.WXK_RETURN`` key event for :class:`FloatSpin`.""" |
| 896 |
default = self.TopLevelParent.DefaultItem |
| 897 |
if ( |
| 898 |
default |
| 899 |
and default.Enabled |
| 900 |
and default.IsShownOnScreen() |
| 901 |
and isinstance(default, wx.Button) |
| 902 |
): |
| 903 |
default.ProcessEvent( |
| 904 |
wx.PyCommandEvent(wx.EVT_BUTTON.typeId, default.GetId()) |
| 905 |
) |
| 906 |
|
| 907 |
def _handle_wxk_default_key(self, event: wx.KeyEvent, keycode: int) -> None: |
| 908 |
"""Handle the default key event for :class:`FloatSpin`. |
| 909 |
|
| 910 |
Args: |
| 911 |
event (wx.KeyEvent): A :class:`KeyEvent` event to be processed. |
| 912 |
keycode (int): The key code of the pressed key. |
| 913 |
""" |
| 914 |
if ( |
| 915 |
not event.CmdDown() |
| 916 |
and not event.ControlDown() |
| 917 |
and keycode not in self._validkeycode |
| 918 |
): |
| 919 |
return |
| 920 |
event.Skip() |
| 921 |
|
| 922 |
def OnMouseWheel(self, event: wx.MouseEvent) -> None: # noqa: N802 |
| 923 |
"""Handle the ``wx.EVT_MOUSEWHEEL`` event for :class:`FloatSpin`. |
| 924 |
|
| 925 |
Args: |
| 926 |
event (wx.MouseEvent): a :class:`MouseEvent` event to be processed. |
| 927 |
""" |
| 928 |
modifier = FixedPoint(str(1.0), 20) |
| 929 |
if event.ShiftDown(): |
| 930 |
modifier = modifier * 2.0 |
| 931 |
if event.ControlDown(): |
| 932 |
modifier = modifier * 10.0 |
| 933 |
if event.AltDown(): |
| 934 |
modifier = modifier * 100.0 |
| 935 |
|
| 936 |
if self._textctrl and self._textctrl.IsModified(): |
| 937 |
self.SyncSpinToText(False) |
| 938 |
|
| 939 |
if event.GetWheelRotation() > 0: |
| 940 |
self.SetValue(self._value + self._increment * modifier) |
| 941 |
|
| 942 |
else: |
| 943 |
self.SetValue(self._value - self._increment * modifier) |
| 944 |
|
| 945 |
if self._textctrl: |
| 946 |
if "__WXMAC__" in wx.PlatformInfo: |
| 947 |
self._textctrl.SelectAll() |
| 948 |
else: |
| 949 |
self._textctrl.SetFocus() |
| 950 |
self._textctrl.SetSelection(0, 0) |
| 951 |
|
| 952 |
self.DoSendEvent() |
| 953 |
|
| 954 |
def OnSize(self, event: wx.SizeEvent) -> None: # noqa: N802 |
| 955 |
"""Handle the ``wx.EVT_SIZE`` event for :class:`FloatSpin`. |
| 956 |
|
| 957 |
Note: |
| 958 |
This method resizes the text control and reposition the spin button |
| 959 |
when resized. |
| 960 |
|
| 961 |
Args: |
| 962 |
event (wx.SizeEvent): a :class:`SizeEvent` event to be processed. |
| 963 |
""" |
| 964 |
# start Philip Semanchuk addition |
| 965 |
event_width = event.GetSize().width |
| 966 |
|
| 967 |
self._textctrl.SetPosition((self._text_left, self._text_top)) |
| 968 |
|
| 969 |
text_width, text_height = self._textctrl.Size |
| 970 |
|
| 971 |
spin_width, _ = self._spinbutton.Size |
| 972 |
|
| 973 |
text_width = event_width - (spin_width + self._gap + self._text_left) |
| 974 |
|
| 975 |
self._textctrl.SetSize(wx.Size(text_width, event.GetSize().height)) |
| 976 |
|
| 977 |
# The spin button is always snug against the right edge of the |
| 978 |
# control. |
| 979 |
self._spinbutton.SetPosition((event_width - spin_width, self._spin_top)) |
| 980 |
|
| 981 |
event.Skip() |
| 982 |
# end Philip Semanchuk addition |
| 983 |
|
| 984 |
def ReplaceDoubleZero(self, strs: str) -> str: # noqa: N802 |
| 985 |
"""Replace the (somewhat) python ugly `+e000` with `+e00`. |
| 986 |
|
| 987 |
Args: |
| 988 |
strs (str): A string (possibly) containing a `+e00` substring. |
| 989 |
|
| 990 |
Returns: |
| 991 |
str: The modified string with `+e00` replaced by `+e0` or `-e00` |
| 992 |
replaced by `-e0`. |
| 993 |
""" |
| 994 |
if self._textformat not in ["%g", "%e", "%E", "%G"]: |
| 995 |
return strs |
| 996 |
|
| 997 |
if strs.find("e+00") >= 0: |
| 998 |
strs = strs.replace("e+00", "e+0") |
| 999 |
elif strs.find("e-00") >= 0: |
| 1000 |
strs = strs.replace("e-00", "e-0") |
| 1001 |
elif strs.find("E+00") >= 0: |
| 1002 |
strs = strs.replace("E+00", "E+0") |
| 1003 |
elif strs.find("E-00") >= 0: |
| 1004 |
strs = strs.replace("E-00", "E-0") |
| 1005 |
|
| 1006 |
return strs |
| 1007 |
|
| 1008 |
def SetValue(self, value: float | FixedPoint) -> None: # noqa: N802 |
| 1009 |
"""Set the :class:`FloatSpin` value. |
| 1010 |
|
| 1011 |
Args: |
| 1012 |
value (float | FixedPoint): The new value. |
| 1013 |
""" |
| 1014 |
if not self._textctrl or not self.InRange(value): |
| 1015 |
return |
| 1016 |
|
| 1017 |
if self._snapticks and self._increment != 0.0: |
| 1018 |
finite, snap_value = self.IsFinite(value) |
| 1019 |
|
| 1020 |
if not finite: # FIXME What To Do About A Failure? |
| 1021 |
if snap_value - floor(snap_value) < ceil(snap_value) - snap_value: |
| 1022 |
value = self._defaultvalue + floor(snap_value) * self._increment |
| 1023 |
else: |
| 1024 |
value = self._defaultvalue + ceil(snap_value) * self._increment |
| 1025 |
|
| 1026 |
decimal = locale.localeconv()["decimal_point"] |
| 1027 |
strs = ("%100." + str(self._digits) + self._textformat[1]) % value |
| 1028 |
strs = strs.replace(".", decimal) |
| 1029 |
strs = strs.replace(",", ".") |
| 1030 |
strs = strs.strip() |
| 1031 |
strs = self.ReplaceDoubleZero(strs) |
| 1032 |
|
| 1033 |
# Sync spinbutton so that events generated by it match up with the |
| 1034 |
# actual spin direction. |
| 1035 |
# This fixes an issue under GTK and Mac OS X where the EVT_SPIN event |
| 1036 |
# generated by pressing the spin up/down buttons is dependent on the |
| 1037 |
# spin button value (e.g. if the down button is pressed when the button |
| 1038 |
# value is at its minimum, there will always be a EVT_SPIN_UP generated |
| 1039 |
# under GTK, and no event at all under Mac OS X). |
| 1040 |
min_val = self._min if self._min is not None else self._spinbutton.Min |
| 1041 |
max_val = self._max if self._max is not None else self._spinbutton.Max |
| 1042 |
# Scale the value to the spinbutton range |
| 1043 |
spinvalue = round( |
| 1044 |
(float(value - min_val) / float(max_val - min_val)) * self._spinbutton.Max |
| 1045 |
) |
| 1046 |
# Setting the spin button value causes a EVT_SPIN event to be generated |
| 1047 |
# under GTK, which we need to ignore |
| 1048 |
self._ignore_spin_event = True |
| 1049 |
self._spinbutton.SetValue(spinvalue) |
| 1050 |
|
| 1051 |
if value != self._value or strs != self._textctrl.GetValue(): |
| 1052 |
self._textctrl.SetValue(strs) |
| 1053 |
self._textctrl.DiscardEdits() |
| 1054 |
self._value = value |
| 1055 |
|
| 1056 |
def GetValue(self) -> float: # noqa: N802 |
| 1057 |
"""Return the :class:`FloatSpin` value. |
| 1058 |
|
| 1059 |
Returns: |
| 1060 |
float: The current value of :class:`FloatSpin`. |
| 1061 |
""" |
| 1062 |
return float(self._value) |
| 1063 |
|
| 1064 |
def SetRangeDontClampValue( # noqa: N802 |
| 1065 |
self, |
| 1066 |
min_val: None | float | FixedPoint, |
| 1067 |
max_val: None | float | FixedPoint, |
| 1068 |
) -> None: |
| 1069 |
"""Set the allowed range. |
| 1070 |
|
| 1071 |
Args: |
| 1072 |
min_val (None | float | FixedPoint): The minimum value for |
| 1073 |
:class:`FloatSpin`. If it is `None` it is ignored. |
| 1074 |
max_val (None | float | FixedPoint): the maximum value for |
| 1075 |
:class:`FloatSpin`. If it is `None` it is ignored. |
| 1076 |
|
| 1077 |
:note: This method doesn't modify the current value. |
| 1078 |
""" |
| 1079 |
if min_val is not None: |
| 1080 |
self._min = FixedPoint(str(min_val), 20) |
| 1081 |
else: |
| 1082 |
self._min = None |
| 1083 |
if max_val is not None: |
| 1084 |
self._max = FixedPoint(str(max_val), 20) |
| 1085 |
else: |
| 1086 |
self._max = None |
| 1087 |
|
| 1088 |
def SetRange(self, min_val: FixedPoint, max_val: FixedPoint) -> None: # noqa: N802 |
| 1089 |
"""Set the allowed range. |
| 1090 |
|
| 1091 |
Args: |
| 1092 |
min_val (FixedPoint): The minimum value for :class:`FloatSpin`. If |
| 1093 |
it is ``None`` it is ignored. |
| 1094 |
max_val: The maximum value for :class:`FloatSpin`. If it is `None` |
| 1095 |
it is ignored. |
| 1096 |
|
| 1097 |
:note: |
| 1098 |
This method doesn't modify the current value. |
| 1099 |
|
| 1100 |
:note: |
| 1101 |
You specify open ranges like this (you can equally do this in the |
| 1102 |
constructor):: |
| 1103 |
|
| 1104 |
SetRange(min_val=1, max_val=None) |
| 1105 |
SetRange(min_val=None, max_val=0) |
| 1106 |
|
| 1107 |
|
| 1108 |
or no range:: |
| 1109 |
|
| 1110 |
SetRange(min_val=None, max_val=None) |
| 1111 |
""" |
| 1112 |
self.SetRangeDontClampValue(min_val, max_val) |
| 1113 |
|
| 1114 |
value = self.ClampValue(self._value) |
| 1115 |
if value != self._value: |
| 1116 |
self.SetValue(value) |
| 1117 |
|
| 1118 |
def ClampValue(self, var: FixedPoint) -> FixedPoint: # noqa: N802 |
| 1119 |
"""Clamp var between _min and _max depending on the range has been specified. |
| 1120 |
|
| 1121 |
Args: |
| 1122 |
var (FixedPoint): The value to be clamped. |
| 1123 |
|
| 1124 |
Returns: |
| 1125 |
FixedPoint: A clamped copy of `var`. |
| 1126 |
""" |
| 1127 |
if self._min is not None and float(var) < float(self._min): |
| 1128 |
return self._min |
| 1129 |
|
| 1130 |
if self._max is not None and float(var) > float(self._max): |
| 1131 |
var = self._max |
| 1132 |
|
| 1133 |
return var |
| 1134 |
|
| 1135 |
def SetIncrement(self, increment: FixedPoint) -> None: # noqa: N802 |
| 1136 |
"""Set the increment for every ``EVT_FLOATSPIN`` event. |
| 1137 |
|
| 1138 |
Args: |
| 1139 |
increment: A floating point number specifying the :class:`FloatSpin` |
| 1140 |
increment. |
| 1141 |
|
| 1142 |
Raises: |
| 1143 |
Exception: If `increment` is less than 1 / (10 ** digits) or |
| 1144 |
if `increment` is not a valid :class:`FixedPoint` number. |
| 1145 |
""" |
| 1146 |
if increment < 1.0 / (10.0**self._digits): |
| 1147 |
raise Exception( |
| 1148 |
"\nERROR: Increment Should Be Greater Or Equal To 1 / (10 ** digits)." |
| 1149 |
) |
| 1150 |
|
| 1151 |
self._increment = FixedPoint(str(increment), 20) |
| 1152 |
self.SetValue(self._value) |
| 1153 |
|
| 1154 |
def GetIncrement(self) -> FixedPoint: # noqa: N802 |
| 1155 |
"""Return the increment for every ``EVT_FLOATSPIN`` event. |
| 1156 |
|
| 1157 |
Returns: |
| 1158 |
FixedPoint: The increment for every ``EVT_FLOATSPIN`` event. |
| 1159 |
""" |
| 1160 |
return self._increment |
| 1161 |
|
| 1162 |
def SetDigits(self, digits: int = -1) -> None: # noqa: N802 |
| 1163 |
"""Set the number of digits to show. |
| 1164 |
|
| 1165 |
Args: |
| 1166 |
digits (int): The number of digits to show. If `digits` < 0, |
| 1167 |
:class:`FloatSpin` tries to calculate the best number of digits |
| 1168 |
based on input values passed in the constructor. |
| 1169 |
""" |
| 1170 |
if digits < 0: |
| 1171 |
incr = str(self._increment) |
| 1172 |
digits = 0 if incr.find(".") < 0 else len(incr[incr.find(".") + 1 :]) |
| 1173 |
|
| 1174 |
self._digits = digits |
| 1175 |
self.SetValue(self._value) |
| 1176 |
|
| 1177 |
def GetDigits(self) -> int: # noqa: N802 |
| 1178 |
"""Return the number of digits shown. |
| 1179 |
|
| 1180 |
Returns: |
| 1181 |
int: The number of digits shown by :class:`FloatSpin`. |
| 1182 |
""" |
| 1183 |
return self._digits |
| 1184 |
|
| 1185 |
def SetFormat(self, fmt: str = "%f") -> None: # noqa: N802 |
| 1186 |
"""Set the string format to use. |
| 1187 |
|
| 1188 |
Args: |
| 1189 |
fmt (str): The new string format to use. One of the following |
| 1190 |
strings: |
| 1191 |
|
| 1192 |
====== ================================= |
| 1193 |
Format Description |
| 1194 |
====== ================================= |
| 1195 |
'e' Floating point exponential format (lowercase) |
| 1196 |
'E' Floating point exponential format (uppercase) |
| 1197 |
'f' Floating point decimal format |
| 1198 |
'F' Floating point decimal format |
| 1199 |
'g' Floating point format. Uses lowercase exponential format |
| 1200 |
if exponent is less than -4 or not less than precision, |
| 1201 |
decimal format otherwise |
| 1202 |
'G' Floating point format. Uses uppercase exponential format |
| 1203 |
if exponent is less than -4 or not less than precision, |
| 1204 |
decimal format otherwise |
| 1205 |
====== ================================= |
| 1206 |
""" # noqa: E501 |
| 1207 |
if fmt not in ["%f", "%g", "%e", "%E", "%F", "%G"]: |
| 1208 |
raise Exception( |
| 1209 |
f"\nERROR: Bad Float Number Format: {fmt!r}. It Should Be " |
| 1210 |
'One Of "%f", "%g", "%e", "%E", "%F", "%G"' |
| 1211 |
) |
| 1212 |
|
| 1213 |
self._textformat = fmt |
| 1214 |
|
| 1215 |
if self._digits < 0: |
| 1216 |
self.SetDigits() |
| 1217 |
else: |
| 1218 |
self.SetValue(self._value) |
| 1219 |
|
| 1220 |
def GetFormat(self) -> str: # noqa: N802 |
| 1221 |
"""Return the string format in use. |
| 1222 |
|
| 1223 |
:see: :meth:`~FloatSpin.SetFormat` for a list of valid string formats. |
| 1224 |
""" |
| 1225 |
return self._textformat |
| 1226 |
|
| 1227 |
def SetDefaultValue(self, defaultvalue: float) -> None: # noqa: N802 |
| 1228 |
"""Set the :class:`FloatSpin` default value. |
| 1229 |
|
| 1230 |
Args: |
| 1231 |
defaultvalue (float): A floating point value representing the new |
| 1232 |
default value for :class:`FloatSpin`. |
| 1233 |
""" |
| 1234 |
if self.InRange(defaultvalue): |
| 1235 |
self._defaultvalue = FixedPoint(str(defaultvalue), 20) |
| 1236 |
|
| 1237 |
def GetDefaultValue(self) -> None | FixedPoint: # noqa: N802 |
| 1238 |
"""Return the :class:`FloatSpin` default value. |
| 1239 |
|
| 1240 |
Returns: |
| 1241 |
None | FixedPoint: The default value or ``None`` if no default |
| 1242 |
value has been set. |
| 1243 |
""" |
| 1244 |
return self._defaultvalue |
| 1245 |
|
| 1246 |
def IsDefaultValue(self) -> bool: # noqa: N802 |
| 1247 |
"""Return whether the current value is the default value or not. |
| 1248 |
|
| 1249 |
Returns: |
| 1250 |
bool: ``True`` if the current value is the default value, ``False`` |
| 1251 |
otherwise. |
| 1252 |
""" |
| 1253 |
return self._value == self._defaultvalue |
| 1254 |
|
| 1255 |
def SetToDefaultValue(self) -> None: # noqa: N802 |
| 1256 |
"""Set :class:`FloatSpin` value to its default value.""" |
| 1257 |
self.SetValue(self._defaultvalue) |
| 1258 |
|
| 1259 |
def SetSnapToTicks(self, forceticks: bool = True) -> None: # noqa: N802 |
| 1260 |
"""Force the value to always be divisible by the increment. |
| 1261 |
|
| 1262 |
Initially `False`. |
| 1263 |
|
| 1264 |
:note: |
| 1265 |
This uses the default value as the basis, you will get strange results |
| 1266 |
for very large differences between the current value and default value |
| 1267 |
when the increment is very small. |
| 1268 |
|
| 1269 |
Args: |
| 1270 |
forceticks: True to force the snap to ticks option, False otherwise. |
| 1271 |
""" |
| 1272 |
if self._snapticks != forceticks: |
| 1273 |
self._snapticks = forceticks |
| 1274 |
self.SetValue(self._value) |
| 1275 |
|
| 1276 |
def GetSnapToTicks(self) -> bool: # noqa: N802 |
| 1277 |
"""Return whether the snap to ticks option is active or not. |
| 1278 |
|
| 1279 |
Returns: |
| 1280 |
bool: ``True`` if the snap to ticks option is active, ``False`` |
| 1281 |
otherwise. |
| 1282 |
""" |
| 1283 |
return self._snapticks |
| 1284 |
|
| 1285 |
def OnFocus(self, event: wx.FocusEvent) -> None: # noqa: N802 |
| 1286 |
"""Handle the ``wx.EVT_SET_FOCUS`` event for :class:`FloatSpin`. |
| 1287 |
|
| 1288 |
Args: |
| 1289 |
event (wx.FocusEvent): A :class:`FocusEvent` event to be processed. |
| 1290 |
""" |
| 1291 |
if self._textctrl: |
| 1292 |
self._textctrl.SetFocus() |
| 1293 |
|
| 1294 |
event.Skip() |
| 1295 |
|
| 1296 |
def SyncSpinToText(self, send_event: bool = True, force_valid: bool = True) -> None: # noqa: N802 |
| 1297 |
"""Synchronize the underlying :class:`TextCtrl` with :class:`SpinButton`. |
| 1298 |
|
| 1299 |
Args: |
| 1300 |
send_event (bool): ``True`` to send a ``EVT_FLOATSPIN`` event, |
| 1301 |
``False`` otherwise. |
| 1302 |
force_valid (bool): ``True`` to force a valid value (i.e. inside |
| 1303 |
the provided range), ``False`` otherwise. |
| 1304 |
""" |
| 1305 |
if not self._textctrl: |
| 1306 |
return |
| 1307 |
|
| 1308 |
curr = self._textctrl.GetValue() |
| 1309 |
curr = curr.strip() |
| 1310 |
decimal = locale.localeconv()["decimal_point"] |
| 1311 |
curr = curr.replace(decimal, ".") |
| 1312 |
curr = curr.replace(",", ".") |
| 1313 |
|
| 1314 |
if curr: |
| 1315 |
try: |
| 1316 |
# curro = float(curr) |
| 1317 |
curr = FixedPoint(curr, 20) |
| 1318 |
except Exception: |
| 1319 |
self.SetValue(self._value) |
| 1320 |
return |
| 1321 |
|
| 1322 |
if force_valid or not self.HasRange() or self.InRange(curr): |
| 1323 |
if force_valid and self.HasRange(): |
| 1324 |
curr = self.ClampValue(curr) |
| 1325 |
|
| 1326 |
if self._value != curr: |
| 1327 |
self.SetValue(curr) |
| 1328 |
|
| 1329 |
if send_event: |
| 1330 |
self.DoSendEvent() |
| 1331 |
|
| 1332 |
elif force_valid: |
| 1333 |
# textctrl is out of sync, discard and reset |
| 1334 |
self.SetValue(self.GetValue()) |
| 1335 |
|
| 1336 |
def SetFont(self, font: None | wx.Font = None) -> bool: # noqa: N802 |
| 1337 |
"""Set the underlying :class:`TextCtrl` font. |
| 1338 |
|
| 1339 |
Args: |
| 1340 |
font (None | wx.Font, optional): A valid instance of :class:`Font`. |
| 1341 |
|
| 1342 |
Returns: |
| 1343 |
bool: ``True`` if the font was set successfully, ``False`` |
| 1344 |
otherwise. |
| 1345 |
""" |
| 1346 |
if font is None: |
| 1347 |
font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) |
| 1348 |
|
| 1349 |
if not self._textctrl: |
| 1350 |
return False |
| 1351 |
|
| 1352 |
return self._textctrl.SetFont(font) |
| 1353 |
|
| 1354 |
def GetFont(self) -> wx.Font: # noqa: N802 |
| 1355 |
"""Return the underlying :class:`TextCtrl` font. |
| 1356 |
|
| 1357 |
Returns: |
| 1358 |
wx.Font: The font used by the underlying :class:`TextCtrl`. If no |
| 1359 |
:class:`TextCtrl` is present, the default font for the control |
| 1360 |
is returned. |
| 1361 |
""" |
| 1362 |
if not self._textctrl: |
| 1363 |
return self.GetFont() |
| 1364 |
|
| 1365 |
return self._textctrl.GetFont() |
| 1366 |
|
| 1367 |
def GetMin(self) -> None | FixedPoint: # noqa: N802 |
| 1368 |
"""Return the minimum value. |
| 1369 |
|
| 1370 |
It can be a number or ``None`` if no minimum is present. |
| 1371 |
|
| 1372 |
Returns: |
| 1373 |
None | FixedPoint: The minimum value or ``None`` if no minimum |
| 1374 |
is present. |
| 1375 |
""" |
| 1376 |
return self._min |
| 1377 |
|
| 1378 |
def GetMax(self) -> None | FixedPoint: # noqa: N802 |
| 1379 |
"""Return the maximum value. |
| 1380 |
|
| 1381 |
It can be a number or ``None`` if no minimum is present. |
| 1382 |
|
| 1383 |
Returns: |
| 1384 |
None | FixedPoint: The maximum value or ``None`` if no maximum |
| 1385 |
is present. |
| 1386 |
""" |
| 1387 |
return self._max |
| 1388 |
|
| 1389 |
def HasRange(self) -> bool: # noqa: N802 |
| 1390 |
"""Return whether range has been set or not. |
| 1391 |
|
| 1392 |
Returns: |
| 1393 |
bool: ``True`` if a range has been set, ``False`` otherwise. |
| 1394 |
""" |
| 1395 |
return (self._min is not None) or (self._max is not None) |
| 1396 |
|
| 1397 |
def InRange(self, value: float | FixedPoint) -> bool: # noqa: N802 |
| 1398 |
"""Return whether a value is inside the range. |
| 1399 |
|
| 1400 |
Args: |
| 1401 |
value (float | FixedPoint): The value to test. |
| 1402 |
|
| 1403 |
Returns: |
| 1404 |
bool: ``True`` if the value is inside the range, ``False`` |
| 1405 |
otherwise. |
| 1406 |
""" |
| 1407 |
if not self.HasRange(): |
| 1408 |
return True |
| 1409 |
if self._min is not None and float(value) < float(self._min): |
| 1410 |
return False |
| 1411 |
return self._max is None or float(value) <= float(self._max) |
| 1412 |
|
| 1413 |
def GetTextCtrl(self) -> wx.TextCtrl: # noqa: N802 |
| 1414 |
"""Return the underlying :class:`wx.TextCtrl`. |
| 1415 |
|
| 1416 |
Returns: |
| 1417 |
wx.TextCtrl: The underlying :class:`wx.TextCtrl` instance. |
| 1418 |
""" |
| 1419 |
return self._textctrl |
| 1420 |
|
| 1421 |
def IsFinite(self, value: float | FixedPoint) -> tuple[bool, None | FixedPoint]: # noqa: N802 |
| 1422 |
"""Try to determine if a value is finite or infinite/NaN. |
| 1423 |
|
| 1424 |
Args: |
| 1425 |
value: The value to test. |
| 1426 |
|
| 1427 |
Returns: |
| 1428 |
tuple (bool, None | FixedPoint): A tuple containing a boolean |
| 1429 |
indicating whether the value is finite or not, and a |
| 1430 |
`FixedPoint` instance representing the snapped value if finite, |
| 1431 |
or `None` if not finite. |
| 1432 |
""" |
| 1433 |
try: |
| 1434 |
snap_value = (value - self._defaultvalue) / self._increment |
| 1435 |
finite = True |
| 1436 |
except Exception: |
| 1437 |
finite = False |
| 1438 |
snap_value = None |
| 1439 |
|
| 1440 |
return finite, snap_value |
| 1441 |
|
| 1442 |
|
| 1443 |
if wx.VERSION >= (3,): |
| 1444 |
# Use wx.SpinCtrlDouble |
| 1445 |
EVT_FLOATSPIN = wx.EVT_SPINCTRLDOUBLE |
| 1446 |
|
| 1447 |
class FloatSpin(wx.SpinCtrlDouble): |
| 1448 |
"""A wx.SpinCtrlDouble supporting floating point values and a default.""" |
| 1449 |
|
| 1450 |
_spinwidth = 0 |
| 1451 |
|
| 1452 |
def __init__( |
| 1453 |
self, |
| 1454 |
parent: wx.Window, |
| 1455 |
id: int = wx.ID_ANY, # noqa: A002 |
| 1456 |
pos: wx.Point = wx.DefaultPosition, |
| 1457 |
size: tuple[int, int] = (95, -1), |
| 1458 |
style: int = wx.SP_ARROW_KEYS | wx.ALIGN_RIGHT, |
| 1459 |
value: None | str | float | FixedPoint = 0.0, |
| 1460 |
min_val: None | str | float | FixedPoint = None, |
| 1461 |
max_val: None | str | float | FixedPoint = None, |
| 1462 |
increment: float = 1.0, |
| 1463 |
digits: int = -1, |
| 1464 |
agw_style: int = FS_LEFT, |
| 1465 |
name: str = "FloatSpin", |
| 1466 |
) -> None: |
| 1467 |
if "gtk3" in wx.PlatformInfo: |
| 1468 |
if not FloatSpin._spinwidth: |
| 1469 |
spin = wx.SpinCtrl(parent, -1) |
| 1470 |
text = wx.TextCtrl(parent, -1) |
| 1471 |
FloatSpin._spinwidth = spin.Size[0] - text.Size[0] + 11 |
| 1472 |
spin.Destroy() |
| 1473 |
text.Destroy() |
| 1474 |
size = size[0] + FloatSpin._spinwidth, size[1] |
| 1475 |
|
| 1476 |
if agw_style & FS_RIGHT: |
| 1477 |
style = style | wx.TE_RIGHT |
| 1478 |
elif agw_style & FS_CENTRE: |
| 1479 |
style = style | wx.TE_CENTER |
| 1480 |
|
| 1481 |
if agw_style & FS_READONLY: |
| 1482 |
style = style | wx.TE_READONLY |
| 1483 |
|
| 1484 |
wx.SpinCtrlDouble.__init__( |
| 1485 |
self, |
| 1486 |
parent, |
| 1487 |
id, |
| 1488 |
str(value), |
| 1489 |
pos, |
| 1490 |
size, |
| 1491 |
style, |
| 1492 |
min_val or 0, |
| 1493 |
max_val or 100, |
| 1494 |
value, |
| 1495 |
increment, |
| 1496 |
name, |
| 1497 |
) |
| 1498 |
if digits > -1: |
| 1499 |
self.SetDigits(digits) |
| 1500 |
|
| 1501 |
|
| 1502 |
# Class FixedPoint, version 0.0.4. |
| 1503 |
# Released to the public domain 28-Mar-2001, |
| 1504 |
# by Tim Peters ([email protected]). |
| 1505 |
|
| 1506 |
# Provided as-is; use at your own risk; no warranty; no promises; enjoy! |
| 1507 |
|
| 1508 |
|
| 1509 |
# 28-Mar-01 ver 0.0,4 |
| 1510 |
# Use repr() instead of str() inside __str__, because str(long) changed |
| 1511 |
# since this was first written (used to produce trailing "L", doesn't |
| 1512 |
# now). |
| 1513 |
# |
| 1514 |
# 09-May-99 ver 0,0,3 |
| 1515 |
# Repaired __sub__(FixedPoint, string); was blowing up. |
| 1516 |
# Much more careful conversion of float (now best possible). |
| 1517 |
# Implemented exact % and divmod. |
| 1518 |
# |
| 1519 |
# 14-Oct-98 ver 0,0,2 |
| 1520 |
# Added int, long, frac. Beefed up docs. Removed DECIMAL_POINT |
| 1521 |
# and MINUS_SIGN globals to discourage bloating this class instead |
| 1522 |
# of writing formatting wrapper classes (or subclasses) |
| 1523 |
# |
| 1524 |
# 11-Oct-98 ver 0,0,1 |
| 1525 |
# posted to c.l.py |
| 1526 |
|
| 1527 |
__version__ = 0, 0, 4 |
| 1528 |
|
| 1529 |
# The default value for the number of decimal digits carried after the |
| 1530 |
# decimal point. This only has effect at compile-time. |
| 1531 |
DEFAULT_PRECISION = 2 |
| 1532 |
# The default value for the number of decimal digits carried after the decimal point. |
| 1533 |
# This only has effect at compile-time. |
| 1534 |
|
| 1535 |
|
| 1536 |
class FixedPoint: |
| 1537 |
"""Decimal arithmetic with a fixed number of digits after the decimal point. |
| 1538 |
|
| 1539 |
The number of digits before the decimal point is variable & unbounded. |
| 1540 |
|
| 1541 |
The precision is user-settable on a per-object basis when a FixedPoint |
| 1542 |
is constructed, and may vary across FixedPoint objects. The precision |
| 1543 |
may also be changed after construction via `FixedPoint.set_precision(p)`. |
| 1544 |
Note that if the precision of a FixedPoint is reduced via |
| 1545 |
:meth:`FixedPoint.set_precision() <FixedPoint.set_precision>`, |
| 1546 |
information may be lost to rounding. |
| 1547 |
|
| 1548 |
Example:: |
| 1549 |
|
| 1550 |
>>> x = FixedPoint("5.55") # precision defaults to 2 |
| 1551 |
>>> print x |
| 1552 |
5.55 |
| 1553 |
>>> x.set_precision(1) # round to one fraction digit |
| 1554 |
>>> print x |
| 1555 |
5.6 |
| 1556 |
>>> print FixedPoint("5.55", 1) # same thing setting to 1 in constructor |
| 1557 |
5.6 |
| 1558 |
>>> repr(x) # returns constructor string that reproduces object exactly |
| 1559 |
"FixedPoint('5.6', 1)" |
| 1560 |
>>> |
| 1561 |
|
| 1562 |
|
| 1563 |
When :class:`FixedPoint` objects of different precision are combined via + - * /, |
| 1564 |
the result is computed to the larger of the inputs' precisions, which also |
| 1565 |
becomes the precision of the resulting :class:`FixedPoint` object. Example:: |
| 1566 |
|
| 1567 |
>>> print FixedPoint("3.42") + FixedPoint("100.005", 3) |
| 1568 |
103.425 |
| 1569 |
>>> |
| 1570 |
|
| 1571 |
|
| 1572 |
When a :class:`FixedPoint` is combined with other numeric types (ints, floats, |
| 1573 |
strings representing a number) via + - * /, then similarly the computation |
| 1574 |
is carried out using -- and the result inherits -- the :class:`FixedPoint`'s |
| 1575 |
precision. Example:: |
| 1576 |
|
| 1577 |
>>> print FixedPoint(1) / 7 |
| 1578 |
0.14 |
| 1579 |
>>> print FixedPoint(1, 30) / 7 |
| 1580 |
0.142857142857142857142857142857 |
| 1581 |
>>> |
| 1582 |
|
| 1583 |
|
| 1584 |
The string produced by `str(x)` (implictly invoked by `print`) always |
| 1585 |
contains at least one digit before the decimal point, followed by a |
| 1586 |
decimal point, followed by exactly `x.get_precision()` digits. If `x` is |
| 1587 |
negative, `str(x)[0] == "-"`. |
| 1588 |
|
| 1589 |
The :class:`FixedPoint` constructor can be passed an int, long, string, float, |
| 1590 |
:class:`FixedPoint`, or any object convertible to a float via `float()` or to a |
| 1591 |
long via `long()`. Passing a precision is optional; if specified, the |
| 1592 |
precision must be a non-negative int. There is no inherent limit on |
| 1593 |
the size of the precision, but if very very large you'll probably run |
| 1594 |
out of memory. |
| 1595 |
|
| 1596 |
Note that conversion of floats to :class:`FixedPoint` can be surprising, and |
| 1597 |
should be avoided whenever possible. Conversion from string is exact |
| 1598 |
(up to final rounding to the requested precision), so is greatly |
| 1599 |
preferred. Example:: |
| 1600 |
|
| 1601 |
>>> print FixedPoint(1.1e30) |
| 1602 |
1099999999999999993725589651456.00 |
| 1603 |
>>> print FixedPoint("1.1e30") |
| 1604 |
1100000000000000000000000000000.00 |
| 1605 |
>>> |
| 1606 |
|
| 1607 |
Args: |
| 1608 |
value (None | str | float | complex | FixedPoint): The initial value. |
| 1609 |
precision (int): Must be an int >= 0, and defaults to |
| 1610 |
``DEFAULT_PRECISION``. |
| 1611 |
|
| 1612 |
Raises: |
| 1613 |
TypeError: If `value` is not convertible to a float or long, or if |
| 1614 |
`precision` is not convertible to an int. |
| 1615 |
ValueError: If `precision` is less than 0. |
| 1616 |
OverflowError: If the float value is too large to be represented |
| 1617 |
exactly as a :class:`FixedPoint`. |
| 1618 |
""" |
| 1619 |
|
| 1620 |
# the exact value is self.n / (10 ** self.p) |
| 1621 |
# self.n is a long; self.p is an int |
| 1622 |
|
| 1623 |
def __init__( |
| 1624 |
self, |
| 1625 |
value: None | str | float | FixedPoint = None, |
| 1626 |
precision: int = DEFAULT_PRECISION, |
| 1627 |
) -> None: |
| 1628 |
if value is None: |
| 1629 |
value = 0 |
| 1630 |
|
| 1631 |
self.n = self.p = 0 |
| 1632 |
self.set_precision(precision) |
| 1633 |
p = self.p |
| 1634 |
|
| 1635 |
if isinstance(value, str): |
| 1636 |
self._parse_str_value(value, p) |
| 1637 |
return |
| 1638 |
|
| 1639 |
if isinstance(value, int): |
| 1640 |
self.n = value * (10**p) |
| 1641 |
return |
| 1642 |
|
| 1643 |
if isinstance(value, FixedPoint): |
| 1644 |
temp = value.copy() |
| 1645 |
temp.set_precision(p) |
| 1646 |
self.n, self.p = temp.n, temp.p |
| 1647 |
return |
| 1648 |
|
| 1649 |
if isinstance(value, float): |
| 1650 |
self._parse_float_value(value, p) |
| 1651 |
return |
| 1652 |
|
| 1653 |
if isinstance(value, complex): |
| 1654 |
raise TypeError(f"can't convert complex to FixedPoint: {value!r}") |
| 1655 |
|
| 1656 |
# can we coerce to a float? |
| 1657 |
yes = 1 |
| 1658 |
try: |
| 1659 |
asfloat = float(value) |
| 1660 |
except Exception: |
| 1661 |
yes = 0 |
| 1662 |
if yes: |
| 1663 |
self.__init__(asfloat, p) |
| 1664 |
return |
| 1665 |
|
| 1666 |
# similarly for long |
| 1667 |
yes = 1 |
| 1668 |
try: |
| 1669 |
aslong = int(value) |
| 1670 |
except Exception: |
| 1671 |
yes = 0 |
| 1672 |
if yes: |
| 1673 |
self.__init__(aslong, p) |
| 1674 |
return |
| 1675 |
|
| 1676 |
raise TypeError(f"can't convert to FixedPoint: {value!r}") |
| 1677 |
|
| 1678 |
def _parse_str_value(self, value: str, p: int) -> None: |
| 1679 |
"""Parse a str value into the FixedPoint representation. |
| 1680 |
|
| 1681 |
Args: |
| 1682 |
value (str): The string representation of the number. |
| 1683 |
p (int): The precision to use for the FixedPoint representation. |
| 1684 |
""" |
| 1685 |
n, exp = _string2exact(value) |
| 1686 |
# exact value is n * (10 ** exp) = n * (10 ** (exp+p)) / (10 ** p) |
| 1687 |
effective_exp = exp + p |
| 1688 |
if effective_exp > 0: |
| 1689 |
n = n * (10**effective_exp) |
| 1690 |
elif effective_exp < 0: |
| 1691 |
n = _roundquotient(n, (10 ** (-effective_exp))) |
| 1692 |
self.n = n |
| 1693 |
|
| 1694 |
def _parse_float_value(self, value: str, p: int) -> None: |
| 1695 |
"""Parse a float value into the FixedPoint representation. |
| 1696 |
|
| 1697 |
Args: |
| 1698 |
value (float): The float representation of the number. |
| 1699 |
p (int): The precision to use for the FixedPoint representation. |
| 1700 |
|
| 1701 |
Raises: |
| 1702 |
OverflowError: If the float value is too large to be represented |
| 1703 |
exactly as a :class:`FixedPoint`. |
| 1704 |
""" |
| 1705 |
# XXX ignoring infinities and NaNs and overflows for now |
| 1706 |
import math |
| 1707 |
|
| 1708 |
f, e = math.frexp(abs(value)) |
| 1709 |
if f != 0 and not (0.5 <= f < 1.0): |
| 1710 |
raise OverflowError(f"FixedPoint can't represent {value!r} exactly.") |
| 1711 |
# |value| = f * 2 ** e exactly |
| 1712 |
|
| 1713 |
# Suck up chunk bits at a time; 28 is enough so that we suck |
| 1714 |
# up all bits in 2 iterations for all known binary double- |
| 1715 |
# precision formats, and small enough to fit in an int. |
| 1716 |
chunk = 28 |
| 1717 |
top = 0 |
| 1718 |
# invariant: |value| = (top + f) * 2 ** e exactly |
| 1719 |
while f: |
| 1720 |
f = math.ldexp(f, chunk) |
| 1721 |
digit = int(f) |
| 1722 |
if digit >> chunk != 0: |
| 1723 |
raise OverflowError(f"FixedPoint can't represent {value!r} exactly.") |
| 1724 |
top = (top << chunk) | digit |
| 1725 |
f = f - digit |
| 1726 |
if not (0.0 <= f < 1.0): |
| 1727 |
raise OverflowError(f"FixedPoint can't represent {value!r} exactly.") |
| 1728 |
e = e - chunk |
| 1729 |
|
| 1730 |
# now |value| = top * 2 ** e exactly |
| 1731 |
# want n such that n / 10 ** p = top * 2 ** e, or |
| 1732 |
# n = top * 10 ** p * 2 ** e |
| 1733 |
top = top * (10**p) |
| 1734 |
n = top << e if e >= 0 else _roundquotient(top, 1 << -e) |
| 1735 |
if value < 0: |
| 1736 |
n = -n |
| 1737 |
self.n = n |
| 1738 |
|
| 1739 |
def get_precision(self) -> int: |
| 1740 |
"""Return the precision of this :class:`FixedPoint`. |
| 1741 |
|
| 1742 |
Note: |
| 1743 |
The precision is the number of decimal digits carried after the |
| 1744 |
decimal point, and is an int >= 0. |
| 1745 |
|
| 1746 |
Returns: |
| 1747 |
int: The precision of this :class:`FixedPoint`. |
| 1748 |
""" |
| 1749 |
return self.p |
| 1750 |
|
| 1751 |
def set_precision(self, precision: int = DEFAULT_PRECISION) -> None: |
| 1752 |
"""Change the precision carried by this :class:`FixedPoint` to `precision`. |
| 1753 |
|
| 1754 |
Note: |
| 1755 |
If `precision` is less than this :class:`FixedPoint`'s current |
| 1756 |
precision, information may be lost to rounding. |
| 1757 |
|
| 1758 |
Args: |
| 1759 |
precision (int, optional): must be an int >= 0, and defaults to |
| 1760 |
``DEFAULT_PRECISION``. |
| 1761 |
|
| 1762 |
""" |
| 1763 |
try: |
| 1764 |
p = int(precision) |
| 1765 |
except Exception as e: |
| 1766 |
raise TypeError(f"precision not convertable to int: {precision!r}") from e |
| 1767 |
if p < 0: |
| 1768 |
raise ValueError(f"precision must be >= 0: {precision!r}") |
| 1769 |
|
| 1770 |
if p > self.p: |
| 1771 |
self.n = self.n * (10 ** (p - self.p)) |
| 1772 |
elif p < self.p: |
| 1773 |
self.n = _roundquotient(self.n, (10 ** (self.p - p))) |
| 1774 |
self.p = p |
| 1775 |
|
| 1776 |
def __str__(self) -> str: |
| 1777 |
"""Return the string representation of this :class:`FixedPoint`. |
| 1778 |
|
| 1779 |
Returns: |
| 1780 |
str: The string representation of this :class:`FixedPoint`. |
| 1781 |
""" |
| 1782 |
n, p = self.n, self.p |
| 1783 |
i, f = divmod(abs(n), (10**p)) |
| 1784 |
if p: |
| 1785 |
frac = repr(f)[:-1] |
| 1786 |
frac = "0" * (p - len(frac)) + frac |
| 1787 |
else: |
| 1788 |
frac = "" |
| 1789 |
return "-"[: n < 0] + repr(i)[:-1] + "." + frac |
| 1790 |
|
| 1791 |
def __repr__(self) -> str: |
| 1792 |
"""Return the string representation of this :class:`FixedPoint`. |
| 1793 |
|
| 1794 |
Returns: |
| 1795 |
str: The string representation of this :class:`FixedPoint`. |
| 1796 |
""" |
| 1797 |
return f"FixedPoint{(str(self), self.p)!r}" |
| 1798 |
|
| 1799 |
def copy(self) -> FixedPoint: |
| 1800 |
"""Create a copy of the current :class:`FixedPoint`. |
| 1801 |
|
| 1802 |
Returns: |
| 1803 |
FixedPoint: A copy of the current :class:`FixedPoint`. |
| 1804 |
""" |
| 1805 |
return _make_fixed_point(self.n, self.p) |
| 1806 |
|
| 1807 |
__copy__ = __deepcopy__ = copy |
| 1808 |
|
| 1809 |
def __cmp__(self, other: str | float | FixedPoint) -> int: |
| 1810 |
"""Compare this :class:`FixedPoint` with `other`. |
| 1811 |
|
| 1812 |
Args: |
| 1813 |
other (str | float | FixedPoint): The other number to compare with. |
| 1814 |
|
| 1815 |
Returns: |
| 1816 |
int: -1 if this :class:`FixedPoint` is less than `other`, 0 if they are |
| 1817 |
equal, 1 if this :class:`FixedPoint` is greater than `other`. |
| 1818 |
""" |
| 1819 |
if other is None: |
| 1820 |
return 1 |
| 1821 |
xn, yn, p = _norm(self, other) |
| 1822 |
return cmp(xn, yn) |
| 1823 |
|
| 1824 |
def __hash__(self) -> int: |
| 1825 |
"""Return the hash of this :class:`FixedPoint`. |
| 1826 |
|
| 1827 |
Returns: |
| 1828 |
int: The hash of this :class:`FixedPoint`. |
| 1829 |
""" |
| 1830 |
# caution! == values must have equal hashes, and a FixedPoint |
| 1831 |
# is essentially a rational in unnormalized form. There's |
| 1832 |
# really no choice here but to normalize it, so hash is |
| 1833 |
# potentially expensive. |
| 1834 |
n, p = self.__reduce() |
| 1835 |
|
| 1836 |
# Obscurity: if the value is an exact integer, p will be 0 now, |
| 1837 |
# so the hash expression reduces to hash(n). So FixedPoints |
| 1838 |
# that happen to be exact integers hash to the same things as |
| 1839 |
# their int or long equivalents. This is Good. But if a |
| 1840 |
# FixedPoint happens to have a value exactly representable as |
| 1841 |
# a float, their hashes may differ. This is a teensy bit Bad. |
| 1842 |
return hash(n) ^ hash(p) |
| 1843 |
|
| 1844 |
def __bool__(self) -> bool: |
| 1845 |
"""Return whether this :class:`FixedPoint` is non-zero. |
| 1846 |
|
| 1847 |
Returns: |
| 1848 |
bool: ``True`` if this :class:`FixedPoint` is non-zero, ``False`` otherwise. |
| 1849 |
""" |
| 1850 |
return self.n != 0 |
| 1851 |
|
| 1852 |
def __neg__(self) -> FixedPoint: |
| 1853 |
"""Return the negation of this :class:`FixedPoint`. |
| 1854 |
|
| 1855 |
Returns: |
| 1856 |
FixedPoint: The negation of this :class:`FixedPoint`. |
| 1857 |
""" |
| 1858 |
return _make_fixed_point(-self.n, self.p) |
| 1859 |
|
| 1860 |
def __abs__(self) -> FixedPoint: |
| 1861 |
"""Return the absolute value of this :class:`FixedPoint`. |
| 1862 |
|
| 1863 |
Returns: |
| 1864 |
FixedPoint: The absolute value of this :class:`FixedPoint`. |
| 1865 |
""" |
| 1866 |
if self.n >= 0: |
| 1867 |
return self.copy() |
| 1868 |
return -self |
| 1869 |
|
| 1870 |
def __add__(self, other: str | float | FixedPoint) -> FixedPoint: |
| 1871 |
"""Return the addition of this :class:`FixedPoint` and `other`. |
| 1872 |
|
| 1873 |
Args: |
| 1874 |
other (str | float | FixedPoint): The other number to add with. |
| 1875 |
|
| 1876 |
Returns: |
| 1877 |
FixedPoint: The addition of this :class:`FixedPoint`. |
| 1878 |
""" |
| 1879 |
n1, n2, p = _norm(self, other) |
| 1880 |
# n1/10 ** p + n2 / 10 ** p = (n1+n2) / 10 ** p |
| 1881 |
return _make_fixed_point(n1 + n2, p) |
| 1882 |
|
| 1883 |
__radd__ = __add__ |
| 1884 |
"""Return the addition of this :class:`FixedPoint` and `other`.""" |
| 1885 |
|
| 1886 |
def __sub__(self, other: str | float | FixedPoint) -> FixedPoint: |
| 1887 |
"""Return the subtraction of this :class:`FixedPoint` and `other`. |
| 1888 |
|
| 1889 |
Args: |
| 1890 |
other (str | float | FixedPoint): The other number to subtract with. |
| 1891 |
|
| 1892 |
Returns: |
| 1893 |
FixedPoint: The subtraction of this :class:`FixedPoint`. |
| 1894 |
""" |
| 1895 |
if not isinstance(other, FixedPoint): |
| 1896 |
other = FixedPoint(other, self.p) |
| 1897 |
return self.__add__(-other) |
| 1898 |
|
| 1899 |
def __rsub__(self, other: str | float | FixedPoint) -> FixedPoint: |
| 1900 |
"""Return the subtraction of this :class:`FixedPoint` and `other`. |
| 1901 |
|
| 1902 |
Args: |
| 1903 |
other (str | float | FixedPoint): The other number to subtract with. |
| 1904 |
|
| 1905 |
Returns: |
| 1906 |
FixedPoint: The subtraction of this :class:`FixedPoint`. |
| 1907 |
""" |
| 1908 |
return (-self) + other |
| 1909 |
|
| 1910 |
def __mul__(self, other: str | float | FixedPoint) -> FixedPoint: |
| 1911 |
"""Return the multiplication of this :class:`FixedPoint` and `other`. |
| 1912 |
|
| 1913 |
Args: |
| 1914 |
other (str | float | FixedPoint): The other number to multiply with. |
| 1915 |
|
| 1916 |
Returns: |
| 1917 |
FixedPoint: The multiplication of this :class:`FixedPoint`. |
| 1918 |
""" |
| 1919 |
n1, n2, p = _norm(self, other) |
| 1920 |
# n1/10 ** p * n2 / 10 ** p = (n1 * n2 / 10 ** p) / 10 ** p |
| 1921 |
return _make_fixed_point(_roundquotient(n1 * n2, (10**p)), p) |
| 1922 |
|
| 1923 |
__rmul__ = __mul__ |
| 1924 |
|
| 1925 |
def __div__(self, other: str | float | FixedPoint) -> FixedPoint: |
| 1926 |
"""Return the division of this :class:`FixedPoint` and `other`. |
| 1927 |
|
| 1928 |
Args: |
| 1929 |
other (str | float | FixedPoint): The other number to divide with. |
| 1930 |
|
| 1931 |
Returns: |
| 1932 |
FixedPoint: The division of this :class:`FixedPoint`. |
| 1933 |
""" |
| 1934 |
n1, n2, p = _norm(self, other) |
| 1935 |
if n2 == 0: |
| 1936 |
raise ZeroDivisionError("FixedPoint division") |
| 1937 |
if n2 < 0: |
| 1938 |
n1, n2 = -n1, -n2 |
| 1939 |
# n1 / 10 ** p / (n2 / 10 ** p) = n1/n2 = (n1 * 10 ** p / n2) / 10 ** p |
| 1940 |
return _make_fixed_point(_roundquotient(n1 * (10**p), n2), p) |
| 1941 |
|
| 1942 |
def __rdiv__(self, other: str | float | FixedPoint) -> FixedPoint: |
| 1943 |
"""Return the division of this :class:`FixedPoint` and `other`. |
| 1944 |
|
| 1945 |
Args: |
| 1946 |
other (str | float | FixedPoint): The other number to divide with. |
| 1947 |
|
| 1948 |
Returns: |
| 1949 |
FixedPoint: The division of this :class:`FixedPoint`. |
| 1950 |
""" |
| 1951 |
_, n2, p = _norm(self, other) |
| 1952 |
return _make_fixed_point(n2, p) / self |
| 1953 |
|
| 1954 |
def __divmod__(self, other: str | float | FixedPoint) -> tuple[int, FixedPoint]: |
| 1955 |
"""Return the quotient and remainder of this :class:`FixedPoint` and `other`. |
| 1956 |
|
| 1957 |
Args: |
| 1958 |
other (FixedPoint): The other number to divide with. |
| 1959 |
|
| 1960 |
Returns: |
| 1961 |
tuple[int, FixedPoint]: The quotient and remainder of this |
| 1962 |
:class:`FixedPoint`. |
| 1963 |
""" |
| 1964 |
n1, n2, p = _norm(self, other) |
| 1965 |
if n2 == 0: |
| 1966 |
raise ZeroDivisionError("FixedPoint modulo") |
| 1967 |
# floor((n1 / 10 ** p) / (n2 * 10 ** p)) = floor(n1/n2) |
| 1968 |
q = n1 / n2 |
| 1969 |
# n1/10 ** p - q * n2 / 10 ** p = (n1 - q * n2) / 10 ** p |
| 1970 |
return q, _make_fixed_point(n1 - q * n2, p) |
| 1971 |
|
| 1972 |
def __rdivmod__(self, other: float | FixedPoint) -> tuple[int, FixedPoint]: |
| 1973 |
"""Return the quotient and remainder of this :class:`FixedPoint` and `other`. |
| 1974 |
|
| 1975 |
Args: |
| 1976 |
other (str | float | FixedPoint): The other number to divide with. |
| 1977 |
|
| 1978 |
Returns: |
| 1979 |
tuple[int, FixedPoint]: The quotient and remainder of this |
| 1980 |
:class:`FixedPoint`. |
| 1981 |
""" |
| 1982 |
_, n2, p = _norm(self, other) |
| 1983 |
return divmod(_make_fixed_point(n2, p), self) |
| 1984 |
|
| 1985 |
def __mod__(self, other: float | FixedPoint) -> FixedPoint: |
| 1986 |
"""Return the modulo of this :class:`FixedPoint` and `other`. |
| 1987 |
|
| 1988 |
Args: |
| 1989 |
other (float | FixedPoint): The other number to modulo with. |
| 1990 |
|
| 1991 |
Returns: |
| 1992 |
FixedPoint: The modulo of this :class:`FixedPoint`. |
| 1993 |
""" |
| 1994 |
return self.__divmod__(other)[1] |
| 1995 |
|
| 1996 |
def __rmod__(self, other: str | float | FixedPoint) -> FixedPoint: |
| 1997 |
"""Return the modulo of this :class:`FixedPoint` and `other`. |
| 1998 |
|
| 1999 |
Args: |
| 2000 |
other (str | float | FixedPoint): The other number to modulo with. |
| 2001 |
|
| 2002 |
Returns: |
| 2003 |
FixedPoint: The modulo of this :class:`FixedPoint`. |
| 2004 |
""" |
| 2005 |
_, n2, p = _norm(self, other) |
| 2006 |
return _make_fixed_point(n2, p).__mod__(self) |
| 2007 |
|
| 2008 |
def __float__(self) -> float: |
| 2009 |
"""Return the float portion of this :class:`FixedPoint`. |
| 2010 |
|
| 2011 |
Returns: |
| 2012 |
float: The float portion of this :class:`FixedPoint`. |
| 2013 |
""" |
| 2014 |
# caution! float can lose precision |
| 2015 |
n, p = self.__reduce() |
| 2016 |
return float(n) / float(10**p) |
| 2017 |
|
| 2018 |
def __long__(self) -> int: |
| 2019 |
"""Return the long portion of this :class:`FixedPoint`. |
| 2020 |
|
| 2021 |
Returns: |
| 2022 |
int: The long portion of this :class:`FixedPoint. |
| 2023 |
""" |
| 2024 |
# XXX should this round instead? |
| 2025 |
# XXX note e.g. long(-1.9) == -1L and long(1.9) == 1L in Python |
| 2026 |
# XXX note that __int__ inherits whatever __long__ does, |
| 2027 |
# XXX and .frac() is affected too |
| 2028 |
answer = abs(self.n) / (10**self.p) |
| 2029 |
if self.n < 0: |
| 2030 |
answer = -answer |
| 2031 |
return answer |
| 2032 |
|
| 2033 |
def __int__(self) -> int: |
| 2034 |
"""Return the integer portion of this :class:`FixedPoint`. |
| 2035 |
|
| 2036 |
Returns: |
| 2037 |
int: The integer portion of this :class:`FixedPoint`. |
| 2038 |
""" |
| 2039 |
return int(self.__long__()) |
| 2040 |
|
| 2041 |
def frac(self) -> FixedPoint: |
| 2042 |
"""Return fractional portion as a :class:`FixedPoint`. |
| 2043 |
|
| 2044 |
Note: |
| 2045 |
In :class:`FixedPoint`, this equality holds true:: |
| 2046 |
|
| 2047 |
x = x.frac() + long(x) |
| 2048 |
|
| 2049 |
Returns: |
| 2050 |
FixedPoint: The fractional portion of this :class:`FixedPoint`. |
| 2051 |
""" |
| 2052 |
return self - int(self) |
| 2053 |
|
| 2054 |
def __reduce(self) -> tuple[int, int]: |
| 2055 |
"""Return numerator and precision. |
| 2056 |
|
| 2057 |
Returns: |
| 2058 |
tuple[int, int]: A tuple containing the numerator and precision. |
| 2059 |
""" |
| 2060 |
n, p = self.n, self.p |
| 2061 |
if n == 0: |
| 2062 |
p = 0 |
| 2063 |
while p and n % 10 == 0: |
| 2064 |
p = p - 1 |
| 2065 |
n = n / 10 |
| 2066 |
return n, p |
| 2067 |
|
| 2068 |
|
| 2069 |
def _norm(x: FixedPoint, y: str | float | FixedPoint) -> tuple[int, int, int]: |
| 2070 |
"""Normalize x and y to the same precision. |
| 2071 |
|
| 2072 |
Note that this is called a lot, so default-arg tricks are helpful. |
| 2073 |
|
| 2074 |
|
| 2075 |
Args: |
| 2076 |
x (FixedPoint): The first FixedPoint to normalize. |
| 2077 |
y (float | str | FixedPoint): The second FixedPoint or number to |
| 2078 |
normalize with. |
| 2079 |
|
| 2080 |
Returns: |
| 2081 |
tuple[int, int, int]: A tuple containing the normalized numerator of |
| 2082 |
`x`, the normalized numerator of `y`, and the common precision. |
| 2083 |
""" |
| 2084 |
if not isinstance(x, FixedPoint): |
| 2085 |
raise TypeError(f"first arg must be a FixedPoint: {x!r}") |
| 2086 |
if not isinstance(y, FixedPoint): |
| 2087 |
y = FixedPoint(y, x.p) |
| 2088 |
xn, yn = x.n, y.n |
| 2089 |
xp, yp = x.p, y.p |
| 2090 |
if xp > yp: |
| 2091 |
yn = yn * (10 ** (xp - yp)) |
| 2092 |
p = xp |
| 2093 |
elif xp < yp: |
| 2094 |
xn = xn * (10 ** (yp - xp)) |
| 2095 |
p = yp |
| 2096 |
else: |
| 2097 |
p = xp # same as yp |
| 2098 |
return xn, yn, p |
| 2099 |
|
| 2100 |
|
| 2101 |
def _make_fixed_point(n: int, p: int) -> FixedPoint: |
| 2102 |
"""Return a new :class:`FixedPoint` with the same value as `n` and `p`. |
| 2103 |
|
| 2104 |
Args: |
| 2105 |
n (int): The numerator. |
| 2106 |
p (int): The precision. |
| 2107 |
|
| 2108 |
Returns: |
| 2109 |
FixedPoint: A new :class:`FixedPoint` with the same value as `n` and `p`. |
| 2110 |
""" |
| 2111 |
f = FixedPoint() |
| 2112 |
f.n = n |
| 2113 |
f.p = p |
| 2114 |
return f |
| 2115 |
|
| 2116 |
|
| 2117 |
# divide x by y, rounding to int via nearest-even |
| 2118 |
# y must be > 0 |
| 2119 |
# XXX which rounding modes are useful? |
| 2120 |
|
| 2121 |
|
| 2122 |
def cmp(a: int, b: int) -> int: |
| 2123 |
"""Reimplemented Python 2.x cmp function. |
| 2124 |
|
| 2125 |
Args: |
| 2126 |
a (int | float): A number. |
| 2127 |
b (int | float): A number. |
| 2128 |
|
| 2129 |
Return: |
| 2130 |
int: -1 or 1. |
| 2131 |
""" |
| 2132 |
return (a > b) - (a < b) |
| 2133 |
|
| 2134 |
|
| 2135 |
def _roundquotient(x: int, y: int) -> int: |
| 2136 |
"""Divide x by y, rounding to int via nearest-even. |
| 2137 |
|
| 2138 |
Args: |
| 2139 |
x (int): The numerator. |
| 2140 |
y (int): The denominator, must be > 0. |
| 2141 |
|
| 2142 |
Returns: |
| 2143 |
int: The rounded quotient of x and y. |
| 2144 |
""" |
| 2145 |
if y <= 0: |
| 2146 |
raise ValueError("y must be > 0") |
| 2147 |
n, leftover = divmod(x, y) |
| 2148 |
c = cmp(leftover << 1, y) |
| 2149 |
# c < 0 <-> leftover < y/2, etc |
| 2150 |
if c > 0 or (c == 0 and (n & 1) == 1): |
| 2151 |
n = n + 1 |
| 2152 |
return n |
| 2153 |
|
| 2154 |
|
| 2155 |
# crud for parsing strings |
| 2156 |
|
| 2157 |
# There's an optional sign at the start, and an optional exponent |
| 2158 |
# at the end. The exponent has an optional sign and at least one |
| 2159 |
# digit. In between, must have either at least one digit followed |
| 2160 |
# by an optional fraction, or a decimal point followed by at least |
| 2161 |
# one digit. Yuck. |
| 2162 |
|
| 2163 |
_parser = re.compile( |
| 2164 |
r""" |
| 2165 |
\s* |
| 2166 |
(?P<sign>[-+])? |
| 2167 |
( |
| 2168 |
(?P<int>\d+) (\. (?P<frac>\d*))? |
| 2169 |
| |
| 2170 |
\. (?P<onlyfrac>\d+) |
| 2171 |
) |
| 2172 |
([eE](?P<exp>[-+]? \d+))? |
| 2173 |
\s* $ |
| 2174 |
""", |
| 2175 |
re.VERBOSE, |
| 2176 |
).match |
| 2177 |
|
| 2178 |
del re |
| 2179 |
|
| 2180 |
|
| 2181 |
def _string2exact(s: str) -> tuple[int, int]: |
| 2182 |
"""Convert a string to an exact integer and exponent. |
| 2183 |
|
| 2184 |
Args: |
| 2185 |
s (str): The string to convert. |
| 2186 |
|
| 2187 |
Returns: |
| 2188 |
tupel[int, int]: A tuple containing the integer part and the exponent. |
| 2189 |
""" |
| 2190 |
m = _parser(s) |
| 2191 |
if m is None: |
| 2192 |
raise ValueError(f"can't parse as number: {s!r}") |
| 2193 |
|
| 2194 |
exp = m.group("exp") |
| 2195 |
exp = 0 if exp is None else int(exp) |
| 2196 |
|
| 2197 |
intpart = m.group("int") |
| 2198 |
if intpart is None: |
| 2199 |
intpart = "0" |
| 2200 |
fracpart = m.group("onlyfrac") |
| 2201 |
else: |
| 2202 |
fracpart = m.group("frac") |
| 2203 |
if fracpart is None or fracpart == "": |
| 2204 |
fracpart = "0" |
| 2205 |
|
| 2206 |
if intpart is None: |
| 2207 |
raise ValueError("intpart should not be None!") |
| 2208 |
|
| 2209 |
if fracpart is None: |
| 2210 |
raise ValueError("fracpart should not be None!") |
| 2211 |
|
| 2212 |
i, f = int(intpart), int(fracpart) |
| 2213 |
nfrac = len(fracpart) |
| 2214 |
i = i * (10**nfrac) + f |
| 2215 |
exp = exp - nfrac |
| 2216 |
|
| 2217 |
if m.group("sign") == "-": |
| 2218 |
i = -i |
| 2219 |
|
| 2220 |
return i, exp |
| 2221 |
|
| 2222 |
|
| 2223 |
def get_all_keyboard_focusable_children(parent: wx.Control) -> list[wx.Control]: |
| 2224 |
"""Get all keyboard focusable children of parent. |
| 2225 |
|
| 2226 |
Args: |
| 2227 |
parent (wx.Control): The parent control to search for children. |
| 2228 |
|
| 2229 |
Returns: |
| 2230 |
list[wx.Control]: A list of all keyboard focusable children of the |
| 2231 |
parent. |
| 2232 |
""" |
| 2233 |
children = [] |
| 2234 |
try: |
| 2235 |
iter(parent.Children) |
| 2236 |
# Under Mac OS X panels may have non-iterator children |
| 2237 |
except Exception: |
| 2238 |
pass |
| 2239 |
else: |
| 2240 |
for child in parent.Children: |
| 2241 |
if child.Enabled and child.IsShownOnScreen(): |
| 2242 |
if child.AcceptsFocusFromKeyboard() and ( |
| 2243 |
not isinstance(child, wx.RadioButton) or child.Value |
| 2244 |
): |
| 2245 |
children.append(child) |
| 2246 |
if child.Children: |
| 2247 |
children.extend(get_all_keyboard_focusable_children(child)) |
| 2248 |
return children |
| 2249 |
|
| 2250 |
|
| 2251 |
def focus_next_keyboard_focusable_control(control: wx.Control) -> None: |
| 2252 |
"""Focus the next control in tab order that can gain focus. |
| 2253 |
|
| 2254 |
If the shift key is held down, tab order is reversed. |
| 2255 |
|
| 2256 |
Args: |
| 2257 |
control (wx.Control): The control to start from. |
| 2258 |
""" |
| 2259 |
# Find the last panel in the hierarchy of parents |
| 2260 |
parent = control.Parent |
| 2261 |
focusparent = None |
| 2262 |
while parent: |
| 2263 |
if isinstance(parent, (wx.Panel, wx.PyPanel)): |
| 2264 |
focusparent = parent |
| 2265 |
parent = parent.Parent |
| 2266 |
if not focusparent: |
| 2267 |
return |
| 2268 |
children = get_all_keyboard_focusable_children(focusparent) |
| 2269 |
if wx.GetKeyState(wx.WXK_SHIFT): |
| 2270 |
children = list(reversed(children)) |
| 2271 |
for i, child in enumerate(children): |
| 2272 |
if child is not control: |
| 2273 |
continue |
| 2274 |
for next_child in children[i + 1 :] + children[:i]: |
| 2275 |
if next_child is not child.Parent: |
| 2276 |
next_child.SetFocus() |
| 2277 |
break |
| 2278 |
break |