1# This file is generated by wxPython's SIP generator.  Do not edit by hand.
2#
3# Copyright: (c) 2018 by Total Control Software
4# License:   wxWindows License
5
6"""
7The classes in this module are the most commonly used classes for wxPython,
8which is why they have been made visible in the core `wx` namespace.
9Everything you need for building typical GUI applications is here.
10"""
11
12from ._core import *
13
14#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
15# This code block was included from src/core_ex.py
16import sys as _sys
17
18# Load version numbers from __version__ and some other initialization tasks...
19if 'wxEVT_NULL' in dir():
20    from wx.__version__ import *
21    import wx._core
22    __version__ = VERSION_STRING
23
24    # Add the build type to PlatformInfo
25    PlatformInfo = PlatformInfo + ('build-type: ' + BUILD_TYPE, )
26
27    # Register a function to be called when Python terminates that will clean
28    # up and release all system resources that wxWidgets allocated.
29    import atexit
30    atexit.register(wx._core._wxPyCleanup)
31    del atexit
32
33else:
34    Port = ''
35    Platform = ''
36    PlatformInfo = []
37
38# A little trick to make 'wx' be a reference to this module so wx.Names can
39# be used in the python code here.
40wx = _sys.modules[__name__]
41
42
43import warnings
44class wxPyDeprecationWarning(DeprecationWarning):
45    pass
46
47warnings.simplefilter('default', wxPyDeprecationWarning)
48del warnings
49
50
51def deprecated(item, msg='', useName=False):
52    """
53    Create a delegating wrapper that raises a deprecation warning.  Can be
54    used with callable objects (functions, methods, classes) or with
55    properties.
56    """
57    import warnings
58
59    name = ''
60    if useName:
61        try:
62            name = ' ' + item.__name__
63        except AttributeError:
64            pass
65
66    if isinstance(item, type):
67        # It is a class.  Make a subclass that raises a warning.
68        class DeprecatedClassProxy(item):
69            def __init__(*args, **kw):
70                warnings.warn("Using deprecated class%s. %s" % (name, msg),
71                          wxPyDeprecationWarning, stacklevel=2)
72                item.__init__(*args, **kw)
73        DeprecatedClassProxy.__name__ = item.__name__
74        return DeprecatedClassProxy
75
76    elif callable(item):
77        # wrap a new function around the callable
78        def deprecated_func(*args, **kw):
79            warnings.warn("Call to deprecated item%s. %s" % (name, msg),
80                          wxPyDeprecationWarning, stacklevel=2)
81            if not kw:
82                return item(*args)
83            return item(*args, **kw)
84        deprecated_func.__name__ = item.__name__
85        deprecated_func.__doc__ = item.__doc__
86        if hasattr(item, '__dict__'):
87            deprecated_func.__dict__.update(item.__dict__)
88        return deprecated_func
89
90    elif hasattr(item, '__get__'):
91        # it should be a property if there is a getter
92        class DepGetProp(object):
93            def __init__(self, item, msg):
94                self.item = item
95                self.msg = msg
96            def __get__(self, inst, klass):
97                warnings.warn("Accessing deprecated property. %s" % msg,
98                              wxPyDeprecationWarning, stacklevel=2)
99                return self.item.__get__(inst, klass)
100        class DepGetSetProp(DepGetProp):
101            def __set__(self, inst, val):
102                warnings.warn("Accessing deprecated property. %s" % msg,
103                              wxPyDeprecationWarning, stacklevel=2)
104                return self.item.__set__(inst, val)
105        class DepGetSetDelProp(DepGetSetProp):
106            def __delete__(self, inst):
107                warnings.warn("Accessing deprecated property. %s" % msg,
108                              wxPyDeprecationWarning, stacklevel=2)
109                return self.item.__delete__(inst)
110
111        if hasattr(item, '__set__') and hasattr(item, '__delete__'):
112            return DepGetSetDelProp(item, msg)
113        elif hasattr(item, '__set__'):
114            return DepGetSetProp(item, msg)
115        else:
116            return DepGetProp(item, msg)
117    else:
118        raise TypeError("unsupported type %s" % type(item))
119
120
121def deprecatedMsg(msg):
122    """
123    A wrapper for the deprecated decorator that makes it easier to attach a
124    custom message to the warning that is raised if the item is used. This
125    can also be used in the @decorator role since it returns the real
126    decorator when called.
127    """
128    import functools
129    return functools.partial(deprecated, msg=msg, useName=True)
130
131#----------------------------------------------------------------------------
132
133EmptyString = ""
134
135#----------------------------------------------------------------------------
136
137# End of included code block
138#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
139
140BG_STYLE_CUSTOM = BG_STYLE_PAINT
141
142def _ClientDataContainer_GetClientObject(self):
143    """
144    Alias for :meth:`GetClientData`
145    """
146    return self.GetClientData()
147ClientDataContainer.GetClientObject = _ClientDataContainer_GetClientObject
148del _ClientDataContainer_GetClientObject
149def _ClientDataContainer_SetClientObject(self, data):
150    """
151    Alias for :meth:`SetClientData`
152    """
153    self.SetClientData(data)
154ClientDataContainer.SetClientObject = _ClientDataContainer_SetClientObject
155del _ClientDataContainer_SetClientObject
156ClientDataContainer.ClientData = property(ClientDataContainer.GetClientData, ClientDataContainer.SetClientData)
157def _initStockObjects():
158    import wx
159    wx.NORMAL_FONT._copyFrom(       StockGDI.instance().GetFont(StockGDI.FONT_NORMAL))
160    wx.SMALL_FONT._copyFrom(        StockGDI.instance().GetFont(StockGDI.FONT_SMALL))
161    wx.SWISS_FONT._copyFrom(        StockGDI.instance().GetFont(StockGDI.FONT_SWISS))
162    wx.ITALIC_FONT._copyFrom(       StockGDI.instance().GetFont(StockGDI.FONT_ITALIC))
163
164    wx.BLACK_DASHED_PEN._copyFrom(  StockGDI.GetPen(StockGDI.PEN_BLACKDASHED))
165    wx.BLACK_PEN._copyFrom(         StockGDI.GetPen(StockGDI.PEN_BLACK))
166    wx.BLUE_PEN._copyFrom(          StockGDI.GetPen(StockGDI.PEN_BLUE))
167    wx.CYAN_PEN._copyFrom(          StockGDI.GetPen(StockGDI.PEN_CYAN))
168    wx.GREEN_PEN._copyFrom(         StockGDI.GetPen(StockGDI.PEN_GREEN))
169    wx.YELLOW_PEN._copyFrom(        StockGDI.GetPen(StockGDI.PEN_YELLOW))
170    wx.GREY_PEN._copyFrom(          StockGDI.GetPen(StockGDI.PEN_GREY))
171    wx.LIGHT_GREY_PEN._copyFrom(    StockGDI.GetPen(StockGDI.PEN_LIGHTGREY))
172    wx.MEDIUM_GREY_PEN._copyFrom(   StockGDI.GetPen(StockGDI.PEN_MEDIUMGREY))
173    wx.RED_PEN._copyFrom(           StockGDI.GetPen(StockGDI.PEN_RED))
174    wx.TRANSPARENT_PEN._copyFrom(   StockGDI.GetPen(StockGDI.PEN_TRANSPARENT))
175    wx.WHITE_PEN._copyFrom(         StockGDI.GetPen(StockGDI.PEN_WHITE))
176
177    wx.BLACK_BRUSH._copyFrom(       StockGDI.GetBrush(StockGDI.BRUSH_BLACK))
178    wx.BLUE_BRUSH._copyFrom(        StockGDI.GetBrush(StockGDI.BRUSH_BLUE))
179    wx.CYAN_BRUSH._copyFrom(        StockGDI.GetBrush(StockGDI.BRUSH_CYAN))
180    wx.GREEN_BRUSH._copyFrom(       StockGDI.GetBrush(StockGDI.BRUSH_GREEN))
181    wx.YELLOW_BRUSH._copyFrom(      StockGDI.GetBrush(StockGDI.BRUSH_YELLOW))
182    wx.GREY_BRUSH._copyFrom(        StockGDI.GetBrush(StockGDI.BRUSH_GREY))
183    wx.LIGHT_GREY_BRUSH._copyFrom(  StockGDI.GetBrush(StockGDI.BRUSH_LIGHTGREY))
184    wx.MEDIUM_GREY_BRUSH._copyFrom( StockGDI.GetBrush(StockGDI.BRUSH_MEDIUMGREY))
185    wx.RED_BRUSH._copyFrom(         StockGDI.GetBrush(StockGDI.BRUSH_RED))
186    wx.TRANSPARENT_BRUSH._copyFrom( StockGDI.GetBrush(StockGDI.BRUSH_TRANSPARENT))
187    wx.WHITE_BRUSH._copyFrom(       StockGDI.GetBrush(StockGDI.BRUSH_WHITE))
188
189    wx.BLACK._copyFrom(             StockGDI.GetColour(StockGDI.COLOUR_BLACK))
190    wx.BLUE._copyFrom(              StockGDI.GetColour(StockGDI.COLOUR_BLUE))
191    wx.CYAN._copyFrom(              StockGDI.GetColour(StockGDI.COLOUR_CYAN))
192    wx.GREEN._copyFrom(             StockGDI.GetColour(StockGDI.COLOUR_GREEN))
193    wx.YELLOW._copyFrom(            StockGDI.GetColour(StockGDI.COLOUR_YELLOW))
194    wx.LIGHT_GREY._copyFrom(        StockGDI.GetColour(StockGDI.COLOUR_LIGHTGREY))
195    wx.RED._copyFrom(               StockGDI.GetColour(StockGDI.COLOUR_RED))
196    wx.WHITE._copyFrom(             StockGDI.GetColour(StockGDI.COLOUR_WHITE))
197
198    wx.CROSS_CURSOR._copyFrom(      StockGDI.GetCursor(StockGDI.CURSOR_CROSS))
199    wx.HOURGLASS_CURSOR._copyFrom(  StockGDI.GetCursor(StockGDI.CURSOR_HOURGLASS))
200    wx.STANDARD_CURSOR._copyFrom(   StockGDI.GetCursor(StockGDI.CURSOR_STANDARD))
201
202    wx.TheFontList       = StockGDI._getTheFontList()
203    wx.ThePenList        = StockGDI._getThePenList()
204    wx.TheBrushList      = StockGDI._getTheBrushList()
205    wx.TheColourDatabase = StockGDI._getTheColourDatabase()
206
207
208StockGDI._initStockObjects = staticmethod(_initStockObjects)
209def _DateTime___repr__(self):
210    from six import PY2
211    if self.IsValid():
212        f = self.Format()
213        if PY2: f = f.encode('utf-8')
214        return '<wx.DateTime: "%s">' % f
215    else:
216        return '<wx.DateTime: "INVALID">'
217DateTime.__repr__ = _DateTime___repr__
218del _DateTime___repr__
219def _DateTime___str__(self):
220    from six import PY2
221    if self.IsValid():
222        f = self.Format()
223        if PY2: f = f.encode('utf-8')
224        return f
225    else:
226        return "INVALID DateTime"
227DateTime.__str__ = _DateTime___str__
228del _DateTime___str__
229InvalidDateTime = DefaultDateTime
230
231@wx.deprecatedMsg("Use :meth:`DateTime.FromTimeT` instead.")
232def DateTimeFromTimeT(timet):
233    """
234    Compatibility wrapper for :meth:`DateTime.FromTimeT`
235    """
236    return DateTime.FromTimeT(timet)
237
238@wx.deprecatedMsg("Use :meth:`DateTime.FromJDN` instead.")
239def DateTimeFromJDN(jdn):
240    """
241    Compatibility wrapper for :meth:`DateTime.FromJDN`
242    """
243    return DateTime.FromJDN(jdn)
244
245@wx.deprecatedMsg("Use :meth:`DateTime.FromHMS` instead.")
246def DateTimeFromHMS(hour, minute=0, second=0, millisecond=0):
247    """
248    Compatibility wrapper for :meth:`DateTime.FromHMS`
249    """
250    return DateTime.FromHMS(hour, minute, second, millisecond)
251
252@wx.deprecatedMsg("Use :meth:`DateTime.FromDMY` instead.")
253def DateTimeFromDMY(day, month, year=DateTime.Inv_Year, hour=0, minute=0, second=0, millisecond=0):
254    """
255    Compatibility wrapper for :meth:`DateTime.FromDMY`
256    """
257    return DateTime.FromDMY(day, month, year, hour, minute, second, millisecond)
258
259def pydate2wxdate(date):
260    """
261    Convert a Python date or datetime to a :class:`DateTime` object
262    """
263    import datetime
264    assert isinstance(date, (datetime.datetime, datetime.date))
265    return DateTime(date)  # the built-in typemap will convert it for us
266
267def wxdate2pydate(date):
268    """
269    Convert a :class:`DateTime` object to a Python datetime.
270    """
271    import datetime
272    assert isinstance(date, DateTime)
273    if date.IsValid():
274        return datetime.datetime(date.year, date.month+1, date.day,
275                                 date.hour, date.minute, date.second, date.millisecond*1000)
276    else:
277        return None
278
279def _WindowIDRef___repr__(self):
280    return "WindowIDRef: {}".format(self.GetId())
281WindowIDRef.__repr__ = _WindowIDRef___repr__
282del _WindowIDRef___repr__
283def _WindowIDRef___hash__(self):
284    return hash(self.GetValue())
285WindowIDRef.__hash__ = _WindowIDRef___hash__
286del _WindowIDRef___hash__
287def NewIdRef(count=1):
288    """
289    Reserves a new Window ID (or range of WindowIDs) and returns a
290    :class:`wx.WindowIDRef` object (or list of them) that will help
291    manage the reservation of that ID.
292
293    This function is intended to be a drop-in replacement of the old
294    and deprecated :func:`wx.NewId` function, with the added benefit
295    that the ID should never conflict with an in-use ID or other IDs
296    generated by this function.
297    """
298    if count == 1:
299        return WindowIDRef(IdManager.ReserveId())
300    else:
301        start = IdManager.ReserveId(count)
302        IDRefs = []
303        for id in range(start, start+count):
304            IDRefs.append(WindowIDRef(id))
305        return IDRefs
306
307def _ArrayVideoModes___repr__(self):
308    return "ArrayVideoModes: " + repr(list(self))
309ArrayVideoModes.__repr__ = _ArrayVideoModes___repr__
310del _ArrayVideoModes___repr__
311#----------------------------------------------------------------------------
312# Add the directory where the wxWidgets catalogs were installed
313# to the default catalog path, if they were put in the pacakge dir.
314import os
315_localedir = os.path.join(os.path.dirname(__file__), "locale")
316if os.path.exists(_localedir):
317    Locale.AddCatalogLookupPathPrefix(_localedir)
318del os
319#----------------------------------------------------------------------------
320
321def _Point_GetIM(self):
322    """
323    Returns an immutable representation of the ``wx.Point`` object, based on ``namedtuple``.
324
325    This new object is hashable and can be used as a dictionary key,
326    be added to sets, etc.  It can be converted back into a real ``wx.Point``
327    with a simple statement like this: ``obj = wx.Point(imObj)``.
328    """
329    return _im_Point(*self.Get())
330Point.GetIM = _Point_GetIM
331del _Point_GetIM
332def _Point___str__(self):
333    return str(self.Get())
334Point.__str__ = _Point___str__
335del _Point___str__
336def _Point___repr__(self):
337    return "wx.Point"+str(self.Get())
338Point.__repr__ = _Point___repr__
339del _Point___repr__
340def _Point___len__(self):
341    return len(self.Get())
342Point.__len__ = _Point___len__
343del _Point___len__
344def _Point___reduce__(self):
345    return (Point, self.Get())
346Point.__reduce__ = _Point___reduce__
347del _Point___reduce__
348def _Point___getitem__(self, idx):
349    return self.Get()[idx]
350Point.__getitem__ = _Point___getitem__
351del _Point___getitem__
352def _Point___setitem__(self, idx, val):
353    if idx == 0: self.x = val
354    elif idx == 1: self.y = val
355    else: raise IndexError
356Point.__setitem__ = _Point___setitem__
357del _Point___setitem__
358Point.__safe_for_unpickling__ = True
359
360Point.IM = property(Point.GetIM)
361def _Size_GetIM(self):
362    """
363    Returns an immutable representation of the ``wx.Size`` object, based on ``namedtuple``.
364
365    This new object is hashable and can be used as a dictionary key,
366    be added to sets, etc.  It can be converted back into a real ``wx.Size``
367    with a simple statement like this: ``obj = wx.Size(imObj)``.
368    """
369    return _im_Size(*self.Get())
370Size.GetIM = _Size_GetIM
371del _Size_GetIM
372def _Size___str__(self):
373    return str(self.Get())
374Size.__str__ = _Size___str__
375del _Size___str__
376def _Size___repr__(self):
377    return "wx.Size"+str(self.Get())
378Size.__repr__ = _Size___repr__
379del _Size___repr__
380def _Size___len__(self):
381    return len(self.Get())
382Size.__len__ = _Size___len__
383del _Size___len__
384def _Size___nonzero__(self):
385    return self.Get() != (0,0)
386Size.__nonzero__ = _Size___nonzero__
387del _Size___nonzero__
388def _Size___bool__(self):
389    return self.Get() != (0,0)
390Size.__bool__ = _Size___bool__
391del _Size___bool__
392def _Size___reduce__(self):
393    return (Size, self.Get())
394Size.__reduce__ = _Size___reduce__
395del _Size___reduce__
396def _Size___getitem__(self, idx):
397    return self.Get()[idx]
398Size.__getitem__ = _Size___getitem__
399del _Size___getitem__
400def _Size___setitem__(self, idx, val):
401    if idx == 0: self.width = val
402    elif idx == 1: self.height = val
403    else: raise IndexError
404Size.__setitem__ = _Size___setitem__
405del _Size___setitem__
406Size.__safe_for_unpickling__ = True
407
408def _Rect_GetIM(self):
409    """
410    Returns an immutable representation of the ``wx.Rect`` object, based on ``namedtuple``.
411
412    This new object is hashable and can be used as a dictionary key,
413    be added to sets, etc.  It can be converted back into a real ``wx.Rect``
414    with a simple statement like this: ``obj = wx.Rect(imObj)``.
415    """
416    return _im_Rect(*self.Get())
417Rect.GetIM = _Rect_GetIM
418del _Rect_GetIM
419def _Rect___str__(self):
420    return str(self.Get())
421Rect.__str__ = _Rect___str__
422del _Rect___str__
423def _Rect___repr__(self):
424    return "wx.Rect"+str(self.Get())
425Rect.__repr__ = _Rect___repr__
426del _Rect___repr__
427def _Rect___len__(self):
428    return len(self.Get())
429Rect.__len__ = _Rect___len__
430del _Rect___len__
431def _Rect___nonzero__(self):
432    return self.Get() != (0,0,0,0)
433Rect.__nonzero__ = _Rect___nonzero__
434del _Rect___nonzero__
435def _Rect___bool__(self):
436    return self.Get() != (0,0,0,0)
437Rect.__bool__ = _Rect___bool__
438del _Rect___bool__
439def _Rect___reduce__(self):
440    return (Rect, self.Get())
441Rect.__reduce__ = _Rect___reduce__
442del _Rect___reduce__
443def _Rect___getitem__(self, idx):
444    return self.Get()[idx]
445Rect.__getitem__ = _Rect___getitem__
446del _Rect___getitem__
447def _Rect___setitem__(self, idx, val):
448    if idx == 0: self.x = val
449    elif idx == 1: self.y = val
450    elif idx == 2: self.width = val
451    elif idx == 3: self.height = val
452    else: raise IndexError
453Rect.__setitem__ = _Rect___setitem__
454del _Rect___setitem__
455Rect.__safe_for_unpickling__ = True
456
457def _RealPoint_GetIM(self):
458    """
459    Returns an immutable representation of the ``wx.RealPoint`` object, based on ``namedtuple``.
460
461    This new object is hashable and can be used as a dictionary key,
462    be added to sets, etc.  It can be converted back into a real ``wx.RealPoint``
463    with a simple statement like this: ``obj = wx.RealPoint(imObj)``.
464    """
465    return _im_RealPoint(*self.Get())
466RealPoint.GetIM = _RealPoint_GetIM
467del _RealPoint_GetIM
468def _RealPoint___str__(self):
469    return str(self.Get())
470RealPoint.__str__ = _RealPoint___str__
471del _RealPoint___str__
472def _RealPoint___repr__(self):
473    return "wx.RealPoint"+str(self.Get())
474RealPoint.__repr__ = _RealPoint___repr__
475del _RealPoint___repr__
476def _RealPoint___len__(self):
477    return len(self.Get())
478RealPoint.__len__ = _RealPoint___len__
479del _RealPoint___len__
480def _RealPoint___nonzero__(self):
481    return self.Get() != (0,0)
482RealPoint.__nonzero__ = _RealPoint___nonzero__
483del _RealPoint___nonzero__
484def _RealPoint___bool__(self):
485    return self.Get() != (0,0)
486RealPoint.__bool__ = _RealPoint___bool__
487del _RealPoint___bool__
488def _RealPoint___reduce__(self):
489    return (Rect, self.Get())
490RealPoint.__reduce__ = _RealPoint___reduce__
491del _RealPoint___reduce__
492def _RealPoint___getitem__(self, idx):
493    return self.Get()[idx]
494RealPoint.__getitem__ = _RealPoint___getitem__
495del _RealPoint___getitem__
496def _RealPoint___setitem__(self, idx, val):
497    if idx == 0: self.x = val
498    elif idx == 1: self.y = val
499    else: raise IndexError
500RealPoint.__setitem__ = _RealPoint___setitem__
501del _RealPoint___setitem__
502RealPoint.__safe_for_unpickling__ = True
503
504RealPoint.IM = property(RealPoint.GetIM)
505def _ColourDatabase_FindColour(self, colour):
506    return self.Find(colour)
507ColourDatabase.FindColour = _ColourDatabase_FindColour
508del _ColourDatabase_FindColour
509from collections import namedtuple
510_im_Point = namedtuple('_im_Point', ['x', 'y'])
511del namedtuple
512
513def _PointList___repr__(self):
514    return "PointList: " + repr(list(self))
515PointList.__repr__ = _PointList___repr__
516del _PointList___repr__
517from collections import namedtuple
518_im_Size = namedtuple('_im_Size', ['width', 'height'])
519del namedtuple
520
521from collections import namedtuple
522_im_Rect = namedtuple('_im_Rect', ['x', 'y', 'width', 'height'])
523del namedtuple
524
525from collections import namedtuple
526_im_RealPoint = namedtuple('_im_RealPoint', ['x', 'y'])
527del namedtuple
528
529def _Point2D_GetIM(self):
530    """
531    Returns an immutable representation of the ``wx.Point2D`` object, based on ``namedtuple``.
532
533    This new object is hashable and can be used as a dictionary key,
534    be added to sets, etc.  It can be converted back into a real ``wx.Point2D``
535    with a simple statement like this: ``obj = wx.Point2D(imObj)``.
536    """
537    return _im_Point2D(*self.Get())
538Point2D.GetIM = _Point2D_GetIM
539del _Point2D_GetIM
540def _Point2D___str__(self):
541    return str(self.Get())
542Point2D.__str__ = _Point2D___str__
543del _Point2D___str__
544def _Point2D___repr__(self):
545    return "wx.Point2D"+str(self.Get())
546Point2D.__repr__ = _Point2D___repr__
547del _Point2D___repr__
548def _Point2D___len__(self):
549    return len(self.Get())
550Point2D.__len__ = _Point2D___len__
551del _Point2D___len__
552def _Point2D___nonzero__(self):
553    return self.Get() != (0,0)
554Point2D.__nonzero__ = _Point2D___nonzero__
555del _Point2D___nonzero__
556def _Point2D___bool__(self):
557    return self.Get() != (0,0)
558Point2D.__bool__ = _Point2D___bool__
559del _Point2D___bool__
560def _Point2D___reduce__(self):
561    return (Point2D, self.Get())
562Point2D.__reduce__ = _Point2D___reduce__
563del _Point2D___reduce__
564def _Point2D___getitem__(self, idx):
565    return self.Get()[idx]
566Point2D.__getitem__ = _Point2D___getitem__
567del _Point2D___getitem__
568def _Point2D___setitem__(self, idx, val):
569    if idx == 0: self.x = val
570    elif idx == 1: self.y = val
571    else: raise IndexError
572Point2D.__setitem__ = _Point2D___setitem__
573del _Point2D___setitem__
574Point2D.__safe_for_unpickling__ = True
575
576Point2D.IM = property(Point2D.GetIM)
577def _Rect2D_GetIM(self):
578    """
579    Returns an immutable representation of the ``wx.Rect2D`` object, based on ``namedtuple``.
580
581    This new object is hashable and can be used as a dictionary key,
582    be added to sets, etc.  It can be converted back into a real ``wx.Rect2D``
583    with a simple statement like this: ``obj = wx.Rect2D(imObj)``.
584    """
585    return _im_Rect2D(*self.Get())
586Rect2D.GetIM = _Rect2D_GetIM
587del _Rect2D_GetIM
588def _Rect2D___str__(self):
589    return str(self.Get())
590Rect2D.__str__ = _Rect2D___str__
591del _Rect2D___str__
592def _Rect2D___repr__(self):
593    return "wx.Rect2D"+str(self.Get())
594Rect2D.__repr__ = _Rect2D___repr__
595del _Rect2D___repr__
596def _Rect2D___len__(self):
597    return len(self.Get())
598Rect2D.__len__ = _Rect2D___len__
599del _Rect2D___len__
600def _Rect2D___nonzero__(self):
601    return self.Get() != (0,0,0,0)
602Rect2D.__nonzero__ = _Rect2D___nonzero__
603del _Rect2D___nonzero__
604def _Rect2D___bool__(self):
605    return self.Get() != (0,0,0,0)
606Rect2D.__bool__ = _Rect2D___bool__
607del _Rect2D___bool__
608def _Rect2D___reduce__(self):
609    return (Rect2D, self.Get())
610Rect2D.__reduce__ = _Rect2D___reduce__
611del _Rect2D___reduce__
612def _Rect2D___getitem__(self, idx):
613    return self.Get()[idx]
614Rect2D.__getitem__ = _Rect2D___getitem__
615del _Rect2D___getitem__
616def _Rect2D___setitem__(self, idx, val):
617    if idx == 0: self.x = val
618    elif idx == 1: self.y = val
619    elif idx == 2: self.width = val
620    elif idx == 3: self.height = val
621    else: raise IndexError
622Rect2D.__setitem__ = _Rect2D___setitem__
623del _Rect2D___setitem__
624Rect2D.__safe_for_unpickling__ = True
625
626Rect2D.IM = property(Rect2D.GetIM)
627from collections import namedtuple
628_im_Point2D = namedtuple('_im_Point2D', ['x', 'y'])
629del namedtuple
630
631from collections import namedtuple
632_im_Rect2D = namedtuple('_im_Rect2D', ['x', 'y', 'width', 'height'])
633del namedtuple
634
635def _Position_GetIM(self):
636    """
637    Returns an immutable representation of the ``wx.Position`` object, based on ``namedtuple``.
638
639    This new object is hashable and can be used as a dictionary key,
640    be added to sets, etc.  It can be converted back into a real ``wx.Position``
641    with a simple statement like this: ``obj = wx.Position(imObj)``.
642    """
643    return _im_Position(*self.Get())
644Position.GetIM = _Position_GetIM
645del _Position_GetIM
646def _Position___str__(self):
647    return str(self.Get())
648Position.__str__ = _Position___str__
649del _Position___str__
650def _Position___repr__(self):
651    return "wx.Position"+str(self.Get())
652Position.__repr__ = _Position___repr__
653del _Position___repr__
654def _Position___len__(self):
655    return len(self.Get())
656Position.__len__ = _Position___len__
657del _Position___len__
658def _Position___nonzero__(self):
659    return self.Get() != (0,0)
660Position.__nonzero__ = _Position___nonzero__
661del _Position___nonzero__
662def _Position___bool__(self):
663    return self.Get() != (0,0)
664Position.__bool__ = _Position___bool__
665del _Position___bool__
666def _Position___reduce__(self):
667    return (Position, self.Get())
668Position.__reduce__ = _Position___reduce__
669del _Position___reduce__
670def _Position___getitem__(self, idx):
671    return self.Get()[idx]
672Position.__getitem__ = _Position___getitem__
673del _Position___getitem__
674def _Position___setitem__(self, idx, val):
675    if idx == 0: self.Row = val
676    elif idx == 1: self.Col = val
677    else: raise IndexError
678Position.__setitem__ = _Position___setitem__
679del _Position___setitem__
680Position.__safe_for_unpickling__ = True
681
682Position.IM = property(Position.GetIM)
683from collections import namedtuple
684_im_Position = namedtuple('_im_Position', ['Row', 'Col'])
685del namedtuple
686
687def _Colour_GetIM(self):
688    """
689    Returns an immutable representation of the ``wx.Colour`` object, based on ``namedtuple``.
690
691    This new object is hashable and can be used as a dictionary key,
692    be added to sets, etc.  It can be converted back into a real ``wx.Colour``
693    with a simple statement like this: ``obj = wx.Colour(imObj)``.
694    """
695    return _im_Colour(*self.Get())
696Colour.GetIM = _Colour_GetIM
697del _Colour_GetIM
698def _Colour___str__(self):
699    return str(self.Get())
700Colour.__str__ = _Colour___str__
701del _Colour___str__
702def _Colour___repr__(self):
703    return "wx.Colour"+str(self.Get())
704Colour.__repr__ = _Colour___repr__
705del _Colour___repr__
706def _Colour___len__(self):
707    return len(self.Get())
708Colour.__len__ = _Colour___len__
709del _Colour___len__
710def _Colour___reduce__(self):
711    return (Colour, self.Get())
712Colour.__reduce__ = _Colour___reduce__
713del _Colour___reduce__
714def _Colour___getitem__(self, idx):
715    return self.Get()[idx]
716Colour.__getitem__ = _Colour___getitem__
717del _Colour___getitem__
718def _Colour___setitem__(self, idx, val):
719    if idx == 0:   self.red = val
720    elif idx == 1: self.green = val
721    elif idx == 2: self.blue = val
722    elif idx == 3: self.alpha = val
723    else: raise IndexError
724Colour.__setitem__ = _Colour___setitem__
725del _Colour___setitem__
726Colour.__safe_for_unpickling__ = True
727
728# These stock colours will be initialized when the wx.App object is created.
729BLACK = Colour()
730BLUE = Colour()
731CYAN = Colour()
732GREEN = Colour()
733YELLOW = Colour()
734LIGHT_GREY = Colour()
735RED = Colour()
736WHITE = Colour()
737
738from collections import namedtuple
739_im_Colour = namedtuple('_im_Colour', ['red', 'green', 'blue', 'alpha'])
740del namedtuple
741
742NamedColour = wx.deprecated(Colour, "Use Colour instead.")
743
744ZipFSHandler = wx.deprecated(ArchiveFSHandler, "Use ArchiveFSHandler instead.")
745
746def _Image_ConvertToBitmap(self, depth=-1):
747    """
748    ConvertToBitmap(depth=-1) -> Bitmap
749
750    Convert the image to a :class:`wx.Bitmap`.
751    """
752    bmp = wx.Bitmap(self, depth)
753    return bmp
754Image.ConvertToBitmap = _Image_ConvertToBitmap
755del _Image_ConvertToBitmap
756def _Image_ConvertToMonoBitmap(self, red, green, blue):
757    """
758    ConvertToMonoBitmap(red, green, blue) -> Bitmap
759
760    Creates a monochrome version of the image and returns it as a :class:`wx.Bitmap`.
761    """
762    mono = self.ConvertToMono( red, green, blue )
763    bmp = wx.Bitmap( mono, 1 )
764    return bmp
765Image.ConvertToMonoBitmap = _Image_ConvertToMonoBitmap
766del _Image_ConvertToMonoBitmap
767@wx.deprecatedMsg("Use :class:`Image` instead.")
768def EmptyImage(width=0, height=0, clear=True):
769    """
770    A compatibility wrapper for the wx.Image(width, height) constructor
771    """
772    return Image(width, height, clear)
773
774@wx.deprecatedMsg("Use bitmap.ConvertToImage instead.")
775def ImageFromBitmap(bitmap):
776    """
777    Create a :class:`Image` from a :class:`wx.Bitmap`
778    """
779    return bitmap.ConvertToImage()
780
781@wx.deprecatedMsg("Use :class:`Image` instead.")
782def ImageFromStream(stream, type=BITMAP_TYPE_ANY, index=-1):
783    """
784    Load an image from a stream (file-like object)
785    """
786    return wx.Image(stream, type, index)
787
788@wx.deprecatedMsg("Use :class:`Image` instead.")
789def ImageFromData(width, height, data):
790    """
791    Compatibility wrapper for creating an image from RGB data
792    """
793    return Image(width, height, data)
794
795@wx.deprecatedMsg("Use :class:`Image` instead.")
796def ImageFromDataWithAlpha(width, height, data, alpha):
797    """
798    Compatibility wrapper for creating an image from RGB and Alpha data
799    """
800    return Image(width, height, data, alpha)
801
802def ImageFromBuffer(width, height, dataBuffer, alphaBuffer=None):
803    """
804    Creates a :class:`Image` from the data in `dataBuffer`.  The `dataBuffer`
805    parameter must be a Python object that implements the buffer interface,
806    such as a string, array, etc.  The `dataBuffer` object is expected to
807    contain a series of RGB bytes and be width*height*3 bytes long.  A buffer
808    object can optionally be supplied for the image's alpha channel data, and
809    it is expected to be width*height bytes long.
810
811    The :class:`Image` will be created with its data and alpha pointers initialized
812    to the memory address pointed to by the buffer objects, thus saving the
813    time needed to copy the image data from the buffer object to the :class:`Image`.
814    While this has advantages, it also has the shoot-yourself-in-the-foot
815    risks associated with sharing a C pointer between two objects.
816
817    To help alleviate the risk a reference to the data and alpha buffer
818    objects are kept with the :class:`Image`, so that they won't get deleted until
819    after the wx.Image is deleted.  However please be aware that it is not
820    guaranteed that an object won't move its memory buffer to a new location
821    when it needs to resize its contents.  If that happens then the :class:`Image`
822    will end up referring to an invalid memory location and could cause the
823    application to crash.  Therefore care should be taken to not manipulate
824    the objects used for the data and alpha buffers in a way that would cause
825    them to change size.
826    """
827    img = Image(width, height)
828    img.SetDataBuffer(dataBuffer)
829    if alphaBuffer:
830        img.SetAlphaBuffer(alphaBuffer)
831    img._buffer = dataBuffer
832    img._alpha = alphaBuffer
833    return img
834
835def _ImageArray___repr__(self):
836    return "ImageArray: " + repr(list(self))
837ImageArray.__repr__ = _ImageArray___repr__
838del _ImageArray___repr__
839IMAGE_OPTION_QUALITY = "quality"
840IMAGE_OPTION_FILENAME = "FileName"
841IMAGE_OPTION_RESOLUTION = "Resolution"
842IMAGE_OPTION_RESOLUTIONX = "ResolutionX"
843IMAGE_OPTION_RESOLUTIONY = "ResolutionY"
844IMAGE_OPTION_RESOLUTIONUNIT = "ResolutionUnit"
845IMAGE_OPTION_MAX_WIDTH = "MaxWidth"
846IMAGE_OPTION_MAX_HEIGHT = "MaxHeight"
847IMAGE_OPTION_ORIGINAL_WIDTH = "OriginalWidth"
848IMAGE_OPTION_ORIGINAL_HEIGHT = "OriginalHeight"
849IMAGE_OPTION_BMP_FORMAT = "wxBMP_FORMAT"
850IMAGE_OPTION_CUR_HOTSPOT_X = "HotSpotX"
851IMAGE_OPTION_CUR_HOTSPOT_Y = "HotSpotY"
852IMAGE_OPTION_GIF_COMMENT = "GifComment"
853IMAGE_OPTION_PNG_FORMAT = "PngFormat"
854IMAGE_OPTION_PNG_BITDEPTH = "PngBitDepth"
855IMAGE_OPTION_PNG_FILTER = "PngF"
856IMAGE_OPTION_PNG_COMPRESSION_LEVEL = "PngZL"
857IMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL = "PngZM"
858IMAGE_OPTION_PNG_COMPRESSION_STRATEGY = "PngZS"
859IMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE = "PngZB"
860IMAGE_OPTION_TIFF_BITSPERSAMPLE = "BitsPerSample"
861IMAGE_OPTION_TIFF_SAMPLESPERPIXEL = "SamplesPerPixel"
862IMAGE_OPTION_TIFF_COMPRESSION = "Compression"
863IMAGE_OPTION_TIFF_PHOTOMETRIC = "Photometric"
864IMAGE_OPTION_TIFF_IMAGEDESCRIPTOR = "ImageDescriptor"
865IMAGE_OPTION_TIFF_BITSPERSAMPLE = "BitsPerSample"
866IMAGE_OPTION_TIFF_SAMPLESPERPIXEL = "SamplesPerPixel"
867IMAGE_OPTION_TIFF_COMPRESSION = "Compression"
868IMAGE_OPTION_TIFF_PHOTOMETRIC = "Photometric"
869IMAGE_OPTION_TIFF_IMAGEDESCRIPTOR = "ImageDescriptor"
870IMAGE_OPTION_GIF_COMMENT = "GifComment"
871IMAGE_OPTION_PNG_FORMAT = "PngFormat"
872IMAGE_OPTION_PNG_BITDEPTH = "PngBitDepth"
873IMAGE_OPTION_PNG_FILTER = "PngF"
874IMAGE_OPTION_PNG_COMPRESSION_LEVEL = "PngZL"
875IMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL = "PngZM"
876IMAGE_OPTION_PNG_COMPRESSION_STRATEGY = "PngZS"
877IMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE = "PngZB"
878
879@wx.deprecatedMsg("Use :meth:`wx.Bitmap.FromBuffer` or :meth:`wx.Bitmap.FromBufferAndAlpha` instead.")
880def BitmapFromBuffer(width, height, dataBuffer, alphaBuffer=None):
881    """
882    A compatibility wrapper for :meth:`wx.Bitmap.FromBuffer` and :meth:`wx.Bitmap.FromBufferAndAlpha`
883    """
884    if alphaBuffer is not None:
885        return Bitmap.FromBufferAndAlpha(width, height, dataBuffer, alphaBuffer)
886    else:
887        return Bitmap.FromBuffer(width, height, dataBuffer)
888
889@wx.deprecatedMsg("Use :meth:`wx.Bitmap.FromBufferRGBA` instead.")
890def BitmapFromBufferRGBA(width, height, dataBuffer):
891    """
892    A compatibility wrapper for :meth:`wx.Bitmap.FromBufferRGBA`
893    """
894    return Bitmap.FromBufferRGBA(width, height, dataBuffer)
895
896@wx.deprecatedMsg("Use :meth:`wx.Bitmap.FromRGBA` instead.")
897def EmptyBitmapRGBA(width, height, red=0, green=0, blue=0, alpha=0):
898    """
899    A compatibility wrapper for :meth:`wx.Bitmap.FromRGBA`
900    """
901    return Bitmap.FromRGBA(width, height, red, green, blue, alpha)
902
903@wx.deprecatedMsg("Use :class:`wx.Bitmap` instead")
904def EmptyBitmap(width, height, depth=BITMAP_SCREEN_DEPTH):
905    """
906    A compatibility wrapper for the wx.Bitmap(width, height, depth) constructor
907    """
908    return Bitmap(width, height, depth)
909
910@wx.deprecatedMsg("Use :class:`wx.Bitmap` instead")
911def BitmapFromImage(image):
912    """
913    A compatibility wrapper for the wx.Bitmap(wx.Image) constructor
914    """
915    return Bitmap(image)
916
917@wx.deprecatedMsg("Use :class:`Icon` instead")
918def EmptyIcon():
919    """
920    A compatibility wrapper for the :class:`Icon` constructor
921    """
922    return Icon()
923
924def _Font_SetNoAntiAliasing(self, no=True):
925    pass
926Font.SetNoAntiAliasing = wx.deprecated(_Font_SetNoAntiAliasing)
927del _Font_SetNoAntiAliasing
928def _Font_GetNoAntiAliasing(self):
929    pass
930Font.GetNoAntiAliasing = wx.deprecated(_Font_GetNoAntiAliasing)
931del _Font_GetNoAntiAliasing
932# These stock fonts will be initialized when the wx.App object is created.
933NORMAL_FONT = Font()
934SMALL_FONT = Font()
935ITALIC_FONT = Font()
936SWISS_FONT = Font()
937
938wx.DEFAULT    = int(wx.FONTFAMILY_DEFAULT)
939wx.DECORATIVE = int(wx.FONTFAMILY_DECORATIVE)
940wx.ROMAN      = int(wx.FONTFAMILY_ROMAN)
941wx.SCRIPT     = int(wx.FONTFAMILY_SCRIPT)
942wx.SWISS      = int(wx.FONTFAMILY_SWISS)
943wx.MODERN     = int(wx.FONTFAMILY_MODERN)
944wx.TELETYPE   = int(wx.FONTFAMILY_TELETYPE)
945
946wx.NORMAL = int(wx.FONTWEIGHT_NORMAL)
947wx.LIGHT  = int(wx.FONTWEIGHT_LIGHT)
948wx.BOLD   = int(wx.FONTWEIGHT_BOLD)
949
950wx.NORMAL = int(wx.FONTSTYLE_NORMAL)
951wx.ITALIC = int(wx.FONTSTYLE_ITALIC)
952wx.SLANT  = int(wx.FONTSTYLE_SLANT)
953
954# These stock pens will be initialized when the wx.App object is created.
955RED_PEN = Pen()
956BLUE_PEN = Pen()
957CYAN_PEN = Pen()
958GREEN_PEN = Pen()
959YELLOW_PEN = Pen()
960BLACK_PEN = Pen()
961WHITE_PEN = Pen()
962TRANSPARENT_PEN = Pen()
963BLACK_DASHED_PEN = Pen()
964GREY_PEN = Pen()
965MEDIUM_GREY_PEN = Pen()
966LIGHT_GREY_PEN = Pen()
967
968wx.SOLID       = int(wx.PENSTYLE_SOLID)
969wx.DOT         = int(wx.PENSTYLE_DOT)
970wx.LONG_DASH   = int(wx.PENSTYLE_LONG_DASH)
971wx.SHORT_DASH  = int(wx.PENSTYLE_SHORT_DASH)
972wx.DOT_DASH    = int(wx.PENSTYLE_DOT_DASH)
973wx.USER_DASH   = int(wx.PENSTYLE_USER_DASH)
974wx.TRANSPARENT = int(wx.PENSTYLE_TRANSPARENT)
975
976# These stock brushes will be initialized when the wx.App object is created.
977BLUE_BRUSH = Brush()
978GREEN_BRUSH = Brush()
979YELLOW_BRUSH = Brush()
980WHITE_BRUSH = Brush()
981BLACK_BRUSH = Brush()
982GREY_BRUSH = Brush()
983MEDIUM_GREY_BRUSH = Brush()
984LIGHT_GREY_BRUSH = Brush()
985TRANSPARENT_BRUSH = Brush()
986CYAN_BRUSH = Brush()
987RED_BRUSH = Brush()
988
989wx.STIPPLE_MASK_OPAQUE = int(wx.BRUSHSTYLE_STIPPLE_MASK_OPAQUE)
990wx.STIPPLE_MASK        = int(wx.BRUSHSTYLE_STIPPLE_MASK)
991wx.STIPPLE             = int(wx.BRUSHSTYLE_STIPPLE)
992wx.BDIAGONAL_HATCH     = int(wx.BRUSHSTYLE_BDIAGONAL_HATCH)
993wx.CROSSDIAG_HATCH     = int(wx.BRUSHSTYLE_CROSSDIAG_HATCH)
994wx.FDIAGONAL_HATCH     = int(wx.BRUSHSTYLE_FDIAGONAL_HATCH)
995wx.CROSS_HATCH         = int(wx.BRUSHSTYLE_CROSS_HATCH)
996wx.HORIZONTAL_HATCH    = int(wx.BRUSHSTYLE_HORIZONTAL_HATCH)
997wx.VERTICAL_HATCH      = int(wx.BRUSHSTYLE_VERTICAL_HATCH)
998
999# These stock cursors will be initialized when the wx.App object is created.
1000STANDARD_CURSOR = Cursor()
1001HOURGLASS_CURSOR = Cursor()
1002CROSS_CURSOR = Cursor()
1003
1004StockCursor = wx.deprecated(Cursor, "Use Cursor instead.")
1005
1006CursorFromImage = wx.deprecated(Cursor, "Use Cursor instead.")
1007
1008def _Region___iter__(self):
1009    """
1010    Returns a rectangle interator conforming to the Python iterator
1011    protocol.
1012    """
1013    return PyRegionIterator(self)
1014Region.__iter__ = _Region___iter__
1015del _Region___iter__
1016class PyRegionIterator(object):
1017    "A Python iterator for wx.Region objects"
1018    def __init__(self, region):
1019        self._region = region
1020        self._iterator = wx.RegionIterator(region)
1021    def next(self):
1022        if not self._iterator:
1023            raise StopIteration
1024        rect = self._iterator.GetRect()
1025        if self._iterator.HaveRects():
1026            self._iterator.Next()
1027        return rect
1028    __next__ = next  # for Python 3
1029
1030def _DC_GetClippingRect(self):
1031    """
1032    Gets the rectangle surrounding the current clipping region
1033    """
1034    return wx.Rect(*self.GetClippingBox())
1035DC.GetClippingRect = _DC_GetClippingRect
1036del _DC_GetClippingRect
1037DC.DrawImageLabel = wx.deprecated(DC.DrawLabel, "Use DrawLabel instead.")
1038
1039def _DC_GetBoundingBox(self):
1040    """
1041    GetBoundingBox() -> (x1,y1, x2,y2)
1042
1043    Returns the min and max points used in drawing commands so far.
1044    """
1045    return (self.MinX(), self.MinY(), self.MaxX(), self.MaxY())
1046DC.GetBoundingBox = _DC_GetBoundingBox
1047del _DC_GetBoundingBox
1048DC.GetHDC = wx.deprecated(DC.GetHDC, "Use GetHandle instead.")
1049
1050DC.GetCGContext = wx.deprecated(DC.GetCGContext, "Use GetHandle instead.")
1051
1052DC.GetGdkDrawable = wx.deprecated(DC.GetGdkDrawable, "Use GetHandle instead.")
1053
1054def _DC___enter__(self):
1055    return self
1056DC.__enter__ = _DC___enter__
1057del _DC___enter__
1058def _DC___exit__(self, exc_type, exc_val, exc_tb):
1059    self.Destroy()
1060DC.__exit__ = _DC___exit__
1061del _DC___exit__
1062def _DC_DrawPointList(self, points, pens=None):
1063    """
1064    Draw a list of points as quickly as possible.
1065
1066    :param points: A sequence of 2-element sequences representing
1067                   each point to draw, (x,y).
1068    :param pens:   If None, then the current pen is used.  If a single
1069                   pen then it will be used for all points.  If a list of
1070                   pens then there should be one for each point in points.
1071    """
1072    if pens is None:
1073        pens = []
1074    elif isinstance(pens, wx.Pen):
1075        pens = [pens]
1076    elif len(pens) != len(points):
1077        raise ValueError('points and pens must have same length')
1078    return self._DrawPointList(points, pens, [])
1079DC.DrawPointList = _DC_DrawPointList
1080del _DC_DrawPointList
1081def _DC_DrawLineList(self, lines, pens=None):
1082    """
1083    Draw a list of lines as quickly as possible.
1084
1085    :param lines: A sequence of 4-element sequences representing
1086                  each line to draw, (x1,y1, x2,y2).
1087    :param pens:  If None, then the current pen is used.  If a
1088                  single pen then it will be used for all lines.  If
1089                  a list of pens then there should be one for each line
1090                  in lines.
1091    """
1092    if pens is None:
1093        pens = []
1094    elif isinstance(pens, wx.Pen):
1095        pens = [pens]
1096    elif len(pens) != len(lines):
1097        raise ValueError('lines and pens must have same length')
1098    return self._DrawLineList(lines, pens, [])
1099DC.DrawLineList = _DC_DrawLineList
1100del _DC_DrawLineList
1101def _DC_DrawRectangleList(self, rectangles, pens=None, brushes=None):
1102    """
1103    Draw a list of rectangles as quickly as possible.
1104
1105    :param rectangles: A sequence of 4-element sequences representing
1106                       each rectangle to draw, (x,y, w,h).
1107    :param pens:       If None, then the current pen is used.  If a
1108                       single pen then it will be used for all rectangles.
1109                       If a list of pens then there should be one for each
1110                       rectangle in rectangles.
1111    :param brushes:    A brush or brushes to be used to fill the rectagles,
1112                       with similar semantics as the pens parameter.
1113    """
1114    if pens is None:
1115        pens = []
1116    elif isinstance(pens, wx.Pen):
1117        pens = [pens]
1118    elif len(pens) != len(rectangles):
1119        raise ValueError('rectangles and pens must have same length')
1120    if brushes is None:
1121        brushes = []
1122    elif isinstance(brushes, wx.Brush):
1123        brushes = [brushes]
1124    elif len(brushes) != len(rectangles):
1125        raise ValueError('rectangles and brushes must have same length')
1126    return self._DrawRectangleList(rectangles, pens, brushes)
1127DC.DrawRectangleList = _DC_DrawRectangleList
1128del _DC_DrawRectangleList
1129def _DC_DrawEllipseList(self, ellipses, pens=None, brushes=None):
1130    """
1131    Draw a list of ellipses as quickly as possible.
1132
1133    :param ellipses: A sequence of 4-element sequences representing
1134                     each ellipse to draw, (x,y, w,h).
1135    :param pens:     If None, then the current pen is used.  If a
1136                     single pen then it will be used for all ellipses.
1137                     If a list of pens then there should be one for each
1138                     ellipse in ellipses.
1139    :param brushes:  A brush or brushes to be used to fill the ellipses,
1140                     with similar semantics as the pens parameter.
1141    """
1142    if pens is None:
1143        pens = []
1144    elif isinstance(pens, wx.Pen):
1145        pens = [pens]
1146    elif len(pens) != len(ellipses):
1147        raise ValueError('ellipses and pens must have same length')
1148    if brushes is None:
1149        brushes = []
1150    elif isinstance(brushes, wx.Brush):
1151        brushes = [brushes]
1152    elif len(brushes) != len(ellipses):
1153        raise ValueError('ellipses and brushes must have same length')
1154    return self._DrawEllipseList(ellipses, pens, brushes)
1155DC.DrawEllipseList = _DC_DrawEllipseList
1156del _DC_DrawEllipseList
1157def _DC_DrawPolygonList(self, polygons, pens=None, brushes=None):
1158    """
1159    Draw a list of polygons, each of which is a list of points.
1160
1161    :param polygons: A sequence of sequences of sequences.
1162                     [[(x1,y1),(x2,y2),(x3,y3)...], [(x1,y1),(x2,y2),(x3,y3)...]]
1163
1164    :param pens:     If None, then the current pen is used.  If a
1165                     single pen then it will be used for all polygons.
1166                     If a list of pens then there should be one for each
1167                     polygon.
1168    :param brushes:  A brush or brushes to be used to fill the polygons,
1169                     with similar semantics as the pens parameter.
1170    """
1171    if pens is None:
1172        pens = []
1173    elif isinstance(pens, wx.Pen):
1174        pens = [pens]
1175    elif len(pens) != len(polygons):
1176        raise ValueError('polygons and pens must have same length')
1177    if brushes is None:
1178        brushes = []
1179    elif isinstance(brushes, wx.Brush):
1180        brushes = [brushes]
1181    elif len(brushes) != len(polygons):
1182        raise ValueError('polygons and brushes must have same length')
1183    return self._DrawPolygonList(polygons, pens, brushes)
1184DC.DrawPolygonList = _DC_DrawPolygonList
1185del _DC_DrawPolygonList
1186def _DC_DrawTextList(self, textList, coords, foregrounds=None, backgrounds=None):
1187    """
1188    Draw a list of strings using a list of coordinants for positioning each string.
1189
1190    :param textList:    A list of strings
1191    :param coords:      A list of (x,y) positions
1192    :param foregrounds: A list of `wx.Colour` objects to use for the
1193                        foregrounds of the strings.
1194    :param backgrounds: A list of `wx.Colour` objects to use for the
1195                        backgrounds of the strings.
1196
1197    NOTE: Make sure you set background mode to wx.Solid (DC.SetBackgroundMode)
1198          If you want backgrounds to do anything.
1199    """
1200    if type(textList) == type(''):
1201        textList = [textList]
1202    elif len(textList) != len(coords):
1203        raise ValueError('textlist and coords must have same length')
1204    if foregrounds is None:
1205        foregrounds = []
1206    elif isinstance(foregrounds, wx.Colour):
1207        foregrounds = [foregrounds]
1208    elif len(foregrounds) != len(coords):
1209        raise ValueError('foregrounds and coords must have same length')
1210    if backgrounds is None:
1211        backgrounds = []
1212    elif isinstance(backgrounds, wx.Colour):
1213        backgrounds = [backgrounds]
1214    elif len(backgrounds) != len(coords):
1215        raise ValueError('backgrounds and coords must have same length')
1216    return  self._DrawTextList(textList, coords, foregrounds, backgrounds)
1217DC.DrawTextList = _DC_DrawTextList
1218del _DC_DrawTextList
1219DC.BoundingBox = property(DC.GetBoundingBox)
1220DC.ClippingRect = property(DC.GetClippingRect)
1221def _DCClipper___enter__(self):
1222    return self
1223DCClipper.__enter__ = _DCClipper___enter__
1224del _DCClipper___enter__
1225def _DCClipper___exit__(self, exc_type, exc_val, exc_tb):
1226    return False
1227DCClipper.__exit__ = _DCClipper___exit__
1228del _DCClipper___exit__
1229def _DCBrushChanger___enter__(self):
1230    return self
1231DCBrushChanger.__enter__ = _DCBrushChanger___enter__
1232del _DCBrushChanger___enter__
1233def _DCBrushChanger___exit__(self, exc_type, exc_val, exc_tb):
1234    return False
1235DCBrushChanger.__exit__ = _DCBrushChanger___exit__
1236del _DCBrushChanger___exit__
1237def _DCPenChanger___enter__(self):
1238    return self
1239DCPenChanger.__enter__ = _DCPenChanger___enter__
1240del _DCPenChanger___enter__
1241def _DCPenChanger___exit__(self, exc_type, exc_val, exc_tb):
1242    return False
1243DCPenChanger.__exit__ = _DCPenChanger___exit__
1244del _DCPenChanger___exit__
1245def _DCTextColourChanger___enter__(self):
1246    return self
1247DCTextColourChanger.__enter__ = _DCTextColourChanger___enter__
1248del _DCTextColourChanger___enter__
1249def _DCTextColourChanger___exit__(self, exc_type, exc_val, exc_tb):
1250    return False
1251DCTextColourChanger.__exit__ = _DCTextColourChanger___exit__
1252del _DCTextColourChanger___exit__
1253def _DCFontChanger___enter__(self):
1254    return self
1255DCFontChanger.__enter__ = _DCFontChanger___enter__
1256del _DCFontChanger___enter__
1257def _DCFontChanger___exit__(self, exc_type, exc_val, exc_tb):
1258    return False
1259DCFontChanger.__exit__ = _DCFontChanger___exit__
1260del _DCFontChanger___exit__
1261GraphicsContext.DrawRotatedText = wx.deprecated(GraphicsContext.DrawText, 'Use DrawText instead.')
1262
1263def _PixelDataBase___iter__(self):
1264    """
1265    Create and return an iterator/generator object for traversing
1266    this pixel data object.
1267    """
1268    width  = self.GetWidth()
1269    height = self.GetHeight()
1270    pixels = self.GetPixels() # this is the C++ iterator
1271
1272    # This class is a facade over the pixels object (using the one
1273    # in the enclosing scope) that only allows Get() and Set() to
1274    # be called.
1275    class PixelFacade(object):
1276        def Get(self):
1277            return pixels.Get()
1278        def Set(self, *args, **kw):
1279            return pixels.Set(*args, **kw)
1280        def __str__(self):
1281            return str(self.Get())
1282        def __repr__(self):
1283            return 'pixel(%d,%d): %s' % (x,y,self.Get())
1284        X = property(lambda self: x)
1285        Y = property(lambda self: y)
1286
1287    import sys
1288    rangeFunc = range if sys.version_info >= (3,) else xrange
1289
1290    pf = PixelFacade()
1291    for y in rangeFunc(height):
1292        pixels.MoveTo(self, 0, y)
1293        for x in rangeFunc(width):
1294            # We always generate the same pf instance, but it
1295            # accesses the pixels object which we use to iterate
1296            # over the pixel buffer.
1297            yield pf
1298            pixels.nextPixel()
1299PixelDataBase.__iter__ = _PixelDataBase___iter__
1300del _PixelDataBase___iter__
1301@wx.deprecated
1302def GetAccelFromString(label):
1303    accel = wx.AcceleratorEntry()
1304    accel.FromString(label)
1305    return accel
1306
1307def CustomDataFormat(format):
1308    return wx.DataFormat(format)
1309CustomDataFormat = wx.deprecated(CustomDataFormat, "Use wx.DataFormat instead.")
1310
1311PyDataObjectSimple = wx.deprecated(DataObjectSimple), 'Use DataObjectSimple instead.'
1312
1313PyTextDataObject = wx.deprecated(TextDataObject, 'Use TextDataObject instead.')
1314
1315PyBitmapDataObject = wx.deprecated(BitmapDataObject, 'Use TextDataObject instead.')
1316
1317PyDropTarget = wx.deprecated(DropTarget, 'Use DropTarget instead.')
1318
1319# Since wxTheClipboard is not really a global variable (it is a macro
1320# that calls the Get static method) we can't declare it as a global
1321# variable for the wrapper generator, otherwise it will try to run the
1322# function at module import and the wxApp object won't exist yet.  So
1323# we'll use a class that will allow us to delay calling the Get until
1324# wx.TheClipboard is actually being used for the first time.
1325class _wxPyDelayedInitWrapper(object):
1326    def __init__(self, initfunc, *args, **kwargs):
1327        self._initfunc = initfunc
1328        self._args = args
1329        self._kwargs = kwargs
1330        self._instance = None
1331    def _checkInstance(self):
1332        if self._instance is None:
1333            if wx.GetApp():
1334                self._instance = self._initfunc(*self._args, **self._kwargs)
1335    def __getattr__(self, name):
1336        self._checkInstance()
1337        return getattr(self._instance, name)
1338    def __repr__(self):
1339        self._checkInstance()
1340        return repr(self._instance)
1341
1342    # context manager methods
1343    def __enter__(self):
1344        self._checkInstance()
1345        if not self.Open():
1346            raise RuntimeError('Unable to open clipboard.')
1347        return self
1348    def __exit__(self, exc_type, exc_val, exc_tb):
1349        self.Close()
1350
1351TheClipboard = _wxPyDelayedInitWrapper(Clipboard.Get)
1352
1353def _ConfigBase_ReadInt(self, key, defaultVal=0):
1354    import six
1355    rv = self._cpp_ReadInt(key, defaultVal)
1356    if six.PY2:
1357        rv = int(rv)
1358    return rv
1359ConfigBase.ReadInt = _ConfigBase_ReadInt
1360del _ConfigBase_ReadInt
1361def _ConfigPathChanger___enter__(self):
1362    return self
1363ConfigPathChanger.__enter__ = _ConfigPathChanger___enter__
1364del _ConfigPathChanger___enter__
1365def _ConfigPathChanger___exit__(self, exc_type, exc_val, exc_tb):
1366    return False
1367ConfigPathChanger.__exit__ = _ConfigPathChanger___exit__
1368del _ConfigPathChanger___exit__
1369# For 2.8 compatibility
1370KeyboardState.m_controlDown = wx.deprecated(KeyboardState.controlDown, "Use controlDown instead.")
1371KeyboardState.m_shiftDown   = wx.deprecated(KeyboardState.shiftDown, "Use shiftDown instead.")
1372KeyboardState.m_altDown     = wx.deprecated(KeyboardState.altDown, "Use altDown instead.")
1373KeyboardState.m_metaDown    = wx.deprecated(KeyboardState.metaDown, "Use metaDown instead.")
1374
1375def _EvtHandler_Bind(self, event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY):
1376    """
1377    Bind an event to an event handler.
1378
1379    :param event: One of the ``EVT_*`` event binder objects that
1380                  specifies the type of event to bind.
1381
1382    :param handler: A callable object to be invoked when the
1383                    event is delivered to self.  Pass ``None`` to
1384                    disconnect an event handler.
1385
1386    :param source: Sometimes the event originates from a
1387                   different window than self, but you still
1388                   want to catch it in self.  (For example, a
1389                   button event delivered to a frame.)  By
1390                   passing the source of the event, the event
1391                   handling system is able to differentiate
1392                   between the same event type from different
1393                   controls.
1394
1395    :param id: Used to spcify the event source by ID instead
1396               of instance.
1397
1398    :param id2: Used when it is desirable to bind a handler
1399                to a range of IDs, such as with EVT_MENU_RANGE.
1400    """
1401    assert isinstance(event, wx.PyEventBinder)
1402    assert callable(handler) or handler is None
1403    assert source is None or hasattr(source, 'GetId')
1404    if source is not None:
1405        id  = source.GetId()
1406    event.Bind(self, id, id2, handler)
1407EvtHandler.Bind = _EvtHandler_Bind
1408del _EvtHandler_Bind
1409def _EvtHandler_Unbind(self, event, source=None, id=wx.ID_ANY, id2=wx.ID_ANY, handler=None):
1410    """
1411    Disconnects the event handler binding for event from `self`.
1412    Returns ``True`` if successful.
1413    """
1414    if source is not None:
1415        id  = source.GetId()
1416    return event.Unbind(self, id, id2, handler)
1417EvtHandler.Unbind = _EvtHandler_Unbind
1418del _EvtHandler_Unbind
1419def _EventBlocker___enter__(self):
1420    return self
1421EventBlocker.__enter__ = _EventBlocker___enter__
1422del _EventBlocker___enter__
1423def _EventBlocker___exit__(self, exc_type, exc_val, exc_tb):
1424    return False
1425EventBlocker.__exit__ = _EventBlocker___exit__
1426del _EventBlocker___exit__
1427def _PropagationDisabler___enter__(self):
1428    return self
1429PropagationDisabler.__enter__ = _PropagationDisabler___enter__
1430del _PropagationDisabler___enter__
1431def _PropagationDisabler___exit__(self, exc_type, exc_val, exc_tb):
1432    return False
1433PropagationDisabler.__exit__ = _PropagationDisabler___exit__
1434del _PropagationDisabler___exit__
1435def _PropagateOnce___enter__(self):
1436    return self
1437PropagateOnce.__enter__ = _PropagateOnce___enter__
1438del _PropagateOnce___enter__
1439def _PropagateOnce___exit__(self, exc_type, exc_val, exc_tb):
1440    return False
1441PropagateOnce.__exit__ = _PropagateOnce___exit__
1442del _PropagateOnce___exit__
1443def _CommandEvent_GetClientObject(self):
1444    """
1445    Alias for :meth:`GetClientData`
1446    """
1447    return self.GetClientData()
1448CommandEvent.GetClientObject = _CommandEvent_GetClientObject
1449del _CommandEvent_GetClientObject
1450def _CommandEvent_SetClientObject(self, data):
1451    """
1452    Alias for :meth:`SetClientData`
1453    """
1454    self.SetClientData(data)
1455CommandEvent.SetClientObject = _CommandEvent_SetClientObject
1456del _CommandEvent_SetClientObject
1457CommandEvent.ClientData = property(CommandEvent.GetClientData, CommandEvent.SetClientData)
1458class PyEventBinder(object):
1459    """
1460    Instances of this class are used to bind specific events to event handlers.
1461    """
1462    def __init__(self, evtType, expectedIDs=0):
1463        if expectedIDs not in [0, 1, 2]:
1464            raise ValueError("Invalid number of expectedIDs")
1465        self.expectedIDs = expectedIDs
1466
1467        if isinstance(evtType, (list, tuple)):
1468            self.evtType = list(evtType)
1469        else:
1470            self.evtType = [evtType]
1471
1472    def Bind(self, target, id1, id2, function):
1473        """
1474        Bind this set of event types to target using its Connect() method.
1475        """
1476        for et in self.evtType:
1477            target.Connect(id1, id2, et, function)
1478
1479    def Unbind(self, target, id1, id2, handler=None):
1480        """
1481        Remove an event binding.
1482        """
1483        success = 0
1484        for et in self.evtType:
1485            success += int(target.Disconnect(id1, id2, et, handler))
1486        return success != 0
1487
1488    def _getEvtType(self):
1489        """
1490        Make it easy to get to the default wxEventType typeID for this
1491        event binder.
1492        """
1493        return self.evtType[0]
1494
1495    typeId = property(_getEvtType)
1496    @wx.deprecatedMsg("Use :meth:`EvtHandler.Bind` instead.")
1497    def __call__(self, *args):
1498        """
1499        For backwards compatibility with the old ``EVT_*`` functions.
1500        Should be called with either (window, func), (window, ID,
1501        func) or (window, ID1, ID2, func) parameters depending on the
1502        type of the event.
1503        """
1504        assert len(args) == 2 + self.expectedIDs
1505        id1 = ID_ANY
1506        id2 = ID_ANY
1507        target = args[0]
1508        if self.expectedIDs == 0:
1509            func = args[1]
1510        elif self.expectedIDs == 1:
1511            id1 = args[1]
1512            func = args[2]
1513        elif self.expectedIDs == 2:
1514            id1 = args[1]
1515            id2 = args[2]
1516            func = args[3]
1517        else:
1518            raise ValueError("Unexpected number of IDs")
1519
1520        self.Bind(target, id1, id2, func)
1521
1522
1523#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
1524# This code block was included from src/event_ex.py
1525# Create some event binders
1526EVT_SIZE = wx.PyEventBinder( wxEVT_SIZE )
1527EVT_SIZING = wx.PyEventBinder( wxEVT_SIZING )
1528EVT_MOVE = wx.PyEventBinder( wxEVT_MOVE )
1529EVT_MOVING = wx.PyEventBinder( wxEVT_MOVING )
1530EVT_MOVE_START = wx.PyEventBinder( wxEVT_MOVE_START )
1531EVT_MOVE_END = wx.PyEventBinder( wxEVT_MOVE_END )
1532EVT_CLOSE = wx.PyEventBinder( wxEVT_CLOSE_WINDOW )
1533EVT_END_SESSION = wx.PyEventBinder( wxEVT_END_SESSION )
1534EVT_QUERY_END_SESSION = wx.PyEventBinder( wxEVT_QUERY_END_SESSION )
1535EVT_PAINT = wx.PyEventBinder( wxEVT_PAINT )
1536EVT_NC_PAINT = wx.PyEventBinder( wxEVT_NC_PAINT )
1537EVT_ERASE_BACKGROUND = wx.PyEventBinder( wxEVT_ERASE_BACKGROUND )
1538EVT_CHAR = wx.PyEventBinder( wxEVT_CHAR )
1539EVT_KEY_DOWN = wx.PyEventBinder( wxEVT_KEY_DOWN )
1540EVT_KEY_UP = wx.PyEventBinder( wxEVT_KEY_UP )
1541EVT_HOTKEY = wx.PyEventBinder( wxEVT_HOTKEY, 1)
1542EVT_CHAR_HOOK = wx.PyEventBinder( wxEVT_CHAR_HOOK )
1543EVT_MENU_OPEN = wx.PyEventBinder( wxEVT_MENU_OPEN )
1544EVT_MENU_CLOSE = wx.PyEventBinder( wxEVT_MENU_CLOSE )
1545EVT_MENU_HIGHLIGHT = wx.PyEventBinder( wxEVT_MENU_HIGHLIGHT, 1)
1546EVT_MENU_HIGHLIGHT_ALL = wx.PyEventBinder( wxEVT_MENU_HIGHLIGHT )
1547EVT_SET_FOCUS = wx.PyEventBinder( wxEVT_SET_FOCUS )
1548EVT_KILL_FOCUS = wx.PyEventBinder( wxEVT_KILL_FOCUS )
1549EVT_CHILD_FOCUS = wx.PyEventBinder( wxEVT_CHILD_FOCUS )
1550EVT_ACTIVATE = wx.PyEventBinder( wxEVT_ACTIVATE )
1551EVT_ACTIVATE_APP = wx.PyEventBinder( wxEVT_ACTIVATE_APP )
1552EVT_HIBERNATE = wx.PyEventBinder( wxEVT_HIBERNATE )
1553EVT_DROP_FILES = wx.PyEventBinder( wxEVT_DROP_FILES )
1554EVT_INIT_DIALOG = wx.PyEventBinder( wxEVT_INIT_DIALOG )
1555EVT_SYS_COLOUR_CHANGED = wx.PyEventBinder( wxEVT_SYS_COLOUR_CHANGED )
1556EVT_DISPLAY_CHANGED = wx.PyEventBinder( wxEVT_DISPLAY_CHANGED )
1557EVT_SHOW = wx.PyEventBinder( wxEVT_SHOW )
1558EVT_MAXIMIZE = wx.PyEventBinder( wxEVT_MAXIMIZE )
1559EVT_ICONIZE = wx.PyEventBinder( wxEVT_ICONIZE )
1560EVT_NAVIGATION_KEY = wx.PyEventBinder( wxEVT_NAVIGATION_KEY )
1561EVT_PALETTE_CHANGED = wx.PyEventBinder( wxEVT_PALETTE_CHANGED )
1562EVT_QUERY_NEW_PALETTE = wx.PyEventBinder( wxEVT_QUERY_NEW_PALETTE )
1563EVT_WINDOW_CREATE = wx.PyEventBinder( wxEVT_CREATE )
1564EVT_WINDOW_DESTROY = wx.PyEventBinder( wxEVT_DESTROY )
1565EVT_SET_CURSOR = wx.PyEventBinder( wxEVT_SET_CURSOR )
1566EVT_MOUSE_CAPTURE_CHANGED = wx.PyEventBinder( wxEVT_MOUSE_CAPTURE_CHANGED )
1567EVT_MOUSE_CAPTURE_LOST = wx.PyEventBinder( wxEVT_MOUSE_CAPTURE_LOST )
1568
1569EVT_LEFT_DOWN = wx.PyEventBinder( wxEVT_LEFT_DOWN )
1570EVT_LEFT_UP = wx.PyEventBinder( wxEVT_LEFT_UP )
1571EVT_MIDDLE_DOWN = wx.PyEventBinder( wxEVT_MIDDLE_DOWN )
1572EVT_MIDDLE_UP = wx.PyEventBinder( wxEVT_MIDDLE_UP )
1573EVT_RIGHT_DOWN = wx.PyEventBinder( wxEVT_RIGHT_DOWN )
1574EVT_RIGHT_UP = wx.PyEventBinder( wxEVT_RIGHT_UP )
1575EVT_MOTION = wx.PyEventBinder( wxEVT_MOTION )
1576EVT_LEFT_DCLICK = wx.PyEventBinder( wxEVT_LEFT_DCLICK )
1577EVT_MIDDLE_DCLICK = wx.PyEventBinder( wxEVT_MIDDLE_DCLICK )
1578EVT_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_RIGHT_DCLICK )
1579EVT_LEAVE_WINDOW = wx.PyEventBinder( wxEVT_LEAVE_WINDOW )
1580EVT_ENTER_WINDOW = wx.PyEventBinder( wxEVT_ENTER_WINDOW )
1581EVT_MOUSEWHEEL = wx.PyEventBinder( wxEVT_MOUSEWHEEL )
1582EVT_MOUSE_AUX1_DOWN = wx.PyEventBinder( wxEVT_AUX1_DOWN )
1583EVT_MOUSE_AUX1_UP = wx.PyEventBinder( wxEVT_AUX1_UP )
1584EVT_MOUSE_AUX1_DCLICK = wx.PyEventBinder( wxEVT_AUX1_DCLICK )
1585EVT_MOUSE_AUX2_DOWN = wx.PyEventBinder( wxEVT_AUX2_DOWN )
1586EVT_MOUSE_AUX2_UP = wx.PyEventBinder( wxEVT_AUX2_UP )
1587EVT_MOUSE_AUX2_DCLICK = wx.PyEventBinder( wxEVT_AUX2_DCLICK )
1588
1589EVT_MOUSE_EVENTS = wx.PyEventBinder([ wxEVT_LEFT_DOWN,
1590                                      wxEVT_LEFT_UP,
1591                                      wxEVT_MIDDLE_DOWN,
1592                                      wxEVT_MIDDLE_UP,
1593                                      wxEVT_RIGHT_DOWN,
1594                                      wxEVT_RIGHT_UP,
1595                                      wxEVT_MOTION,
1596                                      wxEVT_LEFT_DCLICK,
1597                                      wxEVT_MIDDLE_DCLICK,
1598                                      wxEVT_RIGHT_DCLICK,
1599                                      wxEVT_ENTER_WINDOW,
1600                                      wxEVT_LEAVE_WINDOW,
1601                                      wxEVT_MOUSEWHEEL,
1602                                      wxEVT_AUX1_DOWN,
1603                                      wxEVT_AUX1_UP,
1604                                      wxEVT_AUX1_DCLICK,
1605                                      wxEVT_AUX2_DOWN,
1606                                      wxEVT_AUX2_UP,
1607                                      wxEVT_AUX2_DCLICK,
1608                                     ])
1609
1610
1611# Scrolling from wxWindow (sent to wxScrolledWindow)
1612EVT_SCROLLWIN = wx.PyEventBinder([ wxEVT_SCROLLWIN_TOP,
1613                                  wxEVT_SCROLLWIN_BOTTOM,
1614                                  wxEVT_SCROLLWIN_LINEUP,
1615                                  wxEVT_SCROLLWIN_LINEDOWN,
1616                                  wxEVT_SCROLLWIN_PAGEUP,
1617                                  wxEVT_SCROLLWIN_PAGEDOWN,
1618                                  wxEVT_SCROLLWIN_THUMBTRACK,
1619                                  wxEVT_SCROLLWIN_THUMBRELEASE,
1620                                  ])
1621
1622EVT_SCROLLWIN_TOP = wx.PyEventBinder( wxEVT_SCROLLWIN_TOP )
1623EVT_SCROLLWIN_BOTTOM = wx.PyEventBinder( wxEVT_SCROLLWIN_BOTTOM )
1624EVT_SCROLLWIN_LINEUP = wx.PyEventBinder( wxEVT_SCROLLWIN_LINEUP )
1625EVT_SCROLLWIN_LINEDOWN = wx.PyEventBinder( wxEVT_SCROLLWIN_LINEDOWN )
1626EVT_SCROLLWIN_PAGEUP = wx.PyEventBinder( wxEVT_SCROLLWIN_PAGEUP )
1627EVT_SCROLLWIN_PAGEDOWN = wx.PyEventBinder( wxEVT_SCROLLWIN_PAGEDOWN )
1628EVT_SCROLLWIN_THUMBTRACK = wx.PyEventBinder( wxEVT_SCROLLWIN_THUMBTRACK )
1629EVT_SCROLLWIN_THUMBRELEASE = wx.PyEventBinder( wxEVT_SCROLLWIN_THUMBRELEASE )
1630
1631# Scrolling from wx.Slider and wx.ScrollBar
1632EVT_SCROLL = wx.PyEventBinder([ wxEVT_SCROLL_TOP,
1633                               wxEVT_SCROLL_BOTTOM,
1634                               wxEVT_SCROLL_LINEUP,
1635                               wxEVT_SCROLL_LINEDOWN,
1636                               wxEVT_SCROLL_PAGEUP,
1637                               wxEVT_SCROLL_PAGEDOWN,
1638                               wxEVT_SCROLL_THUMBTRACK,
1639                               wxEVT_SCROLL_THUMBRELEASE,
1640                               wxEVT_SCROLL_CHANGED,
1641                               ])
1642
1643EVT_SCROLL_TOP = wx.PyEventBinder( wxEVT_SCROLL_TOP )
1644EVT_SCROLL_BOTTOM = wx.PyEventBinder( wxEVT_SCROLL_BOTTOM )
1645EVT_SCROLL_LINEUP = wx.PyEventBinder( wxEVT_SCROLL_LINEUP )
1646EVT_SCROLL_LINEDOWN = wx.PyEventBinder( wxEVT_SCROLL_LINEDOWN )
1647EVT_SCROLL_PAGEUP = wx.PyEventBinder( wxEVT_SCROLL_PAGEUP )
1648EVT_SCROLL_PAGEDOWN = wx.PyEventBinder( wxEVT_SCROLL_PAGEDOWN )
1649EVT_SCROLL_THUMBTRACK = wx.PyEventBinder( wxEVT_SCROLL_THUMBTRACK )
1650EVT_SCROLL_THUMBRELEASE = wx.PyEventBinder( wxEVT_SCROLL_THUMBRELEASE )
1651EVT_SCROLL_CHANGED = wx.PyEventBinder( wxEVT_SCROLL_CHANGED )
1652EVT_SCROLL_ENDSCROLL = EVT_SCROLL_CHANGED
1653
1654# Scrolling from wx.Slider and wx.ScrollBar, with an id
1655EVT_COMMAND_SCROLL = wx.PyEventBinder([ wxEVT_SCROLL_TOP,
1656                                       wxEVT_SCROLL_BOTTOM,
1657                                       wxEVT_SCROLL_LINEUP,
1658                                       wxEVT_SCROLL_LINEDOWN,
1659                                       wxEVT_SCROLL_PAGEUP,
1660                                       wxEVT_SCROLL_PAGEDOWN,
1661                                       wxEVT_SCROLL_THUMBTRACK,
1662                                       wxEVT_SCROLL_THUMBRELEASE,
1663                                       wxEVT_SCROLL_CHANGED,
1664                                       ], 1)
1665
1666EVT_COMMAND_SCROLL_TOP = wx.PyEventBinder( wxEVT_SCROLL_TOP, 1)
1667EVT_COMMAND_SCROLL_BOTTOM = wx.PyEventBinder( wxEVT_SCROLL_BOTTOM, 1)
1668EVT_COMMAND_SCROLL_LINEUP = wx.PyEventBinder( wxEVT_SCROLL_LINEUP, 1)
1669EVT_COMMAND_SCROLL_LINEDOWN = wx.PyEventBinder( wxEVT_SCROLL_LINEDOWN, 1)
1670EVT_COMMAND_SCROLL_PAGEUP = wx.PyEventBinder( wxEVT_SCROLL_PAGEUP, 1)
1671EVT_COMMAND_SCROLL_PAGEDOWN = wx.PyEventBinder( wxEVT_SCROLL_PAGEDOWN, 1)
1672EVT_COMMAND_SCROLL_THUMBTRACK = wx.PyEventBinder( wxEVT_SCROLL_THUMBTRACK, 1)
1673EVT_COMMAND_SCROLL_THUMBRELEASE = wx.PyEventBinder( wxEVT_SCROLL_THUMBRELEASE, 1)
1674EVT_COMMAND_SCROLL_CHANGED = wx.PyEventBinder( wxEVT_SCROLL_CHANGED, 1)
1675EVT_COMMAND_SCROLL_ENDSCROLL = EVT_COMMAND_SCROLL_CHANGED
1676
1677EVT_BUTTON = wx.PyEventBinder( wxEVT_BUTTON, 1)
1678EVT_CHECKBOX = wx.PyEventBinder( wxEVT_CHECKBOX, 1)
1679EVT_CHOICE = wx.PyEventBinder( wxEVT_CHOICE, 1)
1680EVT_LISTBOX = wx.PyEventBinder( wxEVT_LISTBOX, 1)
1681EVT_LISTBOX_DCLICK = wx.PyEventBinder( wxEVT_LISTBOX_DCLICK, 1)
1682EVT_MENU = wx.PyEventBinder( wxEVT_MENU, 1)
1683EVT_MENU_RANGE = wx.PyEventBinder( wxEVT_MENU, 2)
1684EVT_SLIDER = wx.PyEventBinder( wxEVT_SLIDER, 1)
1685EVT_RADIOBOX = wx.PyEventBinder( wxEVT_RADIOBOX, 1)
1686EVT_RADIOBUTTON = wx.PyEventBinder( wxEVT_RADIOBUTTON, 1)
1687
1688EVT_SCROLLBAR = wx.PyEventBinder( wxEVT_SCROLLBAR, 1)
1689EVT_VLBOX = wx.PyEventBinder( wxEVT_VLBOX, 1)
1690EVT_COMBOBOX = wx.PyEventBinder( wxEVT_COMBOBOX, 1)
1691EVT_TOOL = wx.PyEventBinder( wxEVT_TOOL, 1)
1692EVT_TOOL_RANGE = wx.PyEventBinder( wxEVT_TOOL, 2)
1693EVT_TOOL_RCLICKED = wx.PyEventBinder( wxEVT_TOOL_RCLICKED, 1)
1694EVT_TOOL_RCLICKED_RANGE = wx.PyEventBinder( wxEVT_TOOL_RCLICKED, 2)
1695EVT_TOOL_ENTER = wx.PyEventBinder( wxEVT_TOOL_ENTER, 1)
1696EVT_TOOL_DROPDOWN = wx.PyEventBinder( wxEVT_TOOL_DROPDOWN, 1)
1697EVT_CHECKLISTBOX = wx.PyEventBinder( wxEVT_CHECKLISTBOX, 1)
1698EVT_COMBOBOX_DROPDOWN = wx.PyEventBinder( wxEVT_COMBOBOX_DROPDOWN , 1)
1699EVT_COMBOBOX_CLOSEUP  = wx.PyEventBinder( wxEVT_COMBOBOX_CLOSEUP , 1)
1700
1701EVT_COMMAND_LEFT_CLICK = wx.PyEventBinder( wxEVT_COMMAND_LEFT_CLICK, 1)
1702EVT_COMMAND_LEFT_DCLICK = wx.PyEventBinder( wxEVT_COMMAND_LEFT_DCLICK, 1)
1703EVT_COMMAND_RIGHT_CLICK = wx.PyEventBinder( wxEVT_COMMAND_RIGHT_CLICK, 1)
1704EVT_COMMAND_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_COMMAND_RIGHT_DCLICK, 1)
1705EVT_COMMAND_SET_FOCUS = wx.PyEventBinder( wxEVT_COMMAND_SET_FOCUS, 1)
1706EVT_COMMAND_KILL_FOCUS = wx.PyEventBinder( wxEVT_COMMAND_KILL_FOCUS, 1)
1707EVT_COMMAND_ENTER = wx.PyEventBinder( wxEVT_COMMAND_ENTER, 1)
1708
1709EVT_HELP = wx.PyEventBinder( wxEVT_HELP, 1)
1710EVT_HELP_RANGE = wx.PyEventBinder(  wxEVT_HELP, 2)
1711EVT_DETAILED_HELP = wx.PyEventBinder( wxEVT_DETAILED_HELP, 1)
1712EVT_DETAILED_HELP_RANGE = wx.PyEventBinder( wxEVT_DETAILED_HELP, 2)
1713
1714EVT_IDLE = wx.PyEventBinder( wxEVT_IDLE )
1715
1716EVT_UPDATE_UI = wx.PyEventBinder( wxEVT_UPDATE_UI, 1)
1717EVT_UPDATE_UI_RANGE = wx.PyEventBinder( wxEVT_UPDATE_UI, 2)
1718
1719EVT_CONTEXT_MENU = wx.PyEventBinder( wxEVT_CONTEXT_MENU )
1720
1721EVT_THREAD = wx.PyEventBinder( wxEVT_THREAD )
1722
1723EVT_WINDOW_MODAL_DIALOG_CLOSED = wx.PyEventBinder( wxEVT_WINDOW_MODAL_DIALOG_CLOSED )
1724
1725EVT_JOY_BUTTON_DOWN = wx.PyEventBinder( wxEVT_JOY_BUTTON_DOWN )
1726EVT_JOY_BUTTON_UP = wx.PyEventBinder( wxEVT_JOY_BUTTON_UP )
1727EVT_JOY_MOVE = wx.PyEventBinder( wxEVT_JOY_MOVE )
1728EVT_JOY_ZMOVE = wx.PyEventBinder( wxEVT_JOY_ZMOVE )
1729EVT_JOYSTICK_EVENTS = wx.PyEventBinder([ wxEVT_JOY_BUTTON_DOWN,
1730                                        wxEVT_JOY_BUTTON_UP,
1731                                        wxEVT_JOY_MOVE,
1732                                        wxEVT_JOY_ZMOVE,
1733                                        ])
1734
1735# deprecated wxEVT aliases
1736wxEVT_COMMAND_BUTTON_CLICKED         = wxEVT_BUTTON
1737wxEVT_COMMAND_CHECKBOX_CLICKED       = wxEVT_CHECKBOX
1738wxEVT_COMMAND_CHOICE_SELECTED        = wxEVT_CHOICE
1739wxEVT_COMMAND_LISTBOX_SELECTED       = wxEVT_LISTBOX
1740wxEVT_COMMAND_LISTBOX_DOUBLECLICKED  = wxEVT_LISTBOX_DCLICK
1741wxEVT_COMMAND_CHECKLISTBOX_TOGGLED   = wxEVT_CHECKLISTBOX
1742wxEVT_COMMAND_MENU_SELECTED          = wxEVT_MENU
1743wxEVT_COMMAND_TOOL_CLICKED           = wxEVT_TOOL
1744wxEVT_COMMAND_SLIDER_UPDATED         = wxEVT_SLIDER
1745wxEVT_COMMAND_RADIOBOX_SELECTED      = wxEVT_RADIOBOX
1746wxEVT_COMMAND_RADIOBUTTON_SELECTED   = wxEVT_RADIOBUTTON
1747wxEVT_COMMAND_SCROLLBAR_UPDATED      = wxEVT_SCROLLBAR
1748wxEVT_COMMAND_VLBOX_SELECTED         = wxEVT_VLBOX
1749wxEVT_COMMAND_COMBOBOX_SELECTED      = wxEVT_COMBOBOX
1750wxEVT_COMMAND_TOOL_RCLICKED          = wxEVT_TOOL_RCLICKED
1751wxEVT_COMMAND_TOOL_DROPDOWN_CLICKED  = wxEVT_TOOL_DROPDOWN
1752wxEVT_COMMAND_TOOL_ENTER             = wxEVT_TOOL_ENTER
1753wxEVT_COMMAND_COMBOBOX_DROPDOWN      = wxEVT_COMBOBOX_DROPDOWN
1754wxEVT_COMMAND_COMBOBOX_CLOSEUP       = wxEVT_COMBOBOX_CLOSEUP
1755
1756# End of included code block
1757#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
1758
1759PyEvtHandler = wx.deprecated(EvtHandler, "Use :class:`EvtHandler` instead.")
1760
1761def _PyEvent_Clone(self):
1762    """
1763    Make a new instance of the event that is a copy of self.
1764
1765    Through the magic of Python this implementation should work for
1766    this and all derived classes.
1767    """
1768    # Create a new instance of the same type as this instance and
1769    # then invoke the C++ copy constructor to copy the C++ parts and
1770    # any custom attributes.
1771    clone = wx.PyEvent.__new__(self.__class__)
1772    wx.PyEvent.__init__(clone, self)
1773    return clone
1774PyEvent.Clone = _PyEvent_Clone
1775del _PyEvent_Clone
1776def _PyCommandEvent_Clone(self):
1777    """
1778    Make a new instance of the event that is a copy of self.
1779
1780    Through the magic of Python this implementation should work for
1781    this and all derived classes.
1782    """
1783    # Create a new instance of the same type as this instance and
1784    # then invoke the C++ copy constructor to copy the C++ parts and
1785    # any custom attributes.
1786    clone = wx.PyCommandEvent.__new__(self.__class__)
1787    wx.PyCommandEvent.__init__(clone, self)
1788    return clone
1789PyCommandEvent.Clone = _PyCommandEvent_Clone
1790del _PyCommandEvent_Clone
1791def _Sizer_AddMany(self, items):
1792    """
1793    :meth:`AddMany` is a convenience method for adding several items to a sizer
1794    at one time. Simply pass it a list of tuples, where each tuple
1795    consists of the parameters that you would normally pass to the :meth:`Add`
1796    method.
1797    """
1798    for item in items:
1799        if not isinstance(item, (tuple, list)):
1800            item = (item, )
1801        self.Add(*item)
1802Sizer.AddMany = _Sizer_AddMany
1803del _Sizer_AddMany
1804def _Sizer___nonzero__(self):
1805    """
1806    Can be used to test if the C++ part of the sizer still exists, with
1807    code like this::
1808
1809        if theSizer:
1810            doSomething()
1811    """
1812    import wx.siplib
1813    return not wx.siplib.isdeleted(self)
1814Sizer.__nonzero__ = _Sizer___nonzero__
1815del _Sizer___nonzero__
1816def _Sizer___iter__(self):
1817    """
1818    A Py convenience method that allows Sizers to act as iterables that will yield their wx.SizerItems.
1819    """
1820    for item in self.GetChildren(): yield item
1821Sizer.__iter__ = _Sizer___iter__
1822del _Sizer___iter__
1823Sizer.__bool__ = Sizer.__nonzero__
1824
1825def _GridSizer_CalcRowsCols(self):
1826    """
1827    CalcRowsCols() -> (rows, cols)
1828
1829    Calculates how many rows and columns will be in the sizer based
1830    on the current number of items and also the rows, cols specified
1831    in the constructor.
1832    """
1833    nitems = len(self.GetChildren())
1834    rows = self.GetRows()
1835    cols = self.GetCols()
1836    assert rows != 0 or cols != 0, "Grid sizer must have either rows or columns fixed"
1837    if cols != 0:
1838        rows = (nitems + cols - 1) / cols
1839    elif rows != 0:
1840        cols = (nitems + rows - 1) / rows
1841    return (rows, cols)
1842GridSizer.CalcRowsCols = _GridSizer_CalcRowsCols
1843del _GridSizer_CalcRowsCols
1844PySizer = wx.deprecated(Sizer, 'Use Sizer instead.')
1845
1846def _SizerItemList___repr__(self):
1847    return "SizerItemList: " + repr(list(self))
1848SizerItemList.__repr__ = _SizerItemList___repr__
1849del _SizerItemList___repr__
1850def _GBPosition_GetIM(self):
1851    """
1852    Returns an immutable representation of the ``wx.GBPosition`` object, based on ``namedtuple``.
1853
1854    This new object is hashable and can be used as a dictionary key,
1855    be added to sets, etc.  It can be converted back into a real ``wx.GBPosition``
1856    with a simple statement like this: ``obj = wx.GBPosition(imObj)``.
1857    """
1858    return _im_GBPosition(*self.Get())
1859GBPosition.GetIM = _GBPosition_GetIM
1860del _GBPosition_GetIM
1861def _GBPosition___str__(self):
1862    return str(self.Get())
1863GBPosition.__str__ = _GBPosition___str__
1864del _GBPosition___str__
1865def _GBPosition___repr__(self):
1866    return "wx.GBPosition"+str(self.Get())
1867GBPosition.__repr__ = _GBPosition___repr__
1868del _GBPosition___repr__
1869def _GBPosition___len__(self):
1870    return len(self.Get())
1871GBPosition.__len__ = _GBPosition___len__
1872del _GBPosition___len__
1873def _GBPosition___nonzero__(self):
1874    return self.Get() != (0,0)
1875GBPosition.__nonzero__ = _GBPosition___nonzero__
1876del _GBPosition___nonzero__
1877def _GBPosition___bool__(self):
1878    return self.Get() != (0,0)
1879GBPosition.__bool__ = _GBPosition___bool__
1880del _GBPosition___bool__
1881def _GBPosition___reduce__(self):
1882    return (GBPosition, self.Get())
1883GBPosition.__reduce__ = _GBPosition___reduce__
1884del _GBPosition___reduce__
1885def _GBPosition___getitem__(self, idx):
1886    return self.Get()[idx]
1887GBPosition.__getitem__ = _GBPosition___getitem__
1888del _GBPosition___getitem__
1889def _GBPosition___setitem__(self, idx, val):
1890    if idx == 0: self.Row = val
1891    elif idx == 1: self.Col = val
1892    else: raise IndexError
1893GBPosition.__setitem__ = _GBPosition___setitem__
1894del _GBPosition___setitem__
1895GBPosition.__safe_for_unpickling__ = True
1896
1897def _GBSpan_GetIM(self):
1898    """
1899    Returns an immutable representation of the ``wx.GBSpan`` object, based on ``namedtuple``.
1900
1901    This new object is hashable and can be used as a dictionary key,
1902    be added to sets, etc.  It can be converted back into a real ``wx.GBSpan``
1903    with a simple statement like this: ``obj = wx.GBSpan(imObj)``.
1904    """
1905    return _im_GBSpan(*self.Get())
1906GBSpan.GetIM = _GBSpan_GetIM
1907del _GBSpan_GetIM
1908def _GBSpan___str__(self):
1909    return str(self.Get())
1910GBSpan.__str__ = _GBSpan___str__
1911del _GBSpan___str__
1912def _GBSpan___repr__(self):
1913    return "wx.GBSpan"+str(self.Get())
1914GBSpan.__repr__ = _GBSpan___repr__
1915del _GBSpan___repr__
1916def _GBSpan___len__(self):
1917    return len(self.Get())
1918GBSpan.__len__ = _GBSpan___len__
1919del _GBSpan___len__
1920def _GBSpan___nonzero__(self):
1921    return self.Get() != (0,0)
1922GBSpan.__nonzero__ = _GBSpan___nonzero__
1923del _GBSpan___nonzero__
1924def _GBSpan___bool__(self):
1925    return self.Get() != (0,0)
1926GBSpan.__bool__ = _GBSpan___bool__
1927del _GBSpan___bool__
1928def _GBSpan___reduce__(self):
1929    return (GBSpan, self.Get())
1930GBSpan.__reduce__ = _GBSpan___reduce__
1931del _GBSpan___reduce__
1932def _GBSpan___getitem__(self, idx):
1933    return self.Get()[idx]
1934GBSpan.__getitem__ = _GBSpan___getitem__
1935del _GBSpan___getitem__
1936def _GBSpan___setitem__(self, idx, val):
1937    if idx == 0: self.Rowspan = val
1938    elif idx == 1: self.Colspan = val
1939    else: raise IndexError
1940GBSpan.__setitem__ = _GBSpan___setitem__
1941del _GBSpan___setitem__
1942GBSpan.__safe_for_unpickling__ = True
1943
1944GridBagSizer.CheckForIntersectionPos = wx.deprecated(GridBagSizer.CheckForIntersection, 'Use CheckForIntersection instead.')
1945
1946from collections import namedtuple
1947_im_GBPosition = namedtuple('_im_GBPosition', ['row', 'col'])
1948del namedtuple
1949
1950from collections import namedtuple
1951_im_GBSpan = namedtuple('_im_GBSpan', ['rowspan', 'colspan'])
1952del namedtuple
1953
1954def _EventLoopActivator___enter__(self):
1955    return self
1956EventLoopActivator.__enter__ = _EventLoopActivator___enter__
1957del _EventLoopActivator___enter__
1958def _EventLoopActivator___exit__(self, exc_type, exc_val, exc_tb):
1959    return False
1960EventLoopActivator.__exit__ = _EventLoopActivator___exit__
1961del _EventLoopActivator___exit__
1962@wx.deprecatedMsg('Use GUIEventLoop instead.')
1963class EventLoop(GUIEventLoop):
1964    '''A class using the old name for compatibility.'''
1965    def __init__(self):
1966        GUIEventLoop.__init__(self)
1967
1968def YieldIfNeeded():
1969    """
1970    Convenience function for wx.GetApp().Yield(True)
1971    """
1972    return wx.GetApp().Yield(True)
1973
1974class PyOnDemandOutputWindow(object):
1975    """
1976    A class that can be used for redirecting Python's stdout and
1977    stderr streams.  It will do nothing until something is wrriten to
1978    the stream at which point it will create a Frame with a text area
1979    and write the text there.
1980    """
1981    def __init__(self, title="wxPython: stdout/stderr"):
1982        self.frame  = None
1983        self.title  = title
1984        self.pos    = wx.DefaultPosition
1985        self.size   = (450, 300)
1986        self.parent = None
1987
1988    def SetParent(self, parent):
1989        """
1990        Set the window to be used as the popup Frame's parent.
1991        """
1992        self.parent = parent
1993
1994    def CreateOutputWindow(self, txt):
1995        self.frame = wx.Frame(self.parent, -1, self.title, self.pos, self.size,
1996                              style=wx.DEFAULT_FRAME_STYLE)
1997        self.text  = wx.TextCtrl(self.frame, -1, "",
1998                                 style=wx.TE_MULTILINE|wx.TE_READONLY)
1999        self.text.AppendText(txt)
2000        self.frame.Show(True)
2001        self.frame.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
2002
2003    def OnCloseWindow(self, event):
2004        if self.frame is not None:
2005            self.frame.Destroy()
2006        self.frame = None
2007        self.text  = None
2008        self.parent = None
2009
2010    def write(self, text):
2011        """
2012        Create the output window if needed and write the string to it.
2013        If not called in the context of the gui thread then CallAfter is
2014        used to do the work there.
2015        """
2016        if self.frame is None:
2017            if not wx.IsMainThread():
2018                wx.CallAfter(self.CreateOutputWindow, text)
2019            else:
2020                self.CreateOutputWindow(text)
2021        else:
2022            if not wx.IsMainThread():
2023                wx.CallAfter(self.text.AppendText, text)
2024            else:
2025                self.text.AppendText(text)
2026
2027    def close(self):
2028        if self.frame is not None:
2029            wx.CallAfter(self.frame.Close)
2030
2031    def flush(self):
2032        pass
2033
2034
2035class App(PyApp):
2036    """
2037    The ``wx.App`` class represents the application and is used to:
2038
2039      * bootstrap the wxPython system and initialize the underlying
2040        gui toolkit
2041      * set and get application-wide properties
2042      * implement the native windowing system main message or event loop,
2043        and to dispatch events to window instances
2044      * etc.
2045
2046    Every wx application must have a single ``wx.App`` instance, and all
2047    creation of UI objects should be delayed until after the ``wx.App`` object
2048    has been created in order to ensure that the gui platform and wxWidgets
2049    have been fully initialized.
2050
2051    Normally you would derive from this class and implement an ``OnInit``
2052    method that creates a frame and then calls ``self.SetTopWindow(frame)``,
2053    however ``wx.App`` is also usable on it's own without derivation.
2054    """
2055    outputWindowClass = PyOnDemandOutputWindow
2056    def __init__(self, redirect=False, filename=None, useBestVisual=False, clearSigInt=True):
2057        """
2058        Construct a ``wx.App`` object.
2059
2060        :param redirect: Should ``sys.stdout`` and ``sys.stderr`` be
2061            redirected?  Defaults to False. If ``filename`` is None
2062            then output will be redirected to a window that pops up
2063            as needed.  (You can control what kind of window is created
2064            for the output by resetting the class variable
2065            ``outputWindowClass`` to a class of your choosing.)
2066
2067        :param filename: The name of a file to redirect output to, if
2068            redirect is True.
2069
2070        :param useBestVisual: Should the app try to use the best
2071            available visual provided by the system (only relevant on
2072            systems that have more than one visual.)  This parameter
2073            must be used instead of calling `SetUseBestVisual` later
2074            on because it must be set before the underlying GUI
2075            toolkit is initialized.
2076
2077        :param clearSigInt: Should SIGINT be cleared?  This allows the
2078            app to terminate upon a Ctrl-C in the console like other
2079            GUI apps will.
2080
2081        :note: You should override OnInit to do application
2082            initialization to ensure that the system, toolkit and
2083            wxWidgets are fully initialized.
2084        """
2085        PyApp.__init__(self)
2086
2087        # make sure we can create a GUI
2088        if not self.IsDisplayAvailable():
2089
2090            if wx.Port == "__WXMAC__":
2091                msg = "This program needs access to the screen. Please run with a\n" \
2092                      "Framework build of python, and only when you are logged in\n" \
2093                      "on the main display of your Mac."
2094
2095            elif wx.Port == "__WXGTK__":
2096                msg ="Unable to access the X Display, is $DISPLAY set properly?"
2097
2098            else:
2099                msg = "Unable to create GUI"
2100                # TODO: more description is needed for wxMSW...
2101
2102            raise SystemExit(msg)
2103
2104        # This has to be done before OnInit
2105        self.SetUseBestVisual(useBestVisual)
2106
2107        # Set the default handler for SIGINT.  This fixes a problem
2108        # where if Ctrl-C is pressed in the console that started this
2109        # app then it will not appear to do anything, (not even send
2110        # KeyboardInterrupt???)  but will later segfault on exit.  By
2111        # setting the default handler then the app will exit, as
2112        # expected (depending on platform.)
2113        if clearSigInt:
2114            try:
2115                import signal
2116                signal.signal(signal.SIGINT, signal.SIG_DFL)
2117            except:
2118                pass
2119
2120        # Save and redirect the stdio to a window?
2121        self.stdioWin = None
2122        self.saveStdio = (_sys.stdout, _sys.stderr)
2123        if redirect:
2124            self.RedirectStdio(filename)
2125
2126        # Use Python's install prefix as the default
2127        prefix = _sys.prefix
2128        if isinstance(prefix, (bytes, bytearray)):
2129            prefix = prefix.decode(_sys.getfilesystemencoding())
2130        wx.StandardPaths.Get().SetInstallPrefix(prefix)
2131
2132        # Until the new native control for wxMac is up to par, still use the generic one.
2133        wx.SystemOptions.SetOption("mac.listctrl.always_use_generic", 1)
2134
2135        # This finishes the initialization of wxWindows and then calls
2136        # the OnInit that should be present in the derived class
2137        self._BootstrapApp()
2138
2139    def OnPreInit(self):
2140        """
2141        Things that must be done after _BootstrapApp has done its thing, but
2142        would be nice if they were already done by the time that OnInit is
2143        called.  This can be overridden in derived classes, but be sure to call
2144        this method from there.
2145        """
2146        wx.StockGDI._initStockObjects()
2147        self.InitLocale()
2148
2149    def __del__(self):
2150        # Just in case the MainLoop was overridden without calling RestoreStio
2151        self.RestoreStdio()
2152
2153    def SetTopWindow(self, frame):
2154        """
2155        Set the "main" top level window, which will be used for the parent of
2156        the on-demand output window as well as for dialogs that do not have
2157        an explicit parent set.
2158        """
2159        if self.stdioWin:
2160            self.stdioWin.SetParent(frame)
2161        wx.PyApp.SetTopWindow(self, frame)
2162
2163    def MainLoop(self):
2164        """
2165        Execute the main GUI event loop
2166        """
2167        rv = wx.PyApp.MainLoop(self)
2168        self.RestoreStdio()
2169        return rv
2170
2171    def RedirectStdio(self, filename=None):
2172        """
2173        Redirect sys.stdout and sys.stderr to a file or a popup window.
2174        """
2175        if filename:
2176            _sys.stdout = _sys.stderr = open(filename, 'a')
2177        else:
2178            self.stdioWin = self.outputWindowClass()
2179            _sys.stdout = _sys.stderr = self.stdioWin
2180
2181    def RestoreStdio(self):
2182        try:
2183            _sys.stdout, _sys.stderr = self.saveStdio
2184        except:
2185            pass
2186
2187    def SetOutputWindowAttributes(self, title=None, pos=None, size=None):
2188        """
2189        Set the title, position and/or size of the output window if the stdio
2190        has been redirected. This should be called before any output would
2191        cause the output window to be created.
2192        """
2193        if self.stdioWin:
2194            if title is not None:
2195                self.stdioWin.title = title
2196            if pos is not None:
2197                self.stdioWin.pos = pos
2198            if size is not None:
2199                self.stdioWin.size = size
2200
2201    def InitLocale(self):
2202        """
2203        Try to ensure that the C and Python locale is in sync with wxWidgets locale.
2204        """
2205        self.ResetLocale()
2206        import locale
2207        try:
2208            loc, enc = locale.getlocale()
2209        except ValueError:
2210            loc = enc = None
2211        # Try to set it to the same language as what is already set in the C locale
2212        info = wx.Locale.FindLanguageInfo(loc) if loc else None
2213        if info:
2214            self._initial_locale = wx.Locale(info.Language)
2215        else:
2216            # otherwise fall back to the system default
2217            self._initial_locale = wx.Locale(wx.LANGUAGE_DEFAULT)
2218
2219    def ResetLocale(self):
2220        """
2221        Release the wx.Locale object created in :meth:`InitLocale`.
2222        This will reset the application's locale to the previous settings.
2223        """
2224        self._initial_locale = None
2225
2226    @staticmethod
2227    def Get():
2228        """
2229        A staticmethod returning the currently active application object.
2230        Essentially just a more pythonic version of :meth:`GetApp`.
2231        """
2232        return GetApp()
2233
2234
2235@wx.deprecatedMsg("Use :class:`App` instead.")
2236class PySimpleApp(App):
2237    """
2238    This class is deprecated.  Please use :class:`App` instead.
2239    """
2240    def __init__(self, *args, **kw):
2241        App.__init__(self, *args, **kw)
2242
2243
2244EVT_TIMER = wx.PyEventBinder( wxEVT_TIMER )
2245
2246class PyTimer(Timer):
2247    '''This timer class is passed the callable object to be called when the timer expires.'''
2248    def __init__(self, notify):
2249        Timer.__init__(self)
2250        self.notify = notify
2251
2252    def Notify(self):
2253        if self.notify:
2254            self.notify()
2255
2256def _Window_SetRect(self, rect):
2257    return self.SetSize(rect)
2258Window.SetRect = _Window_SetRect
2259del _Window_SetRect
2260Window.Rect = property(Window.GetRect, Window.SetRect)
2261def _Window_SetClientRect(self, rect):
2262    return self.SetClientSize(rect)
2263Window.SetClientRect = _Window_SetClientRect
2264del _Window_SetClientRect
2265Window.ClientRect = property(Window.GetClientRect, Window.SetClientRect)
2266Window.SetDimensions = wx.deprecated(Window.SetDimensions, 'Use SetSize instead.')
2267
2268def _Window___nonzero__(self):
2269    """
2270    Can be used to test if the C++ part of the window still exists, with
2271    code like this::
2272
2273        if theWindow:
2274            doSomething()
2275    """
2276    import wx.siplib
2277    return not wx.siplib.isdeleted(self)
2278Window.__nonzero__ = _Window___nonzero__
2279del _Window___nonzero__
2280Window.__bool__ = Window.__nonzero__
2281
2282def _Window_DestroyLater(self):
2283    """
2284    Schedules the window to be destroyed in the near future.
2285
2286    This should be used whenever Destroy could happen too soon, such
2287    as when there may still be events for this window or its children
2288    waiting in the event queue.
2289    """
2290    self.Hide()
2291    wx.GetApp().ScheduleForDestruction(self)
2292Window.DestroyLater = _Window_DestroyLater
2293del _Window_DestroyLater
2294def _Window_DLG_UNIT(self, dlg_unit):
2295    """
2296    A convenience wrapper for :meth:`ConvertDialogToPixels`.
2297    """
2298    is_wxType = isinstance(dlg_unit, (wx.Size, wx.Point))
2299    pix = self.ConvertDialogToPixels(dlg_unit)
2300    if not is_wxType:
2301        pix = tuple(pix)
2302    return pix
2303Window.DLG_UNIT = _Window_DLG_UNIT
2304del _Window_DLG_UNIT
2305def _Window_PostCreate(self, pre):
2306    pass
2307Window.PostCreate = wx.deprecated(_Window_PostCreate, "PostCreate is no longer necessary.")
2308del _Window_PostCreate
2309def _Window_GetPositionTuple(self):
2310    return self.GetPosition()
2311Window.GetPositionTuple = wx.deprecated(_Window_GetPositionTuple, "Use GetPosition instead")
2312del _Window_GetPositionTuple
2313def _Window_GetSizeTuple(self):
2314    return self.GetSize()
2315Window.GetSizeTuple = wx.deprecated(_Window_GetSizeTuple, "Use GetSize instead")
2316del _Window_GetSizeTuple
2317def _Window_MoveXY(self, x, y):
2318    return self.Move(x, y)
2319Window.MoveXY = wx.deprecated(_Window_MoveXY, "Use Move instead.")
2320del _Window_MoveXY
2321def _Window_SetSizeWH(self, w, h):
2322    return self.SetSize(w,h)
2323Window.SetSizeWH = wx.deprecated(_Window_SetSizeWH, "Use SetSize instead.")
2324del _Window_SetSizeWH
2325def _Window_SetVirtualSizeWH(self, w, h):
2326    return self.SetVirtualSize(w,h)
2327Window.SetVirtualSizeWH = wx.deprecated(_Window_SetVirtualSizeWH, "Use SetVirtualSize instead.")
2328del _Window_SetVirtualSizeWH
2329def _Window_GetVirtualSizeTuple(self):
2330    return self.GetVirtualSize()
2331Window.GetVirtualSizeTuple = wx.deprecated(_Window_GetVirtualSizeTuple, "Use GetVirtualSize instead.")
2332del _Window_GetVirtualSizeTuple
2333def _Window_SetToolTipString(self, string):
2334    return self.SetToolTip(string)
2335Window.SetToolTipString = wx.deprecated(_Window_SetToolTipString, "Use SetToolTip instead.")
2336del _Window_SetToolTipString
2337def _Window_ConvertDialogPointToPixels(self, point):
2338    return self.ConvertDialogToPixels(point)
2339Window.ConvertDialogPointToPixels = wx.deprecated(_Window_ConvertDialogPointToPixels, "Use ConvertDialogToPixels instead.")
2340del _Window_ConvertDialogPointToPixels
2341def _Window_ConvertDialogSizeToPixels(self, size):
2342    return self.ConvertDialogToPixels(point)
2343Window.ConvertDialogSizeToPixels = wx.deprecated(_Window_ConvertDialogSizeToPixels, "Use ConvertDialogToPixels instead.")
2344del _Window_ConvertDialogSizeToPixels
2345def _Window_SetSizeHintsSz(self, minSize, maxSize=wx.DefaultSize, incSize=wx.DefaultSize):
2346    return self.SetSizeHints(minSize, maxSize, incSize)
2347Window.SetSizeHintsSz = wx.deprecated(_Window_SetSizeHintsSz, "Use SetSizeHints instead.")
2348del _Window_SetSizeHintsSz
2349class FrozenWindow(object):
2350    """
2351    A context manager to be used with Python 'with' statements
2352    that will freeze the given window for the duration of the
2353    with block.
2354    """
2355    def __init__(self, window):
2356        self._win = window
2357    def __enter__(self):
2358        self._win.Freeze()
2359        return self
2360    def __exit__(self, exc_type, exc_val, exc_tb):
2361        self._win.Thaw()
2362
2363def DLG_UNIT(win, dlg_unit, val2=None):
2364    """
2365    Convenience function for converting a wx.Point, wx.Size or
2366    (x,y) in dialog units to pixels, using the given window as a
2367    reference.
2368    """
2369    if val2 is not None:
2370        dlg_unit = (dlg_unit, val2)
2371    is_wxType = isinstance(dlg_unit, (wx.Size, wx.Point))
2372    pix = win.ConvertDialogToPixels(dlg_unit)
2373    if not is_wxType:
2374        pix = tuple(pix)
2375    return pix
2376
2377DLG_PNT = wx.deprecated(DLG_UNIT, "Use DLG_UNIT instead.")
2378DLG_SZE = wx.deprecated(DLG_UNIT, "Use DLG_UNIT instead.")
2379
2380def _WindowList___repr__(self):
2381    return "WindowList: " + repr(list(self))
2382WindowList.__repr__ = _WindowList___repr__
2383del _WindowList___repr__
2384PyWindow = wx.deprecated(Window, 'Use Window instead.')
2385
2386PyValidator = wx.deprecated(Validator, 'Use Validator instead.')
2387
2388PyPanel = wx.deprecated(Panel, 'Use Panel instead.')
2389
2390def _MenuItemList___repr__(self):
2391    return "MenuItemList: " + repr(list(self))
2392MenuItemList.__repr__ = _MenuItemList___repr__
2393del _MenuItemList___repr__
2394def _Menu_AppendMenu(self, id, item, subMenu, help=""):
2395    return self.Append(id, item, subMenu, help)
2396Menu.AppendMenu = wx.deprecated(_Menu_AppendMenu, "Use Append instead.")
2397del _Menu_AppendMenu
2398def _Menu_AppendItem(self, menuItem):
2399    return self.Append(menuItem)
2400Menu.AppendItem = wx.deprecated(_Menu_AppendItem, "Use Append instead.")
2401del _Menu_AppendItem
2402def _Menu_InsertMenu(self, pos, id, item, subMenu, help=""):
2403    return self.Insert(pos, id, item, subMenu, help)
2404Menu.InsertMenu = wx.deprecated(_Menu_InsertMenu, "Use Insert instead.")
2405del _Menu_InsertMenu
2406def _Menu_InsertItem(self, pos, menuItem):
2407    return self.Insert(pos, menuItem)
2408Menu.InsertItem = wx.deprecated(_Menu_InsertItem, "Use Insert instead.")
2409del _Menu_InsertItem
2410def _Menu_PrependMenu(self, id, item, subMenu, help=""):
2411    return self.Prepend(id, item, subMenu, help)
2412Menu.PrependMenu = wx.deprecated(_Menu_PrependMenu, "Use Prepend instead.")
2413del _Menu_PrependMenu
2414def _Menu_PrependItem(self, menuItem):
2415    return self.Prepend(menuItem)
2416Menu.PrependItem = wx.deprecated(_Menu_PrependItem, "Use Prepend instead.")
2417del _Menu_PrependItem
2418def _Menu_RemoveMenu(self, id, item, subMenu, help=""):
2419    return self.Remove(id, item, subMenu, help)
2420Menu.RemoveMenu = wx.deprecated(_Menu_RemoveMenu, "Use Remove instead.")
2421del _Menu_RemoveMenu
2422def _Menu_RemoveItem(self, menuItem):
2423    return self.Remove(menuItem)
2424Menu.RemoveItem = wx.deprecated(_Menu_RemoveItem, "Use Remove instead.")
2425del _Menu_RemoveItem
2426def _MenuBar_GetMenus(self):
2427    """
2428    GetMenus() -> (menu, label)
2429
2430    Return a list of (menu, label) items for the menus in the :class:`MenuBar`.
2431    """
2432    return [(self.GetMenu(i), self.GetLabelTop(i)) for i in range(self.GetMenuCount())]
2433MenuBar.GetMenus = _MenuBar_GetMenus
2434del _MenuBar_GetMenus
2435def _MenuBar_SetMenus(self, items):
2436    """
2437    SetMenus()
2438
2439    Clear and add new menus to the :class:`MenuBar` from a list of (menu, label) items.
2440    """
2441    for i in range(self.GetMenuCount()-1, -1, -1):
2442        self.Remove(i)
2443    for m, l in items:
2444        self.Append(m, l)
2445MenuBar.SetMenus = _MenuBar_SetMenus
2446del _MenuBar_SetMenus
2447MenuBar.Menus = property(MenuBar.GetMenus, MenuBar.SetMenus)
2448def _MenuList___repr__(self):
2449    return "MenuList: " + repr(list(self))
2450MenuList.__repr__ = _MenuList___repr__
2451del _MenuList___repr__
2452PyScrolledWindow = wx.deprecated(ScrolledWindow, 'Use ScrolledWindow instead.')
2453
2454def _VScrolledWindow_HitTest(self, *args):
2455    """
2456    Deprecated compatibility helper.
2457    """
2458    if len(args) == 2:
2459        x, y = args
2460        return self.VirtualHitTest(y)
2461    else:
2462        pt = args[0]
2463        return self.VirtualHitTest(pt[1])
2464VScrolledWindow.HitTest = wx.deprecated(_VScrolledWindow_HitTest, "Use VirtualHitTest instead.")
2465del _VScrolledWindow_HitTest
2466PyControl = wx.deprecated(Control, 'Use Control instead.')
2467
2468def _ItemContainer_GetClientObject(self, n):
2469    """
2470    Alias for :meth:`GetClientData`
2471    """
2472    return self.GetClientData(n)
2473ItemContainer.GetClientObject = _ItemContainer_GetClientObject
2474del _ItemContainer_GetClientObject
2475def _ItemContainer_SetClientObject(self, n, data):
2476    """
2477    Alias for :meth:`SetClientData`
2478    """
2479    self.SetClientData(n, data)
2480ItemContainer.SetClientObject = _ItemContainer_SetClientObject
2481del _ItemContainer_SetClientObject
2482def _ItemContainer_AppendItems(self, items):
2483    self.Append(items)
2484ItemContainer.AppendItems = _ItemContainer_AppendItems
2485del _ItemContainer_AppendItems
2486def _ItemContainer_GetItems(self):
2487    return self.GetStrings()
2488ItemContainer.GetItems = _ItemContainer_GetItems
2489del _ItemContainer_GetItems
2490def _ItemContainer_SetItems(self, items):
2491    self.Set(items)
2492ItemContainer.SetItems = _ItemContainer_SetItems
2493del _ItemContainer_SetItems
2494ItemContainer.Items = property(ItemContainer.GetItems, ItemContainer.SetItems)
2495EVT_NOTEBOOK_PAGE_CHANGED  = wx.PyEventBinder( wxEVT_NOTEBOOK_PAGE_CHANGED, 1 )
2496EVT_NOTEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_NOTEBOOK_PAGE_CHANGING, 1 )
2497
2498# Aliases for the "best book" control as described in the overview
2499BookCtrl =                       Notebook
2500wxEVT_BOOKCTRL_PAGE_CHANGED =    wxEVT_NOTEBOOK_PAGE_CHANGED
2501wxEVT_BOOKCTRL_PAGE_CHANGING =   wxEVT_NOTEBOOK_PAGE_CHANGING
2502EVT_BOOKCTRL_PAGE_CHANGED =      EVT_NOTEBOOK_PAGE_CHANGED
2503EVT_BOOKCTRL_PAGE_CHANGING =     EVT_NOTEBOOK_PAGE_CHANGING
2504
2505# deprecated wxEVT aliases
2506wxEVT_COMMAND_BOOKCTRL_PAGE_CHANGED   = wxEVT_BOOKCTRL_PAGE_CHANGED
2507wxEVT_COMMAND_BOOKCTRL_PAGE_CHANGING  = wxEVT_BOOKCTRL_PAGE_CHANGING
2508wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED   = wxEVT_NOTEBOOK_PAGE_CHANGED
2509wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING  = wxEVT_NOTEBOOK_PAGE_CHANGING
2510
2511EVT_SPLITTER_SASH_POS_CHANGED = wx.PyEventBinder( wxEVT_SPLITTER_SASH_POS_CHANGED, 1 )
2512EVT_SPLITTER_SASH_POS_CHANGING = wx.PyEventBinder( wxEVT_SPLITTER_SASH_POS_CHANGING, 1 )
2513EVT_SPLITTER_DOUBLECLICKED = wx.PyEventBinder( wxEVT_SPLITTER_DOUBLECLICKED, 1 )
2514EVT_SPLITTER_UNSPLIT = wx.PyEventBinder( wxEVT_SPLITTER_UNSPLIT, 1 )
2515EVT_SPLITTER_DCLICK = EVT_SPLITTER_DOUBLECLICKED
2516
2517# deprecated wxEVT aliases
2518wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGED   = wxEVT_SPLITTER_SASH_POS_CHANGED
2519wxEVT_COMMAND_SPLITTER_SASH_POS_CHANGING  = wxEVT_SPLITTER_SASH_POS_CHANGING
2520wxEVT_COMMAND_SPLITTER_DOUBLECLICKED      = wxEVT_SPLITTER_DOUBLECLICKED
2521wxEVT_COMMAND_SPLITTER_UNSPLIT            = wxEVT_SPLITTER_UNSPLIT
2522
2523EVT_COLLAPSIBLEPANE_CHANGED = wx.PyEventBinder( wxEVT_COLLAPSIBLEPANE_CHANGED )
2524
2525# deprecated wxEVT alias
2526wxEVT_COMMAND_COLLPANE_CHANGED  = wxEVT_COLLAPSIBLEPANE_CHANGED
2527
2528EVT_TEXT        = wx.PyEventBinder( wxEVT_TEXT, 1)
2529EVT_TEXT_ENTER  = wx.PyEventBinder( wxEVT_TEXT_ENTER, 1)
2530EVT_TEXT_URL    = wx.PyEventBinder( wxEVT_TEXT_URL, 1)
2531EVT_TEXT_MAXLEN = wx.PyEventBinder( wxEVT_TEXT_MAXLEN, 1)
2532EVT_TEXT_CUT    = wx.PyEventBinder( wxEVT_TEXT_CUT )
2533EVT_TEXT_COPY   = wx.PyEventBinder( wxEVT_TEXT_COPY )
2534EVT_TEXT_PASTE  = wx.PyEventBinder( wxEVT_TEXT_PASTE )
2535
2536# deprecated wxEVT aliases
2537wxEVT_COMMAND_TEXT_UPDATED   = wxEVT_TEXT
2538wxEVT_COMMAND_TEXT_ENTER     = wxEVT_TEXT_ENTER
2539wxEVT_COMMAND_TEXT_URL       = wxEVT_TEXT_URL
2540wxEVT_COMMAND_TEXT_MAXLEN    = wxEVT_TEXT_MAXLEN
2541wxEVT_COMMAND_TEXT_CUT       = wxEVT_TEXT_CUT
2542wxEVT_COMMAND_TEXT_COPY      = wxEVT_TEXT_COPY
2543wxEVT_COMMAND_TEXT_PASTE     = wxEVT_TEXT_PASTE
2544
2545ComboBox.SetMark = wx.deprecated(ComboBox.SetTextSelection, 'Use SetTextSelection instead.')
2546
2547ComboBox.GetMark = wx.deprecated(ComboBox.GetTextSelection, 'Use GetTextSelection instead.')
2548
2549def _CheckListBox_GetCheckedItems(self):
2550    """
2551    GetCheckedItems()
2552
2553    Return a sequence of integers corresponding to the checked items in
2554    the control, based on :meth:`IsChecked`.
2555    """
2556    return tuple([i for i in range(self.Count) if self.IsChecked(i)])
2557CheckListBox.GetCheckedItems = _CheckListBox_GetCheckedItems
2558del _CheckListBox_GetCheckedItems
2559def _CheckListBox_GetCheckedStrings(self):
2560    """
2561    GetCheckedStrings()
2562
2563    Return a tuple of strings corresponding to the checked
2564    items of the control, based on :meth:`GetChecked`.
2565    """
2566    return tuple([self.GetString(i) for i in self.GetCheckedItems()])
2567CheckListBox.GetCheckedStrings = _CheckListBox_GetCheckedStrings
2568del _CheckListBox_GetCheckedStrings
2569def _CheckListBox_SetCheckedItems(self, indexes):
2570    """
2571    SetCheckedItems(indexes)
2572
2573    Sets the checked state of items if the index of the item is
2574    found in the indexes sequence.
2575    """
2576    for i in indexes:
2577        assert 0 <= i < self.Count, "Index (%s) out of range" % i
2578    for i in range(self.Count):
2579        self.Check(i, i in indexes)
2580CheckListBox.SetCheckedItems = _CheckListBox_SetCheckedItems
2581del _CheckListBox_SetCheckedItems
2582def _CheckListBox_SetCheckedStrings(self, strings):
2583    """
2584    SetCheckedStrings(strings)
2585
2586    Sets the checked state of items if the item's string is found
2587    in the strings sequence.
2588    """
2589    for s in strings:
2590        assert s in self.GetStrings(), "String ('%s') not found" % s
2591    for i in range(self.Count):
2592        self.Check(i, self.GetString(i) in strings)
2593CheckListBox.SetCheckedStrings = _CheckListBox_SetCheckedStrings
2594del _CheckListBox_SetCheckedStrings
2595def _CheckListBox_GetChecked(self):
2596    return self.GetCheckedItems()
2597CheckListBox.GetChecked = wx.deprecated(_CheckListBox_GetChecked, "Use GetCheckedItems instead.")
2598del _CheckListBox_GetChecked
2599def _CheckListBox_SetChecked(self, indexes):
2600    return self.SetCheckedItems(indexes)
2601CheckListBox.SetChecked = wx.deprecated(_CheckListBox_SetChecked, "Use SetCheckedItems instead.")
2602del _CheckListBox_SetChecked
2603CheckListBox.Checked = property(CheckListBox.GetChecked, CheckListBox.SetChecked)
2604CheckListBox.CheckedItems = property(CheckListBox.GetCheckedItems, CheckListBox.SetCheckedItems)
2605CheckListBox.CheckedStrings = property(CheckListBox.GetCheckedStrings, CheckListBox.SetCheckedStrings)
2606SettableHeaderColumn.Title = property(HeaderColumn.GetTitle, SettableHeaderColumn.SetTitle)
2607SettableHeaderColumn.Bitmap = property(HeaderColumn.GetBitmap, SettableHeaderColumn.SetBitmap)
2608SettableHeaderColumn.Width = property(HeaderColumn.GetWidth, SettableHeaderColumn.SetWidth)
2609SettableHeaderColumn.MinWidth = property(HeaderColumn.GetMinWidth, SettableHeaderColumn.SetMinWidth)
2610SettableHeaderColumn.Alignment = property(HeaderColumn.GetAlignment, SettableHeaderColumn.SetAlignment)
2611SettableHeaderColumn.Flags = property(HeaderColumn.GetFlags, SettableHeaderColumn.SetFlags)
2612SettableHeaderColumn.Resizeable = property(HeaderColumn.IsResizeable, SettableHeaderColumn.SetResizeable)
2613SettableHeaderColumn.Sortable = property(HeaderColumn.IsSortable, SettableHeaderColumn.SetSortable)
2614SettableHeaderColumn.Reorderable = property(HeaderColumn.IsReorderable, SettableHeaderColumn.SetReorderable)
2615SettableHeaderColumn.Hidden = property(HeaderColumn.IsHidden, SettableHeaderColumn.SetHidden)
2616EVT_HEADER_CLICK =              wx.PyEventBinder( wxEVT_HEADER_CLICK )
2617EVT_HEADER_RIGHT_CLICK =        wx.PyEventBinder( wxEVT_HEADER_RIGHT_CLICK )
2618EVT_HEADER_MIDDLE_CLICK =       wx.PyEventBinder( wxEVT_HEADER_MIDDLE_CLICK )
2619EVT_HEADER_DCLICK =             wx.PyEventBinder( wxEVT_HEADER_DCLICK )
2620EVT_HEADER_RIGHT_DCLICK =       wx.PyEventBinder( wxEVT_HEADER_RIGHT_DCLICK )
2621EVT_HEADER_MIDDLE_DCLICK =      wx.PyEventBinder( wxEVT_HEADER_MIDDLE_DCLICK )
2622EVT_HEADER_SEPARATOR_DCLICK =   wx.PyEventBinder( wxEVT_HEADER_SEPARATOR_DCLICK )
2623EVT_HEADER_BEGIN_RESIZE =       wx.PyEventBinder( wxEVT_HEADER_BEGIN_RESIZE )
2624EVT_HEADER_RESIZING =           wx.PyEventBinder( wxEVT_HEADER_RESIZING )
2625EVT_HEADER_END_RESIZE =         wx.PyEventBinder( wxEVT_HEADER_END_RESIZE )
2626EVT_HEADER_BEGIN_REORDER =      wx.PyEventBinder( wxEVT_HEADER_BEGIN_REORDER )
2627EVT_HEADER_END_REORDER =        wx.PyEventBinder( wxEVT_HEADER_END_REORDER )
2628EVT_HEADER_DRAGGING_CANCELLED = wx.PyEventBinder( wxEVT_HEADER_DRAGGING_CANCELLED )
2629
2630# deprecated wxEVT aliases
2631wxEVT_COMMAND_HEADER_CLICK               = wxEVT_HEADER_CLICK
2632wxEVT_COMMAND_HEADER_RIGHT_CLICK         = wxEVT_HEADER_RIGHT_CLICK
2633wxEVT_COMMAND_HEADER_MIDDLE_CLICK        = wxEVT_HEADER_MIDDLE_CLICK
2634wxEVT_COMMAND_HEADER_DCLICK              = wxEVT_HEADER_DCLICK
2635wxEVT_COMMAND_HEADER_RIGHT_DCLICK        = wxEVT_HEADER_RIGHT_DCLICK
2636wxEVT_COMMAND_HEADER_MIDDLE_DCLICK       = wxEVT_HEADER_MIDDLE_DCLICK
2637wxEVT_COMMAND_HEADER_SEPARATOR_DCLICK    = wxEVT_HEADER_SEPARATOR_DCLICK
2638wxEVT_COMMAND_HEADER_BEGIN_RESIZE        = wxEVT_HEADER_BEGIN_RESIZE
2639wxEVT_COMMAND_HEADER_RESIZING            = wxEVT_HEADER_RESIZING
2640wxEVT_COMMAND_HEADER_END_RESIZE          = wxEVT_HEADER_END_RESIZE
2641wxEVT_COMMAND_HEADER_BEGIN_REORDER       = wxEVT_HEADER_BEGIN_REORDER
2642wxEVT_COMMAND_HEADER_END_REORDER         = wxEVT_HEADER_END_REORDER
2643wxEVT_COMMAND_HEADER_DRAGGING_CANCELLED  = wxEVT_HEADER_DRAGGING_CANCELLED
2644
2645EVT_SEARCHCTRL_CANCEL_BTN = wx.PyEventBinder( wxEVT_SEARCHCTRL_CANCEL_BTN, 1)
2646EVT_SEARCHCTRL_SEARCH_BTN = wx.PyEventBinder( wxEVT_SEARCHCTRL_SEARCH_BTN, 1)
2647
2648# deprecated wxEVT aliases
2649wxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN  = wxEVT_SEARCHCTRL_CANCEL_BTN
2650wxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN  = wxEVT_SEARCHCTRL_SEARCH_BTN
2651
2652def _RadioBox_GetItemLabel(self, n):
2653    """
2654    GetItemLabel(self, n) -> string
2655
2656    Return the text of the n'th item in the radio box.
2657    """
2658    return self.GetString(n)
2659RadioBox.GetItemLabel = _RadioBox_GetItemLabel
2660del _RadioBox_GetItemLabel
2661def _RadioBox_SetItemLabel(self, n, text):
2662    """
2663    SetItemLabel(self, n, text)
2664
2665    Set the text of the n'th item in the radio box.
2666    """
2667    self.SetString(n, text)
2668RadioBox.SetItemLabel = _RadioBox_SetItemLabel
2669del _RadioBox_SetItemLabel
2670def _Slider_GetRange(self):
2671    return (self.GetMin(), self.GetMax())
2672Slider.GetRange = _Slider_GetRange
2673del _Slider_GetRange
2674Slider.Range = property(Slider.GetRange)
2675def _SpinButton_GetRange(self):
2676    return (self.GetMin(), self.GetMax())
2677SpinButton.GetRange = _SpinButton_GetRange
2678del _SpinButton_GetRange
2679def _SpinButton_SetMin(self, minVal):
2680    self.SetRange(minVal, self.GetMax())
2681SpinButton.SetMin = _SpinButton_SetMin
2682del _SpinButton_SetMin
2683def _SpinButton_SetMax(self, maxVal):
2684    self.SetRange(self.GetMin(), maxVal)
2685SpinButton.SetMax = _SpinButton_SetMax
2686del _SpinButton_SetMax
2687SpinButton.Max = property(SpinButton.GetMax, SpinButton.SetMax)
2688SpinButton.Min = property(SpinButton.GetMin, SpinButton.SetMin)
2689SpinButton.Range = property(SpinButton.GetRange)
2690EVT_SPIN_UP   = wx.PyEventBinder( wxEVT_SPIN_UP, 1)
2691EVT_SPIN_DOWN = wx.PyEventBinder( wxEVT_SPIN_DOWN, 1)
2692EVT_SPIN      = wx.PyEventBinder( wxEVT_SPIN, 1)
2693
2694def _SpinCtrl_GetRange(self):
2695    return (self.GetMin(), self.GetMax())
2696SpinCtrl.GetRange = _SpinCtrl_GetRange
2697del _SpinCtrl_GetRange
2698def _SpinCtrl_SetMin(self, minVal):
2699    self.SetRange(minVal, self.GetMax())
2700SpinCtrl.SetMin = _SpinCtrl_SetMin
2701del _SpinCtrl_SetMin
2702def _SpinCtrl_SetMax(self, maxVal):
2703    self.SetRange(self.GetMin(), maxVal)
2704SpinCtrl.SetMax = _SpinCtrl_SetMax
2705del _SpinCtrl_SetMax
2706SpinCtrl.Max = property(SpinCtrl.GetMax, SpinCtrl.SetMax)
2707SpinCtrl.Min = property(SpinCtrl.GetMin, SpinCtrl.SetMin)
2708SpinCtrl.Range = property(SpinCtrl.GetRange)
2709def _SpinCtrlDouble_GetRange(self):
2710    return (self.GetMin(), self.GetMax())
2711SpinCtrlDouble.GetRange = _SpinCtrlDouble_GetRange
2712del _SpinCtrlDouble_GetRange
2713def _SpinCtrlDouble_SetMin(self, minVal):
2714    self.SetRange(minVal, self.GetMax())
2715SpinCtrlDouble.SetMin = _SpinCtrlDouble_SetMin
2716del _SpinCtrlDouble_SetMin
2717def _SpinCtrlDouble_SetMax(self, maxVal):
2718    self.SetRange(self.GetMin(), maxVal)
2719SpinCtrlDouble.SetMax = _SpinCtrlDouble_SetMax
2720del _SpinCtrlDouble_SetMax
2721SpinCtrlDouble.Max = property(SpinCtrlDouble.GetMax, SpinCtrlDouble.SetMax)
2722SpinCtrlDouble.Min = property(SpinCtrlDouble.GetMin, SpinCtrlDouble.SetMin)
2723SpinCtrlDouble.Range = property(SpinCtrlDouble.GetRange)
2724EVT_SPINCTRL = wx.PyEventBinder( wxEVT_SPINCTRL, 1)
2725EVT_SPINCTRLDOUBLE = wx.PyEventBinder( wxEVT_SPINCTRLDOUBLE, 1)
2726
2727# deprecated wxEVT aliases
2728wxEVT_COMMAND_SPINCTRL_UPDATED        = wxEVT_SPINCTRL
2729wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED  = wxEVT_SPINCTRLDOUBLE
2730
2731EVT_TOGGLEBUTTON = PyEventBinder(wxEVT_TOGGLEBUTTON, 1)
2732
2733# deprecated wxEVT alias
2734wxEVT_COMMAND_TOGGLEBUTTON_CLICKED   = wxEVT_TOGGLEBUTTON
2735
2736def _ToolBar_AddSimpleTool(self, toolId, bitmap, shortHelpString="", longHelpString="", isToggle=0):
2737    """
2738    Old style method to add a tool to the toolbar.
2739    """
2740    kind = wx.ITEM_NORMAL
2741    if isToggle: kind = wx.ITEM_CHECK
2742    return self.AddTool(toolId, '', bitmap, wx.NullBitmap, kind,
2743                        shortHelpString, longHelpString)
2744ToolBar.AddSimpleTool = wx.deprecated(_ToolBar_AddSimpleTool, "Use :meth:`AddTool` instead.")
2745del _ToolBar_AddSimpleTool
2746def _ToolBar_AddLabelTool(self, id, label, bitmap, bmpDisabled=wx.NullBitmap, kind=wx.ITEM_NORMAL, shortHelp="", longHelp="", clientData=None):
2747    """
2748    Old style method to add a tool in the toolbar.
2749    """
2750    return self.AddTool(id, label, bitmap, bmpDisabled, kind,
2751                        shortHelp, longHelp, clientData)
2752ToolBar.AddLabelTool = wx.deprecated(_ToolBar_AddLabelTool, "Use :meth:`AddTool` instead.")
2753del _ToolBar_AddLabelTool
2754def _ToolBar_InsertSimpleTool(self, pos, toolId, bitmap, shortHelpString="", longHelpString="", isToggle=0):
2755    """
2756    Old style method to insert a tool in the toolbar.
2757    """
2758    kind = wx.ITEM_NORMAL
2759    if isToggle: kind = wx.ITEM_CHECK
2760    return self.InsertTool(pos, toolId, '', bitmap, wx.NullBitmap, kind,
2761                           shortHelpString, longHelpString)
2762ToolBar.InsertSimpleTool = wx.deprecated(_ToolBar_InsertSimpleTool, "Use :meth:`InsertTool` instead.")
2763del _ToolBar_InsertSimpleTool
2764def _ToolBar_InsertLabelTool(self, pos, id, label, bitmap, bmpDisabled=wx.NullBitmap, kind=wx.ITEM_NORMAL, shortHelp="", longHelp="", clientData=None):
2765    """
2766    Old style method to insert a tool in the toolbar.
2767    """
2768    return self.InsertTool(pos, id, label, bitmap, bmpDisabled, kind,
2769                           shortHelp, longHelp, clientData)
2770ToolBar.InsertLabelTool = wx.deprecated(_ToolBar_InsertLabelTool, "Use :meth:`InsertTool` instead.")
2771del _ToolBar_InsertLabelTool
2772ListCtrl.FindItemData = wx.deprecated(ListCtrl.FindItem, "Use FindItem instead.")
2773
2774ListCtrl.FindItemAtPos = wx.deprecated(ListCtrl.FindItem, "Use FindItem instead.")
2775
2776ListCtrl.InsertStringItem = wx.deprecated(ListCtrl.InsertItem, "Use InsertItem instead.")
2777
2778ListCtrl.InsertImageItem = wx.deprecated(ListCtrl.InsertItem, "Use InsertItem instead.")
2779
2780ListCtrl.InsertImageStringItem = wx.deprecated(ListCtrl.InsertItem, "Use InsertItem instead.")
2781
2782ListCtrl.SetStringItem = wx.deprecated(ListCtrl.SetItem, "Use SetItem instead.")
2783
2784def _ListCtrl_Select(self, idx, on=1):
2785    """
2786    Selects/deselects an item.
2787    """
2788    if on: state = wx.LIST_STATE_SELECTED
2789    else: state = 0
2790    self.SetItemState(idx, state, wx.LIST_STATE_SELECTED)
2791ListCtrl.Select = _ListCtrl_Select
2792del _ListCtrl_Select
2793def _ListCtrl_Focus(self, idx):
2794    """
2795    Focus and show the given item.
2796    """
2797    self.SetItemState(idx, wx.LIST_STATE_FOCUSED, wx.LIST_STATE_FOCUSED)
2798    self.EnsureVisible(idx)
2799ListCtrl.Focus = _ListCtrl_Focus
2800del _ListCtrl_Focus
2801def _ListCtrl_GetFocusedItem(self):
2802    """
2803    Gets the currently focused item or -1 if none is focused.
2804    """
2805    return self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_FOCUSED)
2806ListCtrl.GetFocusedItem = _ListCtrl_GetFocusedItem
2807del _ListCtrl_GetFocusedItem
2808def _ListCtrl_GetFirstSelected(self, *args):
2809    """
2810    Returns the first selected item, or -1 when none is selected.
2811    """
2812    return self.GetNextSelected(-1)
2813ListCtrl.GetFirstSelected = _ListCtrl_GetFirstSelected
2814del _ListCtrl_GetFirstSelected
2815def _ListCtrl_GetNextSelected(self, item):
2816    """
2817    Returns subsequent selected items, or -1 when no more are selected.
2818    """
2819    return self.GetNextItem(item, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
2820ListCtrl.GetNextSelected = _ListCtrl_GetNextSelected
2821del _ListCtrl_GetNextSelected
2822def _ListCtrl_IsSelected(self, idx):
2823    """
2824    Returns ``True`` if the item is selected.
2825    """
2826    return (self.GetItemState(idx, wx.LIST_STATE_SELECTED) & wx.LIST_STATE_SELECTED) != 0
2827ListCtrl.IsSelected = _ListCtrl_IsSelected
2828del _ListCtrl_IsSelected
2829def _ListCtrl_SetColumnImage(self, col, image):
2830    item = self.GetColumn(col)
2831    # preserve all other attributes too
2832    item.SetMask( wx.LIST_MASK_STATE |
2833                  wx.LIST_MASK_TEXT  |
2834                  wx.LIST_MASK_IMAGE |
2835                  wx.LIST_MASK_DATA  |
2836                  wx.LIST_SET_ITEM   |
2837                  wx.LIST_MASK_WIDTH |
2838                  wx.LIST_MASK_FORMAT )
2839    item.SetImage(image)
2840    self.SetColumn(col, item)
2841ListCtrl.SetColumnImage = _ListCtrl_SetColumnImage
2842del _ListCtrl_SetColumnImage
2843def _ListCtrl_ClearColumnImage(self, col):
2844    self.SetColumnImage(col, -1)
2845ListCtrl.ClearColumnImage = _ListCtrl_ClearColumnImage
2846del _ListCtrl_ClearColumnImage
2847def _ListCtrl_Append(self, entry):
2848    """
2849    Append an item to the list control.  The `entry` parameter should be a
2850    sequence with an item for each column
2851    """
2852    if len(entry):
2853        from six import text_type
2854        pos = self.InsertItem(self.GetItemCount(), text_type(entry[0]))
2855        for i in range(1, len(entry)):
2856            self.SetItem(pos, i, text_type(entry[i]))
2857        return pos
2858ListCtrl.Append = _ListCtrl_Append
2859del _ListCtrl_Append
2860ListCtrl.FocusedItem = property(ListCtrl.GetFocusedItem)
2861EVT_LIST_BEGIN_DRAG        = PyEventBinder(wxEVT_LIST_BEGIN_DRAG       , 1)
2862EVT_LIST_BEGIN_RDRAG       = PyEventBinder(wxEVT_LIST_BEGIN_RDRAG      , 1)
2863EVT_LIST_BEGIN_LABEL_EDIT  = PyEventBinder(wxEVT_LIST_BEGIN_LABEL_EDIT , 1)
2864EVT_LIST_END_LABEL_EDIT    = PyEventBinder(wxEVT_LIST_END_LABEL_EDIT   , 1)
2865EVT_LIST_DELETE_ITEM       = PyEventBinder(wxEVT_LIST_DELETE_ITEM      , 1)
2866EVT_LIST_DELETE_ALL_ITEMS  = PyEventBinder(wxEVT_LIST_DELETE_ALL_ITEMS , 1)
2867EVT_LIST_ITEM_SELECTED     = PyEventBinder(wxEVT_LIST_ITEM_SELECTED    , 1)
2868EVT_LIST_ITEM_DESELECTED   = PyEventBinder(wxEVT_LIST_ITEM_DESELECTED  , 1)
2869EVT_LIST_KEY_DOWN          = PyEventBinder(wxEVT_LIST_KEY_DOWN         , 1)
2870EVT_LIST_INSERT_ITEM       = PyEventBinder(wxEVT_LIST_INSERT_ITEM      , 1)
2871EVT_LIST_COL_CLICK         = PyEventBinder(wxEVT_LIST_COL_CLICK        , 1)
2872EVT_LIST_ITEM_RIGHT_CLICK  = PyEventBinder(wxEVT_LIST_ITEM_RIGHT_CLICK , 1)
2873EVT_LIST_ITEM_MIDDLE_CLICK = PyEventBinder(wxEVT_LIST_ITEM_MIDDLE_CLICK, 1)
2874EVT_LIST_ITEM_ACTIVATED    = PyEventBinder(wxEVT_LIST_ITEM_ACTIVATED   , 1)
2875EVT_LIST_CACHE_HINT        = PyEventBinder(wxEVT_LIST_CACHE_HINT       , 1)
2876EVT_LIST_COL_RIGHT_CLICK   = PyEventBinder(wxEVT_LIST_COL_RIGHT_CLICK  , 1)
2877EVT_LIST_COL_BEGIN_DRAG    = PyEventBinder(wxEVT_LIST_COL_BEGIN_DRAG   , 1)
2878EVT_LIST_COL_DRAGGING      = PyEventBinder(wxEVT_LIST_COL_DRAGGING     , 1)
2879EVT_LIST_COL_END_DRAG      = PyEventBinder(wxEVT_LIST_COL_END_DRAG     , 1)
2880EVT_LIST_ITEM_FOCUSED      = PyEventBinder(wxEVT_LIST_ITEM_FOCUSED     , 1)
2881
2882# deprecated wxEVT aliases
2883wxEVT_COMMAND_LIST_BEGIN_DRAG         = wxEVT_LIST_BEGIN_DRAG
2884wxEVT_COMMAND_LIST_BEGIN_RDRAG        = wxEVT_LIST_BEGIN_RDRAG
2885wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT   = wxEVT_LIST_BEGIN_LABEL_EDIT
2886wxEVT_COMMAND_LIST_END_LABEL_EDIT     = wxEVT_LIST_END_LABEL_EDIT
2887wxEVT_COMMAND_LIST_DELETE_ITEM        = wxEVT_LIST_DELETE_ITEM
2888wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS   = wxEVT_LIST_DELETE_ALL_ITEMS
2889wxEVT_COMMAND_LIST_ITEM_SELECTED      = wxEVT_LIST_ITEM_SELECTED
2890wxEVT_COMMAND_LIST_ITEM_DESELECTED    = wxEVT_LIST_ITEM_DESELECTED
2891wxEVT_COMMAND_LIST_KEY_DOWN           = wxEVT_LIST_KEY_DOWN
2892wxEVT_COMMAND_LIST_INSERT_ITEM        = wxEVT_LIST_INSERT_ITEM
2893wxEVT_COMMAND_LIST_COL_CLICK          = wxEVT_LIST_COL_CLICK
2894wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK   = wxEVT_LIST_ITEM_RIGHT_CLICK
2895wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK  = wxEVT_LIST_ITEM_MIDDLE_CLICK
2896wxEVT_COMMAND_LIST_ITEM_ACTIVATED     = wxEVT_LIST_ITEM_ACTIVATED
2897wxEVT_COMMAND_LIST_CACHE_HINT         = wxEVT_LIST_CACHE_HINT
2898wxEVT_COMMAND_LIST_COL_RIGHT_CLICK    = wxEVT_LIST_COL_RIGHT_CLICK
2899wxEVT_COMMAND_LIST_COL_BEGIN_DRAG     = wxEVT_LIST_COL_BEGIN_DRAG
2900wxEVT_COMMAND_LIST_COL_DRAGGING       = wxEVT_LIST_COL_DRAGGING
2901wxEVT_COMMAND_LIST_COL_END_DRAG       = wxEVT_LIST_COL_END_DRAG
2902wxEVT_COMMAND_LIST_ITEM_FOCUSED       = wxEVT_LIST_ITEM_FOCUSED
2903
2904def _TreeItemId___hash__(self):
2905    return hash(int(self.GetID()))
2906TreeItemId.__hash__ = _TreeItemId___hash__
2907del _TreeItemId___hash__
2908TreeCtrl.GetItemPyData = wx.deprecated(TreeCtrl.GetItemData, 'Use GetItemData instead.')
2909TreeCtrl.SetItemPyData = wx.deprecated(TreeCtrl.SetItemData, 'Use SetItemData instead.')
2910TreeCtrl.GetPyData = wx.deprecated(TreeCtrl.GetItemData, 'Use GetItemData instead.')
2911TreeCtrl.SetPyData = wx.deprecated(TreeCtrl.SetItemData, 'Use SetItemData instead.')
2912
2913def TreeItemData(data):
2914    return data
2915TreeItemData = deprecated(TreeItemData, "The TreeItemData class no longer exists, just pass your object directly to the tree instead.")
2916
2917EVT_TREE_BEGIN_DRAG        = PyEventBinder(wxEVT_TREE_BEGIN_DRAG       , 1)
2918EVT_TREE_BEGIN_RDRAG       = PyEventBinder(wxEVT_TREE_BEGIN_RDRAG      , 1)
2919EVT_TREE_BEGIN_LABEL_EDIT  = PyEventBinder(wxEVT_TREE_BEGIN_LABEL_EDIT , 1)
2920EVT_TREE_END_LABEL_EDIT    = PyEventBinder(wxEVT_TREE_END_LABEL_EDIT   , 1)
2921EVT_TREE_DELETE_ITEM       = PyEventBinder(wxEVT_TREE_DELETE_ITEM      , 1)
2922EVT_TREE_GET_INFO          = PyEventBinder(wxEVT_TREE_GET_INFO         , 1)
2923EVT_TREE_SET_INFO          = PyEventBinder(wxEVT_TREE_SET_INFO         , 1)
2924EVT_TREE_ITEM_EXPANDED     = PyEventBinder(wxEVT_TREE_ITEM_EXPANDED    , 1)
2925EVT_TREE_ITEM_EXPANDING    = PyEventBinder(wxEVT_TREE_ITEM_EXPANDING   , 1)
2926EVT_TREE_ITEM_COLLAPSED    = PyEventBinder(wxEVT_TREE_ITEM_COLLAPSED   , 1)
2927EVT_TREE_ITEM_COLLAPSING   = PyEventBinder(wxEVT_TREE_ITEM_COLLAPSING  , 1)
2928EVT_TREE_SEL_CHANGED       = PyEventBinder(wxEVT_TREE_SEL_CHANGED      , 1)
2929EVT_TREE_SEL_CHANGING      = PyEventBinder(wxEVT_TREE_SEL_CHANGING     , 1)
2930EVT_TREE_KEY_DOWN          = PyEventBinder(wxEVT_TREE_KEY_DOWN         , 1)
2931EVT_TREE_ITEM_ACTIVATED    = PyEventBinder(wxEVT_TREE_ITEM_ACTIVATED   , 1)
2932EVT_TREE_ITEM_RIGHT_CLICK  = PyEventBinder(wxEVT_TREE_ITEM_RIGHT_CLICK , 1)
2933EVT_TREE_ITEM_MIDDLE_CLICK = PyEventBinder(wxEVT_TREE_ITEM_MIDDLE_CLICK, 1)
2934EVT_TREE_END_DRAG          = PyEventBinder(wxEVT_TREE_END_DRAG         , 1)
2935EVT_TREE_STATE_IMAGE_CLICK = PyEventBinder(wxEVT_TREE_STATE_IMAGE_CLICK, 1)
2936EVT_TREE_ITEM_GETTOOLTIP   = PyEventBinder(wxEVT_TREE_ITEM_GETTOOLTIP,   1)
2937EVT_TREE_ITEM_MENU         = PyEventBinder(wxEVT_TREE_ITEM_MENU,         1)
2938
2939# deprecated wxEVT aliases
2940wxEVT_COMMAND_TREE_BEGIN_DRAG         = wxEVT_TREE_BEGIN_DRAG
2941wxEVT_COMMAND_TREE_BEGIN_RDRAG        = wxEVT_TREE_BEGIN_RDRAG
2942wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT   = wxEVT_TREE_BEGIN_LABEL_EDIT
2943wxEVT_COMMAND_TREE_END_LABEL_EDIT     = wxEVT_TREE_END_LABEL_EDIT
2944wxEVT_COMMAND_TREE_DELETE_ITEM        = wxEVT_TREE_DELETE_ITEM
2945wxEVT_COMMAND_TREE_GET_INFO           = wxEVT_TREE_GET_INFO
2946wxEVT_COMMAND_TREE_SET_INFO           = wxEVT_TREE_SET_INFO
2947wxEVT_COMMAND_TREE_ITEM_EXPANDED      = wxEVT_TREE_ITEM_EXPANDED
2948wxEVT_COMMAND_TREE_ITEM_EXPANDING     = wxEVT_TREE_ITEM_EXPANDING
2949wxEVT_COMMAND_TREE_ITEM_COLLAPSED     = wxEVT_TREE_ITEM_COLLAPSED
2950wxEVT_COMMAND_TREE_ITEM_COLLAPSING    = wxEVT_TREE_ITEM_COLLAPSING
2951wxEVT_COMMAND_TREE_SEL_CHANGED        = wxEVT_TREE_SEL_CHANGED
2952wxEVT_COMMAND_TREE_SEL_CHANGING       = wxEVT_TREE_SEL_CHANGING
2953wxEVT_COMMAND_TREE_KEY_DOWN           = wxEVT_TREE_KEY_DOWN
2954wxEVT_COMMAND_TREE_ITEM_ACTIVATED     = wxEVT_TREE_ITEM_ACTIVATED
2955wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK   = wxEVT_TREE_ITEM_RIGHT_CLICK
2956wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK  = wxEVT_TREE_ITEM_MIDDLE_CLICK
2957wxEVT_COMMAND_TREE_END_DRAG           = wxEVT_TREE_END_DRAG
2958wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK  = wxEVT_TREE_STATE_IMAGE_CLICK
2959wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP    = wxEVT_TREE_ITEM_GETTOOLTIP
2960wxEVT_COMMAND_TREE_ITEM_MENU          = wxEVT_TREE_ITEM_MENU
2961
2962EVT_COLOURPICKER_CHANGED = wx.PyEventBinder( wxEVT_COLOURPICKER_CHANGED, 1 )
2963
2964# deprecated wxEVT alias
2965wxEVT_COMMAND_COLOURPICKER_CHANGED  = wxEVT_COLOURPICKER_CHANGED
2966
2967EVT_FILEPICKER_CHANGED = wx.PyEventBinder( wxEVT_FILEPICKER_CHANGED, 1 )
2968EVT_DIRPICKER_CHANGED = wx.PyEventBinder( wxEVT_DIRPICKER_CHANGED, 1 )
2969
2970# deprecated wxEVT aliases
2971wxEVT_COMMAND_FILEPICKER_CHANGED   = wxEVT_FILEPICKER_CHANGED
2972wxEVT_COMMAND_DIRPICKER_CHANGED    = wxEVT_DIRPICKER_CHANGED
2973
2974EVT_FONTPICKER_CHANGED = wx.PyEventBinder( wxEVT_FONTPICKER_CHANGED, 1 )
2975
2976# deprecated wxEVT alias
2977wxEVT_COMMAND_FONTPICKER_CHANGED  = wxEVT_FONTPICKER_CHANGED
2978
2979if 'wxMac' in wx.PlatformInfo:
2980    class ColourPickerCtrl(PickerBase):
2981        '''
2982        This control allows the user to select a colour. The
2983        implementation varies by platform but is usually a button which
2984        brings up a `wx.ColourDialog` when clicked.
2985
2986
2987        Window Styles
2988        -------------
2989
2990            ======================  ============================================
2991            wx.CLRP_DEFAULT         Default style.
2992            wx.CLRP_USE_TEXTCTRL    Creates a text control to the left of the
2993                                    picker button which is completely managed
2994                                    by the `wx.ColourPickerCtrl` and which can
2995                                    be used by the user to specify a colour.
2996                                    The text control is automatically synchronized
2997                                    with the button's value. Use functions defined in
2998                                    `wx.PickerBase` to modify the text control.
2999            wx.CLRP_SHOW_LABEL      Shows the colour in HTML form (AABBCC) as the
3000                                    colour button label (instead of no label at all).
3001            ======================  ============================================
3002
3003        Events
3004        ------
3005
3006            ========================  ==========================================
3007            EVT_COLOURPICKER_CHANGED  The user changed the colour selected in the
3008                                      control either using the button or using the
3009                                      text control (see wx.CLRP_USE_TEXTCTRL; note
3010                                      that in this case the event is fired only if
3011                                      the user's input is valid, i.e. recognizable).
3012            ========================  ==========================================
3013        '''
3014
3015        # ColourData object to be shared by all colour pickers, so they can
3016        # share the custom colours
3017        _colourData = None
3018
3019        #--------------------------------------------------
3020        class ColourPickerButton(BitmapButton):
3021            def __init__(self, parent, id=-1, colour=wx.BLACK,
3022                         pos=wx.DefaultPosition, size=wx.DefaultSize,
3023                         style = CLRP_DEFAULT_STYLE,
3024                         validator = wx.DefaultValidator,
3025                         name = "colourpickerwidget"):
3026
3027                wx.BitmapButton.__init__(self, parent, id, wx.Bitmap(1,1),
3028                                         pos, size, style, validator, name)
3029                self.SetColour(colour)
3030                self.InvalidateBestSize()
3031                self.SetInitialSize(size)
3032                self.Bind(wx.EVT_BUTTON, self.OnButtonClick)
3033
3034                if ColourPickerCtrl._colourData is None:
3035                    ColourPickerCtrl._colourData = wx.ColourData()
3036                    ColourPickerCtrl._colourData.SetChooseFull(True)
3037                    grey = 0
3038                    for i in range(16):
3039                        c = wx.Colour(grey, grey, grey)
3040                        ColourPickerCtrl._colourData.SetCustomColour(i, c)
3041                        grey += 16
3042
3043            def SetColour(self, colour):
3044                # force a copy, in case the _colorData is shared
3045                self.colour = wx.Colour(colour)
3046                bmp = self._makeBitmap()
3047                self.SetBitmapLabel(bmp)
3048
3049            def GetColour(self):
3050                return self.colour
3051
3052            def OnButtonClick(self, evt):
3053                ColourPickerCtrl._colourData.SetColour(self.colour)
3054                dlg = wx.ColourDialog(self, ColourPickerCtrl._colourData)
3055                if dlg.ShowModal() == wx.ID_OK:
3056                    ColourPickerCtrl._colourData = dlg.GetColourData()
3057                    self.SetColour(ColourPickerCtrl._colourData.GetColour())
3058                    evt = wx.ColourPickerEvent(self, self.GetId(), self.GetColour())
3059                    self.GetEventHandler().ProcessEvent(evt)
3060
3061            def _makeBitmap(self):
3062                width = height = 24
3063                bg = self.GetColour()
3064                if self.HasFlag(CLRP_SHOW_LABEL):
3065                    w, h = self.GetTextExtent(bg.GetAsString(wx.C2S_HTML_SYNTAX))
3066                    width += w
3067                bmp = wx.Bitmap(width, height)
3068                dc = wx.MemoryDC(bmp)
3069                dc.SetBackground(wx.Brush(self.colour))
3070                dc.Clear()
3071                if self.HasFlag(CLRP_SHOW_LABEL):
3072                    from wx.lib.colourutils import BestLabelColour
3073                    fg = BestLabelColour(bg)
3074                    dc.SetTextForeground(fg)
3075                    dc.DrawText(bg.GetAsString(wx.C2S_HTML_SYNTAX),
3076                                (width - w)/2, (height - h)/2)
3077                return bmp
3078
3079        #--------------------------------------------------
3080
3081        def __init__(self, parent, id=-1, colour=wx.BLACK,
3082                     pos=wx.DefaultPosition, size=wx.DefaultSize,
3083                     style = CLRP_DEFAULT_STYLE,
3084                     validator = wx.DefaultValidator,
3085                     name = "colourpicker"):
3086            if type(colour) != wx.Colour:
3087                colour = wx.Colour(colour)
3088            wx.PickerBase.__init__(self)
3089            self.CreateBase(parent, id, colour.GetAsString(),
3090                            pos, size, style, validator, name)
3091            widget = ColourPickerCtrl.ColourPickerButton(
3092                self, -1, colour, style=self.GetPickerStyle(style))
3093            self.SetPickerCtrl(widget)
3094            widget.Bind(wx.EVT_COLOURPICKER_CHANGED, self.OnColourChange)
3095            self.PostCreation()
3096
3097
3098        def GetColour(self):
3099            '''Set the displayed colour.'''
3100            return self.GetPickerCtrl().GetColour()
3101
3102        def SetColour(self, colour):
3103            '''Returns the currently selected colour.'''
3104            self.GetPickerCtrl().SetColour(colour)
3105            self.UpdateTextCtrlFromPicker()
3106        Colour = property(GetColour, SetColour)
3107
3108
3109        def UpdatePickerFromTextCtrl(self):
3110            col = wx.Colour(self.GetTextCtrl().GetValue())
3111            if not col.IsOk():
3112                return
3113            if self.GetColour() != col:
3114                self.GetPickerCtrl().SetColour(col)
3115                evt = wx.ColourPickerEvent(self, self.GetId(), self.GetColour())
3116                self.GetEventHandler().ProcessEvent(evt)
3117
3118        def UpdateTextCtrlFromPicker(self):
3119            if not self.GetTextCtrl():
3120                return
3121            self.GetTextCtrl().SetValue(self.GetColour().GetAsString())
3122
3123        def GetPickerStyle(self, style):
3124            return style & CLRP_SHOW_LABEL
3125
3126        def OnColourChange(self, evt):
3127            self.UpdateTextCtrlFromPicker()
3128            evt = wx.ColourPickerEvent(self, self.GetId(), self.GetColour())
3129            self.GetEventHandler().ProcessEvent(evt)
3130
3131EVT_FILECTRL_SELECTIONCHANGED = wx.PyEventBinder( wxEVT_FILECTRL_SELECTIONCHANGED, 1)
3132EVT_FILECTRL_FILEACTIVATED = wx.PyEventBinder( wxEVT_FILECTRL_FILEACTIVATED, 1)
3133EVT_FILECTRL_FOLDERCHANGED = wx.PyEventBinder( wxEVT_FILECTRL_FOLDERCHANGED, 1)
3134EVT_FILECTRL_FILTERCHANGED = wx.PyEventBinder( wxEVT_FILECTRL_FILTERCHANGED, 1)
3135
3136EVT_CHOICEBOOK_PAGE_CHANGED  = wx.PyEventBinder( wxEVT_CHOICEBOOK_PAGE_CHANGED, 1 )
3137EVT_CHOICEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_CHOICEBOOK_PAGE_CHANGING, 1 )
3138
3139# deprecated wxEVT aliases
3140wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED   = wxEVT_CHOICEBOOK_PAGE_CHANGED
3141wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING  = wxEVT_CHOICEBOOK_PAGE_CHANGING
3142
3143EVT_LISTBOOK_PAGE_CHANGED  = wx.PyEventBinder( wxEVT_LISTBOOK_PAGE_CHANGED, 1 )
3144EVT_LISTBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_LISTBOOK_PAGE_CHANGING, 1 )
3145
3146# deprecated wxEVT aliases
3147wxEVT_COMMAND_LISTBOOK_PAGE_CHANGED   = wxEVT_LISTBOOK_PAGE_CHANGED
3148wxEVT_COMMAND_LISTBOOK_PAGE_CHANGING  = wxEVT_LISTBOOK_PAGE_CHANGING
3149
3150EVT_TOOLBOOK_PAGE_CHANGED  = wx.PyEventBinder( wxEVT_TOOLBOOK_PAGE_CHANGED, 1 )
3151EVT_TOOLBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_TOOLBOOK_PAGE_CHANGING, 1 )
3152
3153# deprecated wxEVT aliases
3154wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED   = wxEVT_TOOLBOOK_PAGE_CHANGED
3155wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING  = wxEVT_TOOLBOOK_PAGE_CHANGING
3156
3157EVT_TREEBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_TREEBOOK_PAGE_CHANGED, 1 )
3158EVT_TREEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_TREEBOOK_PAGE_CHANGING, 1)
3159EVT_TREEBOOK_NODE_COLLAPSED = wx.PyEventBinder( wxEVT_TREEBOOK_NODE_COLLAPSED, 1 )
3160EVT_TREEBOOK_NODE_EXPANDED = wx.PyEventBinder( wxEVT_TREEBOOK_NODE_EXPANDED, 1 )
3161
3162# deprecated wxEVT aliases
3163wxEVT_COMMAND_TREEBOOK_PAGE_CHANGED    = wxEVT_TREEBOOK_PAGE_CHANGED
3164wxEVT_COMMAND_TREEBOOK_PAGE_CHANGING   = wxEVT_TREEBOOK_PAGE_CHANGING
3165wxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED  = wxEVT_TREEBOOK_NODE_COLLAPSED
3166wxEVT_COMMAND_TREEBOOK_NODE_EXPANDED   = wxEVT_TREEBOOK_NODE_EXPANDED
3167
3168def _Dialog___enter__(self):
3169    return self
3170Dialog.__enter__ = _Dialog___enter__
3171del _Dialog___enter__
3172def _Dialog___exit__(self, exc_type, exc_val, exc_tb):
3173    self.Destroy()
3174Dialog.__exit__ = _Dialog___exit__
3175del _Dialog___exit__
3176EVT_DIRCTRL_SELECTIONCHANGED = wx.PyEventBinder( wxEVT_DIRCTRL_SELECTIONCHANGED, 1 )
3177EVT_DIRCTRL_FILEACTIVATED = wx.PyEventBinder( wxEVT_DIRCTRL_FILEACTIVATED, 1 )
3178
3179EVT_FIND = wx.PyEventBinder( wxEVT_FIND, 1 )
3180EVT_FIND_NEXT = wx.PyEventBinder( wxEVT_FIND_NEXT, 1 )
3181EVT_FIND_REPLACE = wx.PyEventBinder( wxEVT_FIND_REPLACE, 1 )
3182EVT_FIND_REPLACE_ALL = wx.PyEventBinder( wxEVT_FIND_REPLACE_ALL, 1 )
3183EVT_FIND_CLOSE = wx.PyEventBinder( wxEVT_FIND_CLOSE, 1 )
3184
3185# deprecated wxEVT aliases
3186wxEVT_COMMAND_FIND              = wxEVT_FIND
3187wxEVT_COMMAND_FIND_NEXT         = wxEVT_FIND_NEXT
3188wxEVT_COMMAND_FIND_REPLACE      = wxEVT_FIND_REPLACE
3189wxEVT_COMMAND_FIND_REPLACE_ALL  = wxEVT_FIND_REPLACE_ALL
3190wxEVT_COMMAND_FIND_CLOSE        = wxEVT_FIND_CLOSE
3191
3192EVT_POWER_SUSPENDING       = wx.PyEventBinder( wxEVT_POWER_SUSPENDING , 1 )
3193EVT_POWER_SUSPENDED        = wx.PyEventBinder( wxEVT_POWER_SUSPENDED , 1 )
3194EVT_POWER_SUSPEND_CANCEL   = wx.PyEventBinder( wxEVT_POWER_SUSPEND_CANCEL , 1 )
3195EVT_POWER_RESUME           = wx.PyEventBinder( wxEVT_POWER_RESUME , 1 )
3196
3197def _WindowDisabler___enter__(self):
3198    return self
3199WindowDisabler.__enter__ = _WindowDisabler___enter__
3200del _WindowDisabler___enter__
3201def _WindowDisabler___exit__(self, exc_type, exc_val, exc_tb):
3202    pass
3203WindowDisabler.__exit__ = _WindowDisabler___exit__
3204del _WindowDisabler___exit__
3205def _BusyCursor___enter__(self):
3206    return self
3207BusyCursor.__enter__ = _BusyCursor___enter__
3208del _BusyCursor___enter__
3209def _BusyCursor___exit__(self, exc_type, exc_val, exc_tb):
3210    pass
3211BusyCursor.__exit__ = _BusyCursor___exit__
3212del _BusyCursor___exit__
3213EVT_END_PROCESS = wx.PyEventBinder( wxEVT_END_PROCESS )
3214
3215PrintPreview.Ok = wx.deprecated(PrintPreview.IsOk, 'Use IsOk instead.')
3216
3217PyPrintPreview = wx.deprecated(PrintPreview, 'Use PrintPreview instead.')
3218
3219PyPreviewFrame = wx.deprecated(PreviewFrame, 'Use PreviewFrame instead.')
3220
3221PyPreviewControlBar = wx.deprecated(PreviewControlBar, 'Use PreviewControlBar instead.')
3222
3223PyPrintout = wx.deprecated(Printout, 'Use Printout instead.')
3224
3225def _BusyInfo___enter__(self):
3226    return self
3227BusyInfo.__enter__ = _BusyInfo___enter__
3228del _BusyInfo___enter__
3229def _BusyInfo___exit__(self, exc_type, exc_val, exc_tb):
3230    return False
3231BusyInfo.__exit__ = _BusyInfo___exit__
3232del _BusyInfo___exit__
3233def _FileHistoryMenuList___repr__(self):
3234    return "FileHistoryMenuList: " + repr(list(self))
3235FileHistoryMenuList.__repr__ = _FileHistoryMenuList___repr__
3236del _FileHistoryMenuList___repr__
3237def _CommandList___repr__(self):
3238    return "CommandList: " + repr(list(self))
3239CommandList.__repr__ = _CommandList___repr__
3240del _CommandList___repr__
3241EVT_FSWATCHER = wx.PyEventBinder(wxEVT_FSWATCHER)
3242
3243def version():
3244    """
3245    Returns a string containing version and port info
3246    """
3247    if wx.Port == '__WXMSW__':
3248        port = 'msw'
3249    elif wx.Port == '__WXMAC__':
3250        if 'wxOSX-carbon' in wx.PlatformInfo:
3251            port = 'osx-carbon'
3252        else:
3253            port = 'osx-cocoa'
3254    elif wx.Port == '__WXGTK__':
3255        port = 'gtk'
3256        if 'gtk2' in wx.PlatformInfo:
3257            port = 'gtk2'
3258        elif 'gtk3' in wx.PlatformInfo:
3259            port = 'gtk3'
3260    else:
3261        port = '???'
3262    return "%s %s (phoenix) %s" % (wx.VERSION_STRING, port, wx.wxWidgets_version)
3263
3264def CallAfter(callableObj, *args, **kw):
3265    """
3266    Call the specified function after the current and pending event
3267    handlers have been completed.  This is also good for making GUI
3268    method calls from non-GUI threads.  Any extra positional or
3269    keyword args are passed on to the callable when it is called.
3270
3271    :param PyObject callableObj: the callable object
3272    :param args: arguments to be passed to the callable object
3273    :param kw: keywords to be passed to the callable object
3274
3275    .. seealso::
3276        :ref:`wx.CallLater`
3277    """
3278    assert callable(callableObj), "callableObj is not callable"
3279    app = wx.GetApp()
3280    assert app is not None, 'No wx.App created yet'
3281
3282    if not hasattr(app, "_CallAfterId"):
3283        app._CallAfterId = wx.NewEventType()
3284        app.Connect(-1, -1, app._CallAfterId,
3285                    lambda event: event.callable(*event.args, **event.kw) )
3286    evt = wx.PyEvent()
3287    evt.SetEventType(app._CallAfterId)
3288    evt.callable = callableObj
3289    evt.args = args
3290    evt.kw = kw
3291    wx.PostEvent(app, evt)
3292
3293class CallLater(object):
3294    """
3295    A convenience class for :class:`wx.Timer`, that calls the given callable
3296    object once after the given amount of milliseconds, passing any
3297    positional or keyword args.  The return value of the callable is
3298    available after it has been run with the :meth:`~wx.CallLater.GetResult`
3299    method.
3300
3301    If you don't need to get the return value or restart the timer
3302    then there is no need to hold a reference to this object. CallLater
3303    maintains references to its instances while they are running. When they
3304    finish, the internal reference is deleted and the GC is free to collect
3305    naturally.
3306
3307    .. seealso::
3308        :func:`wx.CallAfter`
3309    """
3310    __instances = {}
3311    def __init__(self, millis, callableObj, *args, **kwargs):
3312        """
3313        Constructs a new :class:`wx.CallLater` object.
3314
3315        :param int millis: number of milliseconds to delay until calling the callable object
3316        :param PyObject callableObj: the callable object
3317        :param args: arguments to be passed to the callable object
3318        :param kw: keywords to be passed to the callable object
3319        """
3320        assert callable(callableObj), "callableObj is not callable"
3321        self.millis = millis
3322        self.callable = callableObj
3323        self.SetArgs(*args, **kwargs)
3324        self.runCount = 0
3325        self.running = False
3326        self.hasRun = False
3327        self.result = None
3328        self.timer = None
3329        self.Start()
3330
3331    def __del__(self):
3332        self.Stop()
3333
3334    def Start(self, millis=None, *args, **kwargs):
3335        """
3336        (Re)start the timer
3337
3338        :param int millis: number of milli seconds
3339        :param args: arguments to be passed to the callable object
3340        :param kw: keywords to be passed to the callable object
3341        """
3342        self.hasRun = False
3343        if millis is not None:
3344            self.millis = millis
3345        if args or kwargs:
3346            self.SetArgs(*args, **kwargs)
3347        self.Stop()
3348        CallLater.__instances[self] = "value irrelevant"  # Maintain a reference to avoid GC
3349        self.timer = wx.PyTimer(self.Notify)
3350        self.timer.Start(self.millis, wx.TIMER_ONE_SHOT)
3351        self.running = True
3352
3353    Restart = Start
3354    def Stop(self):
3355        """
3356        Stop and destroy the timer.
3357        """
3358        if self in CallLater.__instances:
3359            del CallLater.__instances[self]
3360        if self.timer is not None:
3361            self.timer.Stop()
3362            self.timer = None
3363
3364    def GetInterval(self):
3365        if self.timer is not None:
3366            return self.timer.GetInterval()
3367        else:
3368            return 0
3369
3370    def IsRunning(self):
3371        return self.timer is not None and self.timer.IsRunning()
3372
3373    def SetArgs(self, *args, **kwargs):
3374        """
3375        (Re)set the args passed to the callable object.  This is
3376        useful in conjunction with :meth:`Start` if
3377        you want to schedule a new call to the same callable
3378        object but with different parameters.
3379
3380        :param args: arguments to be passed to the callable object
3381        :param kw: keywords to be passed to the callable object
3382        """
3383        self.args = args
3384        self.kwargs = kwargs
3385
3386    def HasRun(self):
3387        """
3388        Returns whether or not the callable has run.
3389
3390        :rtype: bool
3391        """
3392        return self.hasRun
3393
3394    def GetResult(self):
3395        """
3396        Returns the value of the callable.
3397
3398        :rtype: a Python object
3399        :return: result from callable
3400        """
3401        return self.result
3402
3403    def Notify(self):
3404        """
3405        The timer has expired so call the callable.
3406        """
3407        if self.callable and getattr(self.callable, 'im_self', True):
3408            self.runCount += 1
3409            self.running = False
3410            self.result = self.callable(*self.args, **self.kwargs)
3411        self.hasRun = True
3412        if not self.running:
3413            # if it wasn't restarted, then cleanup
3414            wx.CallAfter(self.Stop)
3415
3416    Interval = property(GetInterval)
3417    Result = property(GetResult)
3418
3419FutureCall = deprecated(CallLater, 'Use CallLater instead.')
3420
3421def GetDefaultPyEncoding():
3422    return "utf-8"
3423GetDefaultPyEncoding = deprecated(GetDefaultPyEncoding, msg="wxPython now always uses utf-8")
3424
3425