File: floatspin.py

package info (click to toggle)
displaycal-py3 3.9.16-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 29,120 kB
  • sloc: python: 115,777; javascript: 11,540; xml: 598; sh: 257; makefile: 173
file content (1918 lines) | stat: -rw-r--r-- 61,545 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
# --------------------------------------------------------------------------- #
# FLOATSPIN Control wxPython IMPLEMENTATION
# Python Code By:
#
# Andrea Gavana, @ 16 Nov 2005
# Latest Revision: 03 Jan 2014, 23.00 GMT
#
# Modifications for DisplayCAL:
# - Select text on focus
# - Always accept "," (comma) as decimal point
# - Only call SyncSpinToText if TextCtrl value has actually changed
# - Set value to min/max if not in range
# - Use a different method for tab traversal because the original code didn't
#   work under wxGTK
# - If CMD or CTRL are held, don't block keycodes that are not allowed (fixes
#   copy/paste/select all keyboard shortcuts not working)
# - Do default action if return key is pressed (currently only works if the
#   default item is a button)
# - Fix children not reflecting enabled state under wxMac
#
# TODO List/Caveats
#
# 1. Ay Idea?
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@gmail.com
# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------- #
"""
:class:`FloatSpin` implements a floating point :class:`SpinCtrl`.


Description
===========

:class:`FloatSpin` implements a floating point :class:`SpinCtrl`. It is built using a
custom :class:`PyControl`, composed by a :class:`TextCtrl` and a :class:`SpinButton`. In
order to correctly handle floating points numbers without rounding errors or non-exact
floating point representations, :class:`FloatSpin` uses the great :class:`FixedPoint`
class from Tim Peters.

What you can do:

- Set the number of representative digits for your floating point numbers;
- Set the floating point format (``%f``, ``%F``, ``%e``, ``%E``, ``%g``, ``%G``);
- Set the increment of every ``EVT_FLOATSPIN`` event;
- Set minimum, maximum values for :class:`FloatSpin` as well as its range;
- Change font and colour for the underline :class:`TextCtrl`.


Usage
=====

Usage example::

    import wx
    import wx.lib.agw.floatspin as FS

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init__(self, parent, -1, "FloatSpin Demo")

            panel = wx.Panel(self)

            floatspin = FS.FloatSpin(panel, -1, pos=(50, 50), min_val=0, max_val=1,
                                     increment=0.01, value=0.1, agwStyle=FS.FS_LEFT)
            floatspin.SetFormat("%f")
            floatspin.SetDigits(2)


    # our normal wxApp-derived class, as usual

    app = wx.App(0)

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()



Events
======

:class:`FloatSpin` catches 3 different types of events:

1) Spin events: events generated by spinning up/down the spinbutton;
2) Char events: playing with up/down arrows of the keyboard increase/decrease
   the value of :class:`FloatSpin`;
3) Mouse wheel event: using the wheel will change the value of :class:`FloatSpin`.

In addition, there are some other functionalities:

- It remembers the initial value as a default value, call meth:~FloatSpin.SetToDefaultValue`, or
  press ``Esc`` to return to it;
- ``Shift`` + arrow = 2 * increment        (or ``Shift`` + mouse wheel);
- ``Ctrl``  + arrow = 10 * increment       (or ``Ctrl`` + mouse wheel);
- ``Alt``   + arrow = 100 * increment      (or ``Alt`` + mouse wheel);
- Combinations of ``Shift``, ``Ctrl``, ``Alt`` increment the :class:`FloatSpin` value by the
  product of the factors;
- ``PgUp`` & ``PgDn`` = 10 * increment * the product of the ``Shift``, ``Ctrl``, ``Alt``
  factors;
- ``Space`` sets the control's value to it's last valid state.


Window Styles
=============

This class supports the following window styles:

=============== =========== ==================================================
Window Styles   Hex Value   Description
=============== =========== ==================================================
``FS_READONLY``         0x1 Sets :class:`FloatSpin` as read-only control.
``FS_LEFT``             0x2 Horizontally align the underlying :class:`TextCtrl` on the left.
``FS_CENTRE``           0x4 Horizontally align the underlying :class:`TextCtrl` on center.
``FS_RIGHT``            0x8 Horizontally align the underlying :class:`TextCtrl` on the right.
=============== =========== ==================================================


Events Processing
=================

This class processes the following events:

================= ==================================================
Event Name        Description
================= ==================================================
``EVT_FLOATSPIN`` Emitted when the user changes the value of :class:`FloatSpin`, either with the mouse or with the keyboard.
================= ==================================================


License And Version
===================

:class:`FloatSpin` control is distributed under the wxPython license.

Latest revision: Andrea Gavana @ 03 Jan 2014, 23.00 GMT

Version 0.9


Backward Incompatibilities
==========================

Modifications to allow `min_val` or `max_val` to be ``None`` done by:

James Bigler,
SCI Institute, University of Utah,
March 14, 2007

:note: Note that the changes I made will break backward compatibility,
 because I changed the contructor's parameters from `min` / `max` to
 `min_val` / `max_val` to be consistent with the other functions and to
 eliminate any potential confusion with the built in `min` and `max`
 functions.

You specify open ranges like this (you can equally do this in the
constructor)::

    SetRange(min_val=1, max_val=None)     # [1,  ]
    SetRange(min_val=None, max_val=0)     # [ , 0]

or no range::

    SetRange(min_val=None, max_val=None)  # [ , ]

"""


# ----------------------------------------------------------------------
# Beginning Of FLOATSPIN wxPython Code
# ----------------------------------------------------------------------

import re
import locale
from math import ceil, floor
import wx

# Set The Styles For The Underline wx.TextCtrl
FS_READONLY = 1
""" Sets :class:`FloatSpin` as read-only control. """
FS_LEFT = 2
""" Horizontally align the underlying :class:`TextCtrl` on the left. """
FS_CENTRE = 4
""" Horizontally align the underlying :class:`TextCtrl` on center. """
FS_RIGHT = 8
""" Horizontally align the underlying :class:`TextCtrl` on the right. """

# Define The FloatSpin Event
wxEVT_FLOATSPIN = wx.NewEventType()

# -----------------------------------#
#        FloatSpinEvent
# -----------------------------------#

EVT_FLOATSPIN = wx.PyEventBinder(wxEVT_FLOATSPIN, 1)
# Emitted when the user changes the value of :class:`FloatSpin`, either with the mouse
# or with the keyboard.

# ---------------------------------------------------------------------------- #
# Class FloatSpinEvent
# ---------------------------------------------------------------------------- #


class FloatSpinEvent(wx.PyCommandEvent):
    """This event will be sent when a ``EVT_FLOATSPIN`` event is mapped in the parent."""

    def __init__(self, eventType, eventId=1, nSel=-1, nOldSel=-1):
        """Default class constructor.

        :param eventType: the event type;
        :param eventId: the event identifier;
        :param nSel: the current selection;
        :param nOldSel: the old selection.
        """

        wx.PyCommandEvent.__init__(self, eventType, eventId)
        self._eventType = eventType

    def SetPosition(self, pos):
        """Sets event position.

        :param pos: an integer specyfing the event position.
        """

        self._position = pos

    def GetPosition(self):
        """Returns event position."""

        return self._position


