File: colourselect.py

package info (click to toggle)
wxpython4.0 4.0.4%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 211,112 kB
  • sloc: cpp: 888,355; python: 223,130; makefile: 52,087; ansic: 45,780; sh: 3,012; xml: 1,534; perl: 264
file content (385 lines) | stat: -rw-r--r-- 11,420 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#----------------------------------------------------------------------------
# Name:         ColourSelect.py
# Purpose:      Colour Box Selection Control
#
# Author:       Lorne White, Lorne.White@telusplanet.net
#
# Created:      Feb 25, 2001
# Licence:      wxWindows license
# Tags:         phoenix-port, unittest, documented
#----------------------------------------------------------------------------

# creates a colour wxButton with selectable color
# button click provides a colour selection box
# button colour will change to new colour
# GetColour method to get the selected colour

# Updates:
# call back to function if changes made

# Cliff Wells, logiplexsoftware@earthlink.net:
# - Made ColourSelect into "is a button" rather than "has a button"
# - Added label parameter and logic to adjust the label colour according to the background
#   colour
# - Added id argument
# - Rearranged arguments to more closely follow wx conventions
# - Simplified some of the code

# Cliff Wells, 2002/02/07
# - Added ColourSelect Event

# 12/01/2003 - Jeff Grimmett (grimmtooth@softhome.net)
#
# o Updated for 2.5 compatibility.
#

"""
Provides a :class:`wx.ColourSelect` button that, when clicked, will display a
colour selection dialog.


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

This module provides a :class:`wx.ColourSelect` button that, when clicked, will display a
colour selection dialog. The selected colour is displayed on the button itself.


Usage
=====

Sample usage::

    import wx
    import wx.lib.colourselect as csel

    class MyFrame(wx.Frame):

        def __init__(self, parent, title):

            wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(400, 300))
            self.panel = wx.Panel(self)

            colour_button = csel.ColourSelect(self.panel, -1, "Choose...", wx.WHITE)
            colour_button.Bind(csel.EVT_COLOURSELECT, self.OnChooseBackground)

        def OnChooseBackground(self, event):

            col1 = event.GetValue()
            self.panel.SetBackgroundColour(col1)
            event.Skip()

    app = wx.App()
    frame = MyFrame(None, 'Select a colour')
    frame.Show()
    app.MainLoop()

"""

#----------------------------------------------------------------------------

import wx
import wx.lib.buttons
import functools

#----------------------------------------------------------------------------

wxEVT_COMMAND_COLOURSELECT = wx.NewEventType()

class ColourSelectEvent(wx.PyCommandEvent):
    """
    :class:`wx.ColourSelectEvent` is a special subclassing of :class:`wx.CommandEvent`
    and it provides for a custom event sent every time the user chooses a colour.
    """

    def __init__(self, id, value):
        """
        Default class constructor.

        :param integer `id`: the event identifier;
        :param wx.Colour `value`: the colour currently selected.
        """

        wx.PyCommandEvent.__init__(self, id = id)
        self.SetEventType(wxEVT_COMMAND_COLOURSELECT)
        self.value = value


    def GetValue(self):
        """
        Returns the currently selected colour.

        :rtype: :class:`wx.Colour`
        """

        return self.value


EVT_COLOURSELECT = wx.PyEventBinder(wxEVT_COMMAND_COLOURSELECT, 1)


#----------------------------------------------------------------------------

class CustomColourData(object):
    """
    A simple container for tracking custom colours to be shown in the colour
    dialog, and which facilitates reuse of this collection across multiple
    instances or multiple invocations of the :class:`ColourSelect` button.
    """
    COUNT = 16

    def __init__(self):
        self._customColours = [None] * self.COUNT


    @property
    def Colours(self):
        return self._customColours

    @Colours.setter
    def Colours(self, value):
        # slice it into the current list to keep the same list instance
        if isinstance(value, CustomColourData):
            value = value.Colours
        self._customColours[:] = value


#----------------------------------------------------------------------------