# ----------------------------------------------------------------------------
# FloatTextCtrl
# ----------------------------------------------------------------------------


class FloatTextCtrl(wx.TextCtrl):
    """A class which holds a :class:`TextCtrl`, one of the two building blocks
    of :class:`FloatSpin`.
    """

    def __init__(
        self,
        parent,
        id=wx.ID_ANY,
        value="",
        pos=wx.DefaultPosition,
        size=wx.DefaultSize,
        style=wx.TE_NOHIDESEL | wx.TE_PROCESS_ENTER,
        validator=wx.DefaultValidator,
        name=wx.TextCtrlNameStr,
    ):
        """Default class constructor.
        Used internally. Do not call directly this class in your code!

        :param parent: the :class:`FloatTextCtrl` parent;
        :param id: an identifier for the control: a value of -1 is taken to mean a default;
        :param value: default text value;
        :param pos: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :param size: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :param style: the window style;
        :param validator: the window validator;
        :param name: the window name.

        """

        wx.TextCtrl.__init__(self, parent, id, value, pos, size, style, validator, name)

        self._parent = parent
        self._selection = (-1, -1)
        self._value = value
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wx.EVT_SET_FOCUS, self.OnFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)

    def OnDestroy(self, event):
        """Handle the ``wx.EVT_WINDOW_DESTROY`` event for :class:`FloatTextCtrl`.

        :param event: a :class:`WindowDestroyEvent` event to be processed.

        :note: This method tries to correctly handle the control destruction under MSW.
        """
        if self._parent:
            self._parent._textctrl = None
            self._parent = None
        return 0

    def OnKeyDown(self, event):
        """Handle the ``wx.EVT_KEYDOWN`` event for :class:`FloatTextCtrl`.

        :param event: a :class:`KeyEvent` event to be processed.
        """

        if self._parent:
            self._parent.OnKeyDown(event)

    def OnFocus(self, event):
        self._value = self.Value
        self.RestoreSelection()
        event.Skip()

    def OnKillFocus(self, event):
        """Handles the ``wx.EVT_KILL_FOCUS`` event for :class:`FloatTextCtrl`.

        :param event: a :class:`FocusEvent` event to be processed.

        :note: This method synchronizes the :class:`SpinButton` and the :class:`TextCtrl`
         when focus is lost.
        """

        self._selection = self.GetSelection()
        if self._parent and self.Value != self._value:
            self._parent.SyncSpinToText(True)
        self.SetSelection(0, 0)

        event.Skip()

    def RestoreSelection(self):
        """Restores the selection under Mac OS X, selects all under other platforms
        (consistent with default wx.TextCtrl behaviour)

        """

        if "__WXMAC__" in wx.PlatformInfo and self._selection != (-1, -1):
            self.SetSelection(*self._selection)
        else:
            self.SelectAll()


# ---------------------------------------------------------------------------- #
# FloatSpin
# This Is The Main Class Implementation
# ---------------------------------------------------------------------------- #


class FloatSpin(wx.PyControl):
    """:class:`FloatSpin` implements a floating point :class:`SpinCtrl`. It is built
    using a custom :class:`PyControl`, composed by a :class:`TextCtrl` and a
    :class:`SpinButton`. In order to correctly handle floating points numbers without
    rounding errors or non-exact floating point representations, :class:`FloatSpin` uses
    the great :class:`FixedPoint` class from Tim Peters.
    """

    _spinwidth = 0

    def __init__(
        self,
        parent,
        id=wx.ID_ANY,
        pos=wx.DefaultPosition,
        size=(130, -1),
        style=0,
        value=0.0,
        min_val=None,
        max_val=None,
        increment=1.0,
        digits=-1,
        agwStyle=FS_LEFT,
        name="FloatSpin",
    ):
        """Default class constructor.

        :param parent: the :class:`FloatSpin` parent;
        :param id: an identifier for the control: a value of -1 is taken to mean a
            default;
        :param pos: the control position. A value of (-1, -1) indicates a default
            position, chosen by either the windowing system or wxPython, depending on
            platform;
        :param size: the control size. A value of (-1, -1) indicates a default size,
            chosen by either the windowing system or wxPython, depending on platform;
        :param style: the window style;
        :param value: is the current value for :class:`FloatSpin`;
        :param min_val: the minimum value, ignored if ``None``;
        :param max_val: the maximum value, ignored if ``None``;
        :param increment: the increment for every :class:`FloatSpinEvent` event;
        :param digits: number of representative digits for your floating point numbers;
        :param agwStyle: one of the following bits:

         =============== =========== ==================================================
         Window Styles   Hex Value   Description
         =============== =========== ==================================================
         ``FS_READONLY``         0x1 Sets :class:`FloatSpin` as read-only control.
         ``FS_LEFT``             0x2 Horizontally align the underlying :class:`TextCtrl` on the left.
         ``FS_CENTRE``           0x4 Horizontally align the underlying :class:`TextCtrl` on center.
         ``FS_RIGHT``            0x8 Horizontally align the underlying :class:`TextCtrl` on the right.
         =============== =========== ==================================================

        :param name: the window name.

        """

        wx.PyControl.__init__(
            self,
            parent,
            id,
            pos,
            size,
            style | wx.NO_BORDER | wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN,
            wx.DefaultValidator,
            name,
        )

        # Don't call SetRange here, because it will try to modify
        # self._value whose value doesn't exist yet.
        self.SetRangeDontClampValue(min_val, max_val)
        self._value = self.ClampValue(FixedPoint(str(value), 20))
        self._defaultvalue = self._value
        self._increment = FixedPoint(str(increment), 20)
        self._spinmodifier = FixedPoint(str(1.0), 20)
        self._digits = digits
        self._snapticks = False
        self._spinbutton = None
        self._ignore_spin_event = False
        self._textctrl = None
        self._spinctrl_bestsize = wx.Size(-999, -999)
        self._enabled = True

        # start Philip Semanchuk addition
        # The textbox & spin button are drawn slightly differently
        # depending on the platform. The difference is most pronounced
        # under OS X.
        if "__WXMAC__" in wx.PlatformInfo:
            self._gap = 8
            self._spin_top = 3
            self._text_left = 4
            self._text_top = 4
        elif "__WXMSW__" in wx.PlatformInfo:
            self._gap = 1
            self._spin_top = 0
            self._text_left = 0
            self._text_top = 0
        else:
            # GTK
            if "gtk3" in wx.PlatformInfo:
                self._gap = 1
            else:
                self._gap = -1
            self._spin_top = 0
            self._text_left = 0
            self._text_top = 0
        # end Philip Semanchuk addition

        self.SetLabel(name)
        self.SetForegroundColour(parent.GetForegroundColour())

        width = size[0]
        height = size[1]
        best_size = self.DoGetBestSize()

        if width == -1:
            width = best_size.GetWidth()
        if height == -1:
            height = best_size.GetHeight()

        self._validkeycode = [43, 44, 45, 46, 69, 101]
        self._validkeycode.extend(list(range(48, 58)))
        self._validkeycode.extend(
            [
                wx.WXK_BACK,
                wx.WXK_DELETE,
                wx.WXK_LEFT,
                wx.WXK_RIGHT,
                wx.WXK_NUMPAD0,
                wx.WXK_NUMPAD1,
                wx.WXK_NUMPAD2,
                wx.WXK_NUMPAD3,
                wx.WXK_NUMPAD4,
                wx.WXK_NUMPAD5,
                wx.WXK_NUMPAD6,
                wx.WXK_NUMPAD7,
                wx.WXK_NUMPAD8,
                wx.WXK_NUMPAD9,
                wx.WXK_NUMPAD_ADD,
                wx.WXK_NUMPAD_DECIMAL,
                wx.WXK_NUMPAD_SEPARATOR,
                wx.WXK_NUMPAD_SUBTRACT,
            ]
        )

        self._spinbutton = wx.SpinButton(
            self,
            wx.ID_ANY,
            wx.DefaultPosition,
            size=(-1, height),
            style=wx.SP_ARROW_KEYS | wx.SP_VERTICAL | wx.SP_WRAP,
        )
        self._spinbutton.SetRange(-(2**32) / 2.0, 2**32 / 2.0 - 1)
        self._spinbutton.AcceptsFocusFromKeyboard = lambda: False
        if "gtk3" in wx.PlatformInfo:
            if not FloatSpin._spinwidth:
                spin = wx.SpinCtrl(self, -1)
                text = wx.TextCtrl(self, -1)
                FloatSpin._spinwidth = spin.Size[0] - text.Size[0] + 11
                spin.Destroy()
                text.Destroy()
            self._spinbutton.MaxSize = FloatSpin._spinwidth, height

        txtstyle = wx.TE_NOHIDESEL | wx.TE_PROCESS_ENTER

        if agwStyle & FS_RIGHT:
            txtstyle = txtstyle | wx.TE_RIGHT
        elif agwStyle & FS_CENTRE:
            txtstyle = txtstyle | wx.TE_CENTER

        if agwStyle & FS_READONLY:
            txtstyle = txtstyle | wx.TE_READONLY

        self._textctrl = FloatTextCtrl(
            self,
            wx.ID_ANY,
            "",
            wx.DefaultPosition,
            (width - self._spinbutton.GetSize().GetWidth(), height),
            txtstyle,
        )

        # start Philip Semanchuk addition
        # Setting the textctrl's size in the ctor also sets its min size.
        # But the textctrl is entirely controlled by the parent floatspin
        # control and should accept whatever size its parent dictates, so
        # here we tell it to forget its min size.
        self._textctrl.SetMinSize(wx.DefaultSize)
        # Setting the spin buttons's size in the ctor also sets its min size.
        # Under OS X that results in a rendering artifact because spin buttons
        # are a little shorter than textboxes.
        # Setting the min size to the default allows OS X to draw the spin
        # button correctly. However, Windows and KDE take the call to
        # SetMinSize() as a cue to size the spin button taller than the
        # textbox, so we avoid the call there.
        if "__WXMAC__" in wx.PlatformInfo:
            self._spinbutton.SetMinSize(wx.DefaultSize)
        # end Philip Semanchuk addition

        self._mainsizer = wx.BoxSizer(wx.HORIZONTAL)
        # Ensure the spin button is shown, and the text widget takes
        # all remaining free space
        self._mainsizer.Add(self._textctrl, 1)
        if "gtk3" in wx.PlatformInfo:
            self._mainsizer.Add((self._gap, 1), 0)
        self._mainsizer.Add(self._spinbutton, 0)
        self.SetSizer(self._mainsizer)
        self._mainsizer.Layout()

        self.SetFormat()

        if not (agwStyle & FS_READONLY):
            self.Bind(wx.EVT_SPIN_UP, self.OnSpinUp)
            self.Bind(wx.EVT_SPIN_DOWN, self.OnSpinDown)
            self._spinbutton.Bind(wx.EVT_LEFT_DOWN, self.OnSpinMouseDown)
            self._spinbutton.Bind(wx.EVT_LEFT_UP, self.OnSpinMouseUp)

        self._textctrl.Bind(wx.EVT_TEXT_ENTER, self.OnTextEnter)
        self._textctrl.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)
        self._spinbutton.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)

        self.Bind(wx.EVT_SET_FOCUS, self.OnFocus)

        if "gtk3" not in wx.PlatformInfo:
            self.Bind(wx.EVT_SIZE, self.OnSize)

        if hasattr(self, "SetBestSize"):
            # Not Phoenix
            # start Philip Semanchuk move
            self.SetBestSize((width, height))
            # end Philip Semanchuk move

    def OnDestroy(self, event):
        """Handle the ``wx.EVT_WINDOW_DESTROY`` event for :class:`FloatSpin`.

        :param event: a :class:`WindowDestroyEvent` event to be processed.

        :note: This method tries to correctly handle the control destruction under MSW.
        """
        # Null This Since MSW Sends KILL_FOCUS On Deletion
        if self._textctrl:
            self._textctrl._parent = None
            self._textctrl.Destroy()
            self._textctrl = None

        self._spinbutton.Destroy()
        self._spinbutton = None

        return 0

    def DoGetBestSize(self):
        """Gets the size which best suits the window: for a control, it would be the
        minimal size which doesn't truncate the control, for a panel - the same
        size as it would have after a call to `Fit()`.

        :note: Overridden from :class:`PyControl`.
        """
        if self._spinctrl_bestsize.x == -999:
            spin = wx.SpinCtrl(self, -1)
            self._spinctrl_bestsize = spin.GetBestSize()

            # oops something went wrong, set to reasonable value
            if self._spinctrl_bestsize.GetWidth() < 20:
                self._spinctrl_bestsize.SetWidth(95)
            if self._spinctrl_bestsize.GetHeight() < 10:
                self._spinctrl_bestsize.SetHeight(22)

            spin.Destroy()

        return self._spinctrl_bestsize

    def DoSendEvent(self):
        """Send the event to the parent."""
        event = wx.CommandEvent(wx.wxEVT_COMMAND_SPINCTRL_UPDATED, self.GetId())
        event.SetEventObject(self)
        event.SetInt(int(self._value + 0.5))

        if self._textctrl:
            event.SetString(self._textctrl.GetValue())

        self.GetEventHandler().ProcessEvent(event)

        eventOut = FloatSpinEvent(wxEVT_FLOATSPIN, self.GetId())
        eventOut.SetPosition(int(self._value + 0.5))
        eventOut.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(eventOut)

    def Disable(self):
        self.Enable(False)

    def Enable(self, enable=True):
        """Enable the child controls. This is needed under wxMac"""

        wx.PyControl.Enable(self, enable)
        self._enabled = enable

        if self._textctrl:
            self._textctrl.Enable(enable)
        self._spinbutton.Enable(enable)

    @property
    def Enabled(self):
        return self._enabled

    @Enabled.setter
    def Enabled(self, enable=True):
        self.Enable(enable)

    def IsEnabled(self):
        return self._enabled

    def OnSpinMouseDown(self, event):
        """Handles the ``wx.EVT_LEFT_DOWN`` event for :class:`FloatSpin`.

        :param event: a :class:`MouseEvent` event to be processed.

        :note: This method works on the underlying :class:`SpinButton`.
        """

        modifier = FixedPoint(str(1.0), 20)
        if event.ShiftDown():
            modifier = modifier * 2.0
        if event.ControlDown():
            modifier = modifier * 10.0
        if event.AltDown():
            modifier = modifier * 100.0

        self._spinmodifier = modifier

        self._ignore_spin_event = False
        event.Skip()

    def OnSpinMouseUp(self, event):
        """Handles the ``wx.EVT_LEFT_UP`` event for :class:`FloatSpin`.

        :param event: a :class:`MouseEvent` event to be processed.

        :note: This method works on the underlying :class:`SpinButton`.
        """

        if self._textctrl:
            if "__WXMSW__" in wx.PlatformInfo:
                self._textctrl.SetFocus()
                self._textctrl.SelectAll()
            elif "__WXMAC__" not in wx.PlatformInfo:
                self._textctrl.SetFocus()
                self._textctrl.SetSelection(0, 0)

        self._ignore_spin_event = False
        event.Skip()

    def OnSpinUp(self, event):
        """Handles the ``wx.EVT_SPIN_UP`` event for :class:`FloatSpin`.

        :param event: a :class:`SpinEvent` event to be processed.
        """

        if self._ignore_spin_event:
            self._ignore_spin_event = False
            return

        if self._textctrl and self._textctrl.IsModified():
            self.SyncSpinToText(False)

        if self.InRange(self._value + self._increment * self._spinmodifier):
            self._value = self._value + self._increment * self._spinmodifier
        elif self._max is not None:
            self._value = self._max
        self.SetValue(self._value)
        if "__WXMAC__" in wx.PlatformInfo:
            self._textctrl.SelectAll()
        self.DoSendEvent()

    def OnSpinDown(self, event):
        """Handles the ``wx.EVT_SPIN_DOWN`` event for :class:`FloatSpin`.

        :param event: a :class:`SpinEvent` event to be processed.
        """

        if self._ignore_spin_event:
            self._ignore_spin_event = False
            return

        if self._textctrl and self._textctrl.IsModified():
            self.SyncSpinToText(False)

        if self.InRange(self._value - self._increment * self._spinmodifier):
            self._value = self._value - self._increment * self._spinmodifier
        elif self._min is not None:
            self._value = self._min
        self.SetValue(self._value)
        if "__WXMAC__" in wx.PlatformInfo:
            self._textctrl.SelectAll()
        self.DoSendEvent()

    def OnTextEnter(self, event):
        """Handles the ``wx.EVT_TEXT_ENTER`` event for :class:`FloatSpin`.

        :param event: a :class:`KeyEvent` event to be processed.

        :note: This method works on the underlying :class:`TextCtrl`.
        """

        self.SyncSpinToText(True)
        event.Skip()

    def OnKeyDown(self, event):
        """Handles the ``wx.EVT_KEYDOWN`` event for :class:`FloatSpin`.

        :param event: a :class:`KeyEvent` event to be processed.

        :note: This method works on the underlying :class:`TextCtrl`.
        """

        modifier = FixedPoint(str(1.0), 20)
        if event.ShiftDown():
            modifier = modifier * 2.0
        if event.ControlDown():
            modifier = modifier * 10.0
        if event.AltDown():
            modifier = modifier * 100.0

        keycode = event.GetKeyCode()

        if keycode == wx.WXK_UP:
            if self._textctrl and self._textctrl.IsModified():
                self.SyncSpinToText(False)

            self.SetValue(self._value + self._increment * modifier)
            self.DoSendEvent()

        elif keycode == wx.WXK_DOWN:
            if self._textctrl and self._textctrl.IsModified():
                self.SyncSpinToText(False)

            self.SetValue(self._value - self._increment * modifier)
            self.DoSendEvent()

        elif keycode == wx.WXK_PAGEUP:
            if self._textctrl and self._textctrl.IsModified():
                self.SyncSpinToText(False)

            self.SetValue(self._value + 10.0 * self._increment * modifier)
            self.DoSendEvent()

        elif keycode == wx.WXK_PAGEDOWN:
            if self._textctrl and self._textctrl.IsModified():
                self.SyncSpinToText(False)

            self.SetValue(self._value - 10.0 * self._increment * modifier)
            self.DoSendEvent()

        elif keycode == wx.WXK_SPACE:
            self.SetValue(self._value)
            if self._textctrl:
                self._textctrl.SelectAll()
            event.Skip(False)

        elif keycode == wx.WXK_ESCAPE:
            self.SetToDefaultValue()
            if self._textctrl:
                self._textctrl.SelectAll()
            self.DoSendEvent()

        elif keycode == wx.WXK_TAB:
            # The original event code doesn't work under wxGTK
            focus_next_keyboard_focusable_control(event.EventObject)

        elif keycode in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER):
            default = self.TopLevelParent.DefaultItem
            if (
                default
                and default.Enabled
                and default.IsShownOnScreen()
                and isinstance(default, wx.Button)
            ):
                default.ProcessEvent(
                    wx.PyCommandEvent(wx.EVT_BUTTON.typeId, default.GetId())
                )

        else:
            if (
                not event.CmdDown()
                and not event.ControlDown()
                and keycode not in self._validkeycode
            ):
                return

            event.Skip()

    def OnMouseWheel(self, event):
        """Handles the ``wx.EVT_MOUSEWHEEL`` event for :class:`FloatSpin`.

        :param event: a :class:`MouseEvent` event to be processed.
        """

        modifier = FixedPoint(str(1.0), 20)
        if event.ShiftDown():
            modifier = modifier * 2.0
        if event.ControlDown():
            modifier = modifier * 10.0
        if event.AltDown():
            modifier = modifier * 100.0

        if self._textctrl and self._textctrl.IsModified():
            self.SyncSpinToText(False)

        if event.GetWheelRotation() > 0:
            self.SetValue(self._value + self._increment * modifier)

        else:
            self.SetValue(self._value - self._increment * modifier)

        if self._textctrl:
            if "__WXMAC__" in wx.PlatformInfo:
                self._textctrl.SelectAll()
            else:
                self._textctrl.SetFocus()
                self._textctrl.SetSelection(0, 0)

        self.DoSendEvent()

    def OnSize(self, event):
        """Handles the ``wx.EVT_SIZE`` event for :class:`FloatSpin`.

        :param event: a :class:`SizeEvent` event to be processed.

        :note: This method resizes the text control and reposition the spin button when
         resized.
        """
        # start Philip Semanchuk addition
        event_width = event.GetSize().width

        self._textctrl.SetPosition((self._text_left, self._text_top))

        text_width, text_height = self._textctrl.Size

        spin_width, _ = self._spinbutton.Size

        text_width = event_width - (spin_width + self._gap + self._text_left)

        self._textctrl.SetSize(wx.Size(text_width, event.GetSize().height))

        # The spin button is always snug against the right edge of the
        # control.
        self._spinbutton.SetPosition((event_width - spin_width, self._spin_top))

        event.Skip()
        # end Philip Semanchuk addition

    def ReplaceDoubleZero(self, strs):
        """Replaces the (somewhat) python ugly `+e000` with `+e00`.

        :param strs: a string (possibly) containing a `+e00` substring.
        """

        if self._textformat not in ["%g", "%e", "%E", "%G"]:
            return strs

        if strs.find("e+00") >= 0:
            strs = strs.replace("e+00", "e+0")
        elif strs.find("e-00") >= 0:
            strs = strs.replace("e-00", "e-0")
        elif strs.find("E+00") >= 0:
            strs = strs.replace("E+00", "E+0")
        elif strs.find("E-00") >= 0:
            strs = strs.replace("E-00", "E-0")

        return strs

    def SetValue(self, value):
        """Sets the :class:`FloatSpin` value.

        :param value: the new value.
        """
        if not self._textctrl or not self.InRange(value):
            return

        if self._snapticks and self._increment != 0.0:
            finite, snap_value = self.IsFinite(value)

            if not finite:  # FIXME What To Do About A Failure?
                if snap_value - floor(snap_value) < ceil(snap_value) - snap_value:
                    value = self._defaultvalue + floor(snap_value) * self._increment
                else:
                    value = self._defaultvalue + ceil(snap_value) * self._increment

        decimal = locale.localeconv()["decimal_point"]
        strs = ("%100." + str(self._digits) + self._textformat[1]) % value
        strs = strs.replace(".", decimal)
        strs = strs.replace(",", ".")
        strs = strs.strip()
        strs = self.ReplaceDoubleZero(strs)

        # Sync spinbutton so that events generated by it match up with the
        # actual spin direction.
        # This fixes an issue under GTK and Mac OS X where the EVT_SPIN event
        # generated by pressing the spin up/down buttons is dependent on the
        # spin button value (e.g. if the down button is pressed when the button
        # value is at its minimum, there will always be a EVT_SPIN_UP generated
        # under GTK, and no event at all under Mac OS X).
        min_val = self._min if self._min is not None else self._spinbutton.Min
        max_val = self._max if self._max is not None else self._spinbutton.Max
        # Scale the value to the spinbutton range
        spinvalue = int(
            round(
                (float(value - min_val) / float(max_val - min_val))
                * self._spinbutton.Max
            )
        )
        # Setting the spin button value causes a EVT_SPIN event to be generated
        # under GTK, which we need to ignore
        self._ignore_spin_event = True
        self._spinbutton.SetValue(spinvalue)

        if value != self._value or strs != self._textctrl.GetValue():
            self._textctrl.SetValue(strs)
            self._textctrl.DiscardEdits()
            self._value = value

    def GetValue(self):
        """Returns the :class:`FloatSpin` value."""

        return float(self._value)

    def SetRangeDontClampValue(self, min_val, max_val):
        """Sets the allowed range.

        :param min_val: the minimum value for :class:`FloatSpin`. If it is ``None`` it is
         ignored;
        :param max_val: the maximum value for :class:`FloatSpin`. If it is ``None`` it is
         ignored.

        :note: This method doesn't modify the current value.
        """

        if min_val is not None:
            self._min = FixedPoint(str(min_val), 20)
        else:
            self._min = None
        if max_val is not None:
            self._max = FixedPoint(str(max_val), 20)
        else:
            self._max = None

    def SetRange(self, min_val, max_val):
        """Sets the allowed range.

        :param min_val: the minimum value for :class:`FloatSpin`. If it is ``None`` it is
         ignored;
        :param max_val: the maximum value for :class:`FloatSpin`. If it is ``None`` it is
         ignored.

        :note: This method doesn't modify the current value.

        :note: You specify open ranges like this (you can equally do this in the
         constructor)::

             SetRange(min_val=1, max_val=None)
             SetRange(min_val=None, max_val=0)


         or no range::

             SetRange(min_val=None, max_val=None)

        """

        self.SetRangeDontClampValue(min_val, max_val)

        value = self.ClampValue(self._value)
        if value != self._value:
            self.SetValue(value)

    def ClampValue(self, var):
        """Clamps `var` between `_min` and `_max` depending on the range has
        been specified.

        :param var: the value to be clamped.

        :return: A clamped copy of `var`.
        """

        if self._min is not None:
            if float(var) < float(self._min):
                var = self._min
                return var

        if self._max is not None:
            if float(var) > float(self._max):
                var = self._max

        return var

    def SetIncrement(self, increment):
        """Sets the increment for every ``EVT_FLOATSPIN`` event.

        :param increment: a floating point number specifying the :class:`FloatSpin` increment.
        """

        if increment < 1.0 / 10.0**self._digits:
            raise Exception(
                "\nERROR: Increment Should Be Greater Or Equal To 1/(10**digits)."
            )

        self._increment = FixedPoint(str(increment), 20)
        self.SetValue(self._value)

    def GetIncrement(self):
        """Returns the increment for every ``EVT_FLOATSPIN`` event."""

        return self._increment

    def SetDigits(self, digits=-1):
        """Sets the number of digits to show.

        :param digits: the number of digits to show. If `digits` < 0, :class:`FloatSpin`
         tries to calculate the best number of digits based on input values passed
         in the constructor.
        """

        if digits < 0:
            incr = str(self._increment)
            if incr.find(".") < 0:
                digits = 0
            else:
                digits = len(incr[incr.find(".") + 1 :])

        self._digits = digits

        self.SetValue(self._value)

    def GetDigits(self):
        """Returns the number of digits shown."""

        return self._digits

    def SetFormat(self, fmt="%f"):
        """Set the string format to use.

        :param fmt: the new string format to use. One of the following strings:

         ====== =================================
         Format Description
         ====== =================================
         'e'    Floating point exponential format (lowercase)
         'E'    Floating point exponential format (uppercase)
         'f'    Floating point decimal format
         'F'    Floating point decimal format
         'g'    Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise
         'G'    Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise
         ====== =================================

        """

        if fmt not in ["%f", "%g", "%e", "%E", "%F", "%G"]:
            raise Exception(
                "\nERROR: Bad Float Number Format: " + repr(fmt) + ". It Should Be "
                'One Of "%f", "%g", "%e", "%E", "%F", "%G"'
            )

        self._textformat = fmt

        if self._digits < 0:
            self.SetDigits()
        else:
            self.SetValue(self._value)

    def GetFormat(self):
        """Returns the string format in use.

        :see: :meth:`~FloatSpin.SetFormat` for a list of valid string formats.
        """

        return self._textformat

    def SetDefaultValue(self, defaultvalue):
        """Sets the :class:`FloatSpin` default value.

        :param defaultvalue: a floating point value representing the new default
         value for :class:`FloatSpin`.
        """

        if self.InRange(defaultvalue):
            self._defaultvalue = FixedPoint(str(defaultvalue), 20)

    def GetDefaultValue(self):
        """Returns the :class:`FloatSpin` default value."""

        return self._defaultvalue

    def IsDefaultValue(self):
        """Returns whether the current value is the default value or not."""

        return self._value == self._defaultvalue

    def SetToDefaultValue(self):
        """Sets :class:`FloatSpin` value to its default value."""

        self.SetValue(self._defaultvalue)

    def SetSnapToTicks(self, forceticks=True):
        """Force the value to always be divisible by the increment. Initially ``False``.

        :param forceticks: ``True`` to force the snap to ticks option, ``False`` otherwise.

        :note: This uses the default value as the basis, you will get strange results
         for very large differences between the current value and default value
         when the increment is very small.
        """

        if self._snapticks != forceticks:
            self._snapticks = forceticks
            self.SetValue(self._value)

    def GetSnapToTicks(self):
        """Returns whether the snap to ticks option is active or not."""

        return self._snapticks

    def OnFocus(self, event):
        """Handles the ``wx.EVT_SET_FOCUS`` event for :class:`FloatSpin`.

        :param event: a :class:`FocusEvent` event to be processed.
        """

        if self._textctrl:
            self._textctrl.SetFocus()

        event.Skip()

    def SyncSpinToText(self, send_event=True, force_valid=True):
        """Synchronize the underlying :class:`TextCtrl` with :class:`SpinButton`.

        :param send_event: ``True`` to send a ``EVT_FLOATSPIN`` event, ``False``
         otherwise;
        :param force_valid: ``True`` to force a valid value (i.e. inside the
         provided range), ``False`` otherwise.
        """

        if not self._textctrl:
            return

        curr = self._textctrl.GetValue()
        curr = curr.strip()
        decimal = locale.localeconv()["decimal_point"]
        curr = curr.replace(decimal, ".")
        curr = curr.replace(",", ".")

        if curr:
            try:
                curro = float(curr)
                curr = FixedPoint(curr, 20)
            except Exception:
                self.SetValue(self._value)
                return

            if force_valid or not self.HasRange() or self.InRange(curr):
                if force_valid and self.HasRange():
                    curr = self.ClampValue(curr)

                if self._value != curr:
                    self.SetValue(curr)

                    if send_event:
                        self.DoSendEvent()

        elif force_valid:
            # textctrl is out of sync, discard and reset
            self.SetValue(self.GetValue())

    def SetFont(self, font=None):
        """Sets the underlying :class:`TextCtrl` font.

        :param font: a valid instance of :class:`Font`.
        """

        if font is None:
            font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)

        if not self._textctrl:
            return False

        return self._textctrl.SetFont(font)

    def GetFont(self):
        """Returns the underlying :class:`TextCtrl` font."""

        if not self._textctrl:
            return self.GetFont()

        return self._textctrl.GetFont()

    def GetMin(self):
        """Returns the minimum value for :class:`FloatSpin`. It can be a
        number or ``None`` if no minimum is present.
        """

        return self._min

    def GetMax(self):
        """Returns the maximum value for :class:`FloatSpin`. It can be a
        number or ``None`` if no minimum is present.
        """

        return self._max

    def HasRange(self):
        """Returns whether :class:`FloatSpin` range has been set or not."""

        return (self._min is not None) or (self._max is not None)

    def InRange(self, value):
        """Returns whether a value is inside :class:`FloatSpin` range.

        :param value: the value to test.
        """

        if not self.HasRange():
            return True
        if self._min is not None:
            if float(value) < float(self._min):
                return False
        if self._max is not None:
            if float(value) > float(self._max):
                return False
        return True

    def GetTextCtrl(self):
        """Returns the underlying :class:`TextCtrl`."""

        return self._textctrl

    def IsFinite(self, value):
        """Tries to determine if a value is finite or infinite/NaN.

        :param value: the value to test.
        """

        try:
            snap_value = (value - self._defaultvalue) / self._increment
            finite = True
        except Exception:
            finite = False
            snap_value = None

        return finite, snap_value