class ColourSelect(wx.lib.buttons.GenBitmapButton):
    """
    A subclass of :class:`wx.BitmapButton` that, when clicked, will
    display a colour selection dialog.
    """

    def __init__(self, parent, id=wx.ID_ANY, label="", colour=wx.BLACK,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 callback=None, style=0):
        """
        Default class constructor.

        :param wx.Window `parent`: parent window. Must not be ``None``;
        :param integer `id`: window identifier. A value of -1 indicates a default value;
        :param string `label`: the button text label;
        :param wx.Colour: a valid :class:`wx.Colour` instance, which will be the default initial
         colour for this button;
        :type `colour`: :class:`wx.Colour` or tuple
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :type `pos`: tuple or :class:`wx.Point`
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :type `size`: tuple or :class:`wx.Size`
        :param PyObject `callback`: a callable method/function that will be called every time
         the user chooses a new colour;
        :param integer `style`: the button style.
        """

        size = wx.Size(*size)
        if label:
            mdc = wx.MemoryDC(wx.Bitmap(1,1))
            w, h = mdc.GetTextExtent(label)
            w += 8
            h += 8
        else:
            w, h = 22, 22

        size.width = size.width if size.width != -1 else w
        size.height = size.height if size.height != -1 else h
        super(ColourSelect, self).__init__(parent, id, wx.Bitmap(w,h),
                                 pos=pos, size=size, style=style,
                                 name='ColourSelect')

        if type(colour) == type( () ):
            colour = wx.Colour(*colour)

        self.colour = colour
        self.SetLabel(label)
        self.callback = callback
        bmp = self.MakeBitmap()
        self.SetBitmap(bmp)
        self.customColours = None
        parent.Bind(wx.EVT_BUTTON, self.OnClick, self)


    def GetColour(self):
        """
        Returns the current colour set for the :class:`ColourSelect`.

        :rtype: :class:`wx.Colour`
        """

        return self.colour


    def GetValue(self):
        """
        Returns the current colour set for the :class:`ColourSelect`.
        Same as :meth:`~ColourSelect.GetColour`.

        :rtype: :class:`wx.Colour`
        """

        return self.colour


    def SetValue(self, colour):
        """
        Sets the current colour for :class:`ColourSelect`.  Same as
        :meth:`~ColourSelect.SetColour`.

        :param `colour`: the new colour for :class:`ColourSelect`.
        :type `colour`: tuple or string or :class:`wx.Colour`
        """

        self.SetColour(colour)


    def SetColour(self, colour):
        """
        Sets the current colour for :class:`ColourSelect`.

        :param `colour`: the new colour for :class:`ColourSelect`.
        :type `colour`: tuple or string or :class:`wx.Colour`
        """

        self.colour = wx.Colour(colour)  # use the typmap or copy an existing colour object
        bmp = self.MakeBitmap()
        self.SetBitmap(bmp)


    def SetLabel(self, label):
        """
        Sets the new text label for :class:`wx.ColourSelect`.

        :param string `label`: the new text label for :class:`ColourSelect`.
        """

        self.label = label


    def GetLabel(self):
        """
        Returns the current text label for the :class:`ColourSelect`.

        :rtype: string
        """

        return self.label


    def GetCustomColours(self):
        """
        Returns the current set of custom colour values to be shown in the
        colour dialog, if supported.

        :rtype: :class:`CustomColourData`
        """
        return self.customColours


    def SetCustomColours(self, colours):
        """
        Sets the list of custom colour values to be shown in colour dialog, if
        supported.

        :param `colours`: An instance of :class:`CustomColourData` or a 16
        element list of ``None`` or :class:`wx.Colour` values.
        """
        if isinstance(colours, CustomColourData):
            colours = colours.Colours
        if self.customColours is None:
            self.customColours = CustomColourData()
        self.customColours.Colours = colours


    Colour = property(GetColour, SetColour)
    Value = property(GetValue, SetValue)
    Label = property(GetLabel, SetLabel)
    CustomColours = property(GetCustomColours, SetCustomColours)


    def MakeBitmap(self):
        """ Creates a bitmap representation of the current selected colour. """

        bdr = 8
        width, height = self.GetSize()

        # yes, this is weird, but it appears to work around a bug in wxMac
        if "wxMac" in wx.PlatformInfo and width == height:
            height -= 1

        bmp = wx.Bitmap(width-bdr, height-bdr)
        dc = wx.MemoryDC()
        dc.SelectObject(bmp)
        dc.SetFont(self.GetFont())
        label = self.GetLabel()
        # Just make a little colored bitmap
        dc.SetBackground(wx.Brush(self.colour))
        dc.Clear()

        if label:
            # Add a label to it
            avg = functools.reduce(lambda a, b: a + b, self.colour.Get()) / 3
            fcolour = avg > 128 and wx.BLACK or wx.WHITE
            dc.SetTextForeground(fcolour)
            dc.DrawLabel(label, (0,0, width-bdr, height-bdr),
                         wx.ALIGN_CENTER)

        dc.SelectObject(wx.NullBitmap)
        return bmp


    def SetBitmap(self, bmp):
        """
        Sets the bitmap representation of the current selected colour to the button.

        :param wx.Bitmap `bmp`: the new bitmap.
        """

        self.SetBitmapLabel(bmp)
        self.Refresh()


    def OnChange(self):
        """ Fires the ``EVT_COLOURSELECT`` event, as the user has changed the current colour. """

        evt = ColourSelectEvent(self.GetId(), self.GetValue())
        evt.SetEventObject(self)
        wx.PostEvent(self, evt)
        if self.callback is not None:
            self.callback()


    def OnClick(self, event):
        """
        Handles the ``wx.EVT_BUTTON`` event for :class:`ColourSelect`.

        :param `event`: a :class:`wx.CommandEvent` event to be processed.
        """

        data = wx.ColourData()
        data.SetChooseFull(True)
        data.SetColour(self.colour)
        if self.customColours:
            for idx, clr in enumerate(self.customColours.Colours):
                if clr is not None:
                    data.SetCustomColour(idx, clr)

        dlg = wx.ColourDialog(wx.GetTopLevelParent(self), data)
        changed = dlg.ShowModal() == wx.ID_OK

        if changed:
            data = dlg.GetColourData()
            self.SetColour(data.GetColour())
            if self.customColours:
                self.customColours.Colours = \
                    [data.GetCustomColour(idx) for idx in range(0, 16)]

        dlg.Destroy()

        # moved after dlg.Destroy, since who knows what the callback will do...
        if changed:
            self.OnChange()