if wx.VERSION >= (3,):
    # Use wx.SpinCtrlDouble
    EVT_FLOATSPIN = wx.EVT_SPINCTRLDOUBLE

    class FloatSpin(wx.SpinCtrlDouble):
        _spinwidth = 0

        def __init__(
            self,
            parent,
            id=wx.ID_ANY,
            pos=wx.DefaultPosition,
            size=(95, -1),
            style=wx.SP_ARROW_KEYS | wx.ALIGN_RIGHT,
            value=0.0,
            min_val=None,
            max_val=None,
            increment=1.0,
            digits=-1,
            agwStyle=FS_LEFT,
            name="FloatSpin",
        ):
            if "gtk3" in wx.PlatformInfo:
                if not FloatSpin._spinwidth:
                    spin = wx.SpinCtrl(parent, -1)
                    text = wx.TextCtrl(parent, -1)
                    FloatSpin._spinwidth = spin.Size[0] - text.Size[0] + 11
                    spin.Destroy()
                    text.Destroy()
                size = size[0] + FloatSpin._spinwidth, size[1]

            if agwStyle & FS_RIGHT:
                style = style | wx.TE_RIGHT
            elif agwStyle & FS_CENTRE:
                style = style | wx.TE_CENTER

            if agwStyle & FS_READONLY:
                style = style | wx.TE_READONLY

            wx.SpinCtrlDouble.__init__(
                self,
                parent,
                id,
                str(value),
                pos,
                size,
                style,
                min_val or 0,
                max_val or 100,
                value,
                increment,
                name,
            )
            if digits > -1:
                self.SetDigits(digits)


# Class FixedPoint, version 0.0.4.
# Released to the public domain 28-Mar-2001,
# by Tim Peters (tim.one@home.com).

# Provided as-is; use at your own risk; no warranty; no promises; enjoy!


# 28-Mar-01 ver 0.0,4
#     Use repr() instead of str() inside __str__, because str(long) changed
#     since this was first written (used to produce trailing "L", doesn't
#     now).
#
# 09-May-99 ver 0,0,3
#     Repaired __sub__(FixedPoint, string); was blowing up.
#     Much more careful conversion of float (now best possible).
#     Implemented exact % and divmod.
#
# 14-Oct-98 ver 0,0,2
#     Added int, long, frac.  Beefed up docs.  Removed DECIMAL_POINT
#     and MINUS_SIGN globals to discourage bloating this class instead
#     of writing formatting wrapper classes (or subclasses)
#
# 11-Oct-98 ver 0,0,1
#     posted to c.l.py

__version__ = 0, 0, 4

# The default value for the number of decimal digits carried after the
# decimal point.  This only has effect at compile-time.
DEFAULT_PRECISION = 2
# The default value for the number of decimal digits carried after the decimal point.
# This only has effect at compile-time.


class FixedPoint:
    """FixedPoint objects support decimal arithmetic with a fixed number of
    digits (called the object's precision) after the decimal point.  The
    number of digits before the decimal point is variable & unbounded.

    The precision is user-settable on a per-object basis when a FixedPoint
    is constructed, and may vary across FixedPoint objects.  The precision
    may also be changed after construction via `FixedPoint.set_precision(p)`.
    Note that if the precision of a FixedPoint is reduced via :meth:`FixedPoint.set_precision() <FixedPoint.set_precision>`,
    information may be lost to rounding.

    Example::

        >>> x = FixedPoint("5.55")  # precision defaults to 2
        >>> print x
        5.55
        >>> x.set_precision(1)      # round to one fraction digit
        >>> print x
        5.6
        >>> print FixedPoint("5.55", 1)  # same thing setting to 1 in constructor
        5.6
        >>> repr(x) #  returns constructor string that reproduces object exactly
        "FixedPoint('5.6', 1)"
        >>>


    When :class:`FixedPoint` objects of different precision are combined via + - * /,
    the result is computed to the larger of the inputs' precisions, which also
    becomes the precision of the resulting :class:`FixedPoint` object. Example::

        >>> print FixedPoint("3.42") + FixedPoint("100.005", 3)
        103.425
        >>>


    When a :class:`FixedPoint` is combined with other numeric types (ints, floats,
    strings representing a number) via + - * /, then similarly the computation
    is carried out using -- and the result inherits -- the :class:`FixedPoint`'s
    precision. Example::

        >>> print FixedPoint(1) / 7
        0.14
        >>> print FixedPoint(1, 30) / 7
        0.142857142857142857142857142857
        >>>


    The string produced by `str(x)` (implictly invoked by `print`) always
    contains at least one digit before the decimal point, followed by a
    decimal point, followed by exactly `x.get_precision()` digits.  If `x` is
    negative, `str(x)[0] == "-"`.

    The :class:`FixedPoint` constructor can be passed an int, long, string, float,
    :class:`FixedPoint`, or any object convertible to a float via `float()` or to a
    long via `long()`. Passing a precision is optional; if specified, the
    precision must be a non-negative int. There is no inherent limit on
    the size of the precision, but if very very large you'll probably run
    out of memory.

    Note that conversion of floats to :class:`FixedPoint` can be surprising, and
    should be avoided whenever possible. Conversion from string is exact
    (up to final rounding to the requested precision), so is greatly
    preferred. Example::

        >>> print FixedPoint(1.1e30)
        1099999999999999993725589651456.00
        >>> print FixedPoint("1.1e30")
        1100000000000000000000000000000.00
        >>>

    :param str value: The initial value.
    :param precision: must be an int >= 0, and defaults to ``DEFAULT_PRECISION``.
    """

    # the exact value is self.n / 10**self.p;
    # self.n is a long; self.p is an int

    def __init__(self, value=None, precision=DEFAULT_PRECISION):
        if value is None:
            value = 0

        self.n = self.p = 0
        self.set_precision(precision)
        p = self.p

        if isinstance(value, str):
            n, exp = _string2exact(value)
            # exact value is n*10**exp = n*10**(exp+p)/10**p
            effective_exp = exp + p
            if effective_exp > 0:
                n = n * _tento(effective_exp)
            elif effective_exp < 0:
                n = _roundquotient(n, _tento(-effective_exp))
            self.n = n
            return

        if isinstance(value, int):
            self.n = value * _tento(p)
            return

        if isinstance(value, FixedPoint):
            temp = value.copy()
            temp.set_precision(p)
            self.n, self.p = temp.n, temp.p
            return

        if isinstance(value, float):
            # XXX ignoring infinities and NaNs and overflows for now
            import math

            f, e = math.frexp(abs(value))
            assert f == 0 or 0.5 <= f < 1.0
            # |value| = f * 2**e exactly

            # Suck up CHUNK bits at a time; 28 is enough so that we suck
            # up all bits in 2 iterations for all known binary double-
            # precision formats, and small enough to fit in an int.
            CHUNK = 28
            top = 0
            # invariant: |value| = (top + f) * 2**e exactly
            while f:
                f = math.ldexp(f, CHUNK)
                digit = int(f)
                assert digit >> CHUNK == 0
                top = (top << CHUNK) | digit
                f = f - digit
                assert 0.0 <= f < 1.0
                e = e - CHUNK

            # now |value| = top * 2**e exactly
            # want n such that n / 10**p = top * 2**e, or
            # n = top * 10**p * 2**e
            top = top * _tento(p)
            if e >= 0:
                n = top << e
            else:
                n = _roundquotient(top, 1 << -e)
            if value < 0:
                n = -n
            self.n = n
            return

        if isinstance(value, complex):
            raise TypeError("can't convert complex to FixedPoint: " + repr(value))

        # can we coerce to a float?
        yes = 1
        try:
            asfloat = float(value)
        except Exception:
            yes = 0
        if yes:
            self.__init__(asfloat, p)
            return

        # similarly for long
        yes = 1
        try:
            aslong = int(value)
        except Exception:
            yes = 0
        if yes:
            self.__init__(aslong, p)
            return

        raise TypeError("can't convert to FixedPoint: " + repr(value))

    def get_precision(self):
        """Return the precision of this :class:`FixedPoint`.

        :note: The precision is the number of decimal digits carried after
         the decimal point, and is an int >= 0.
        """

        return self.p

    def set_precision(self, precision=DEFAULT_PRECISION):
        """Change the precision carried by this :class:`FixedPoint` to `precision`.

        :param precision: must be an int >= 0, and defaults to
         ``DEFAULT_PRECISION``.

        :note: If `precision` is less than this :class:`FixedPoint`'s current precision,
         information may be lost to rounding.
        """

        try:
            p = int(precision)
        except Exception:
            raise TypeError("precision not convertable to int: " + repr(precision))
        if p < 0:
            raise ValueError("precision must be >= 0: " + repr(precision))

        if p > self.p:
            self.n = self.n * _tento(p - self.p)
        elif p < self.p:
            self.n = _roundquotient(self.n, _tento(self.p - p))
        self.p = p

    def __str__(self):
        n, p = self.n, self.p
        i, f = divmod(abs(n), _tento(p))
        if p:
            frac = repr(f)[:-1]
            frac = "0" * (p - len(frac)) + frac
        else:
            frac = ""
        return "-"[: n < 0] + repr(i)[:-1] + "." + frac

    def __repr__(self):
        return "FixedPoint" + repr((str(self), self.p))

    def copy(self):
        """Create a copy of the current :class:`FixedPoint`."""

        return _mkFP(self.n, self.p)

    __copy__ = __deepcopy__ = copy

    def __cmp__(self, other):
        if other is None:
            return 1
        xn, yn, p = _norm(self, other)
        return cmp(xn, yn)

    def __hash__(self):
        # caution!  == values must have equal hashes, and a FixedPoint
        # is essentially a rational in unnormalized form.  There's
        # really no choice here but to normalize it, so hash is
        # potentially expensive.
        n, p = self.__reduce()

        # Obscurity: if the value is an exact integer, p will be 0 now,
        # so the hash expression reduces to hash(n).  So FixedPoints
        # that happen to be exact integers hash to the same things as
        # their int or long equivalents.  This is Good.  But if a
        # FixedPoint happens to have a value exactly representable as
        # a float, their hashes may differ.  This is a teensy bit Bad.
        return hash(n) ^ hash(p)

    def __bool__(self):
        return self.n != 0

    def __neg__(self):
        return _mkFP(-self.n, self.p)

    def __abs__(self):
        if self.n >= 0:
            return self.copy()
        else:
            return -self

    def __add__(self, other):
        n1, n2, p = _norm(self, other)
        # n1/10**p + n2/10**p = (n1+n2)/10**p
        return _mkFP(n1 + n2, p)

    __radd__ = __add__

    def __sub__(self, other):
        if not isinstance(other, FixedPoint):
            other = FixedPoint(other, self.p)
        return self.__add__(-other)

    def __rsub__(self, other):
        return (-self) + other

    def __mul__(self, other):
        n1, n2, p = _norm(self, other)
        # n1/10**p * n2/10**p = (n1*n2/10**p)/10**p
        return _mkFP(_roundquotient(n1 * n2, _tento(p)), p)

    __rmul__ = __mul__

    def __div__(self, other):
        n1, n2, p = _norm(self, other)
        if n2 == 0:
            raise ZeroDivisionError("FixedPoint division")
        if n2 < 0:
            n1, n2 = -n1, -n2
        # n1/10**p / (n2/10**p) = n1/n2 = (n1*10**p/n2)/10**p
        return _mkFP(_roundquotient(n1 * _tento(p), n2), p)

    def __rdiv__(self, other):
        n1, n2, p = _norm(self, other)
        return _mkFP(n2, p) / self

    def __divmod__(self, other):
        n1, n2, p = _norm(self, other)
        if n2 == 0:
            raise ZeroDivisionError("FixedPoint modulo")
        # floor((n1/10**p)/(n2*10**p)) = floor(n1/n2)
        q = n1 / n2
        # n1/10**p - q * n2/10**p = (n1 - q * n2)/10**p
        return q, _mkFP(n1 - q * n2, p)

    def __rdivmod__(self, other):
        n1, n2, p = _norm(self, other)
        return divmod(_mkFP(n2, p), self)

    def __mod__(self, other):
        return self.__divmod__(other)[1]

    def __rmod__(self, other):
        n1, n2, p = _norm(self, other)
        return _mkFP(n2, p).__mod__(self)

    # caution! float can lose precision
    def __float__(self):
        n, p = self.__reduce()
        return float(n) / float(_tento(p))

    # XXX should this round instead?
    # XXX note e.g. long(-1.9) == -1L and long(1.9) == 1L in Python
    # XXX note that __int__ inherits whatever __long__ does,
    # XXX and .frac() is affected too
    def __long__(self):
        answer = abs(self.n) / _tento(self.p)
        if self.n < 0:
            answer = -answer
        return answer

    def __int__(self):
        return int(self.__long__())

    def frac(self):
        """Returns fractional portion as a :class:`FixedPoint`.

        :note: In :class:`FixedPoint`,

         this equality holds true::

                x = x.frac() + long(x)


        """
        return self - int(self)

    # return n, p s.t. self == n/10**p and n % 10 != 0
    def __reduce(self):
        n, p = self.n, self.p
        if n == 0:
            p = 0
        while p and n % 10 == 0:
            p = p - 1
            n = n / 10
        return n, p


# return 10L**n


def _tento(n, cache=None):
    if cache is None:
        cache = {}
    try:
        return cache[n]
    except KeyError:
        answer = cache[n] = 10**n
        return answer


# return xn, yn, p s.t.
# p = max(x.p, y.p)
# x = xn / 10**p
# y = yn / 10**p
#
# x must be FixedPoint to begin with; if y is not FixedPoint,
# it inherits its precision from x.
#
# Note that this is called a lot, so default-arg tricks are helpful.


def _norm(x, y, isinstance=isinstance, FixedPoint=FixedPoint, _tento=_tento):
    assert isinstance(x, FixedPoint)
    if not isinstance(y, FixedPoint):
        y = FixedPoint(y, x.p)
    xn, yn = x.n, y.n
    xp, yp = x.p, y.p
    if xp > yp:
        yn = yn * _tento(xp - yp)
        p = xp
    elif xp < yp:
        xn = xn * _tento(yp - xp)
        p = yp
    else:
        p = xp  # same as yp
    return xn, yn, p


def _mkFP(n, p, FixedPoint=FixedPoint):
    f = FixedPoint()
    f.n = n
    f.p = p
    return f


# divide x by y, rounding to int via nearest-even
# y must be > 0
# XXX which rounding modes are useful?


def cmp(a, b):
    """Reimplemented Python 2.x cmp function

    :param a: A number
    :param b: A number
    :return: -1 or 1
    """
    return (a > b) - (a < b)


def _roundquotient(x, y):
    assert y > 0
    n, leftover = divmod(x, y)
    c = cmp(leftover << 1, y)
    # c < 0 <-> leftover < y/2, etc
    if c > 0 or (c == 0 and (n & 1) == 1):
        n = n + 1
    return n


# crud for parsing strings

# There's an optional sign at the start, and an optional exponent
# at the end.  The exponent has an optional sign and at least one
# digit.  In between, must have either at least one digit followed
# by an optional fraction, or a decimal point followed by at least
# one digit.  Yuck.

_parser = re.compile(
    r"""
    \s*
    (?P<sign>[-+])?
    (
        (?P<int>\d+) (\. (?P<frac>\d*))?
    |
        \. (?P<onlyfrac>\d+)
    )
    ([eE](?P<exp>[-+]? \d+))?
    \s* $
""",
    re.VERBOSE,
).match

del re

# return n, p s.t. float string value == n * 10**p exactly


def _string2exact(s):
    m = _parser(s)
    if m is None:
        raise ValueError("can't parse as number: " + repr(s))

    exp = m.group("exp")
    if exp is None:
        exp = 0
    else:
        exp = int(exp)

    intpart = m.group("int")
    if intpart is None:
        intpart = "0"
        fracpart = m.group("onlyfrac")
    else:
        fracpart = m.group("frac")
        if fracpart is None or fracpart == "":
            fracpart = "0"
    assert intpart
    assert fracpart

    i, f = int(intpart), int(fracpart)
    nfrac = len(fracpart)
    i = i * _tento(nfrac) + f
    exp = exp - nfrac

    if m.group("sign") == "-":
        i = -i

    return i, exp


def get_all_keyboard_focusable_children(parent):
    """Get all keyboard focusable children of parent"""

    children = []
    try:
        iter(parent.Children)
        # Under Mac OS X panels may have non-iterator children
    except Exception:
        pass
    else:
        for child in parent.Children:
            if child.Enabled and child.IsShownOnScreen():
                if child.AcceptsFocusFromKeyboard():
                    if not isinstance(child, wx.RadioButton) or child.Value:
                        children.append(child)
                if child.Children:
                    children.extend(get_all_keyboard_focusable_children(child))
    return children


def focus_next_keyboard_focusable_control(control):
    """Focus the next control in tab order that can gain focus.

    If the shift key is held down, tab order is reversed.

    """

    # Find the last panel in the hierarchy of parents
    parent = control.Parent
    focusparent = None
    while parent:
        if isinstance(parent, (wx.Panel, wx.PyPanel)):
            focusparent = parent
        parent = parent.Parent
    if focusparent:
        children = get_all_keyboard_focusable_children(focusparent)
        if wx.GetKeyState(wx.WXK_SHIFT):
            children = list(reversed(children))
        for i, child in enumerate(children):
            if child is control:
                for next in children[i + 1 :] + children[:i]:
                    if next is not child.Parent:
                        next.SetFocus()
                        break
                break