File: resizewidget.py

package info (click to toggle)
wxpython4.0 4.2.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 232,540 kB
  • sloc: cpp: 958,937; python: 233,059; ansic: 150,441; makefile: 51,662; sh: 8,687; perl: 1,563; javascript: 584; php: 326; xml: 200
file content (357 lines) | stat: -rw-r--r-- 11,268 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
#----------------------------------------------------------------------
# Name:        wx.lib.resizewidget
# Purpose:     Adds a resize handle to any widget, with support for
#              notifying parents when layout needs done.
#
# Author:      Robin Dunn
#
# Created:     12-June-2008
# Copyright:   (c) 2008-2020 by Total Control Software
# Licence:     wxWindows license
# Tags:        phoenix-port, unittest, documented, py3-port
#----------------------------------------------------------------------

"""
Reparents a given widget into a specialized panel that provides a resize
handle for the widget. When the user drags the resize handle the widget is
resized accordingly, and an event is sent to notify parents that they should
recalculate their layout.
"""

import wx
import wx.lib.newevent

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

# dimensions used for the handle
RW_THICKNESS = 4
RW_LENGTH = 12

# default colors for the handle
RW_PEN   = 'black'
RW_FILL  = '#A0A0A0'
RW_FILL2 = '#E0E0E0'

# An event and event binder that will notify the containers that they should
# redo the layout in whatever way makes sense for their particular content.
_RWLayoutNeededEvent, EVT_RW_LAYOUT_NEEDED = wx.lib.newevent.NewCommandEvent()


# TODO: Add a style flag that indicates that the ResizeWidget should
# try to adjust the layout itself by looking up the sizer and
# containment hierarchy.  Maybe also a style that says that it is okay
# to adjust the size of top-level windows too.

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

class ResizeWidget(wx.Panel):
    """
    Reparents a given widget into a specialized panel that provides a resize
    handle for the widget.

    """
    def __init__(self, *args, **kw):
        """
        Default class constructor.

        :param `args`: arguments will be passed on to the wx.Panel
        :param `kw`: key words will be passed on to the wx.Panel

        """
        wx.Panel.__init__(self, *args, **kw)
        self._init()

        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MOTION,  self.OnMouseMove)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_PAINT, self.OnPaint)


    def _init(self):
        self._managedChild = None
        self._bestSize = wx.Size(100, 25)
        self.InvalidateBestSize()
        self._resizeCursor = False
        self._dragPos = None
        self._resizeEnabled = True
        self._reparenting = False

        self.SetDimensions()
        self.SetColors()

    def SetDimensions(self, thickness=RW_THICKNESS, length=RW_LENGTH):
        """
        Set the dimensions of handles.

        :param `thickness`: the thickness of the handles
        :param `length`: the length of the handles

        """
        self.RW_THICKNESS = thickness
        self.RW_LENGTH = length

    def SetColors(self, pen=RW_PEN, fill=RW_FILL, fill2=RW_FILL2):
        """
        Set the colors of handles.

        :param `pen`: the pen color
        :param `fill`: the fill color
        :param `fill2`: the secondary fill color

        """
        self.RW_PEN   = pen
        self.RW_FILL  = fill
        self.RW_FILL2 = fill2

    def SetManagedChild(self, child):
        """
        Set a managed child.

        :param `child`: child to manage

        """
        self._reparenting = True
        child.Reparent(self)  # This calls AddChild, so do the rest of the init there
        self._reparenting = False
        self.AdjustToChild()

    def GetManagedChild(self):
        """Get the managed child."""
        return self._managedChild

    ManagedChild = property(GetManagedChild, SetManagedChild)


    def AdjustToChild(self):
        """Adjust the size to the child."""
        self.AdjustToSize(self._managedChild.GetEffectiveMinSize())


    def AdjustToSize(self, size):
        """
        Adjust to given size.

        :param `size`: size to adjust to.

        """
        size = wx.Size(*size)
        self._bestSize = size + (self.RW_THICKNESS, self.RW_THICKNESS)
        self.InvalidateBestSize()
        self.SetSize(self._bestSize)


    def EnableResize(self, enable=True):
        """
        Enable resizing.

        :param boolean `enable`: enable or disable resizing.

        """
        self._resizeEnabled = enable
        self.Refresh(False)


    def IsResizeEnabled(self):
        """Is resize enabled?"""
        return self._resizeEnabled


    #=== Event handler methods ===
    def OnLeftDown(self, evt):
        """
        Handles the ``wx.EVT_LEFT_DOWN`` event for :class:`ResizeWidget`.

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

        """
        if self._hitTest(evt.GetPosition()) and self._resizeEnabled:
            self.CaptureMouse()
            self._dragPos = evt.GetPosition()


    def OnLeftUp(self, evt):
        """
        Handles the ``wx.EVT_LEFT_UP`` event for :class:`ResizeWidget`.

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

        """
        if self.HasCapture():
            self.ReleaseMouse()
        self._dragPos = None


    def OnMouseMove(self, evt):
        """
        Handles the ``wx.EVT_MOTION`` event for :class:`ResizeWidget`.

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

        """
        # set or reset the drag cursor
        pos = evt.GetPosition()
        if self._hitTest(pos) and self._resizeEnabled:
            if not self._resizeCursor:
                self.SetCursor(wx.Cursor(wx.CURSOR_SIZENWSE))
                self._resizeCursor = True
        else:
            if self._resizeCursor:
                self.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
                self._resizeCursor = False

        # determine if a new size is needed
        if evt.Dragging() and self._dragPos is not None:
            delta = self._dragPos - pos
            newSize = self.GetSize() - delta.Get()
            self._adjustNewSize(newSize)
            if newSize != self.GetSize():
                self.SetSize(newSize)
                self._dragPos = pos
                self._bestSize = newSize
                self.InvalidateBestSize()
                self._sendEvent()


    def _sendEvent(self):
        event = _RWLayoutNeededEvent(self.GetId())
        event.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(event)


    def _adjustNewSize(self, newSize):
        if newSize.width < self.RW_LENGTH:
            newSize.width = self.RW_LENGTH
        if newSize.height < self.RW_LENGTH:
            newSize.height = self.RW_LENGTH

        if self._managedChild:
            minsize = self._managedChild.GetMinSize()
            if minsize.width != -1 and newSize.width - self.RW_THICKNESS < minsize.width:
                newSize.width = minsize.width + self.RW_THICKNESS
            if minsize.height != -1 and newSize.height - self.RW_THICKNESS < minsize.height:
                newSize.height = minsize.height + self.RW_THICKNESS
            maxsize = self._managedChild.GetMaxSize()
            if maxsize.width != -1 and newSize.width - self.RW_THICKNESS > maxsize.width:
                newSize.width = maxsize.width + self.RW_THICKNESS
            if maxsize.height != -1 and newSize.height - self.RW_THICKNESS > maxsize.height:
                newSize.height = maxsize.height + self.RW_THICKNESS


    def OnMouseLeave(self, evt):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for :class:`ResizeWidget`.

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

        """
        if self._resizeCursor:
            self.SetCursor(wx.Cursor(wx.CURSOR_ARROW))
            self._resizeCursor = False


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

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

        """
        if not self._managedChild:
            return
        sz = self.GetSize()
        cr = wx.Rect((0, 0), sz - (self.RW_THICKNESS, self.RW_THICKNESS))
        self._managedChild.SetRect(cr)
        r1 = wx.Rect(0, cr.height, sz.width, self.RW_THICKNESS)
        r2 = wx.Rect(cr.width, 0, self.RW_THICKNESS, sz.height)
        self.RefreshRect(r1)
        self.RefreshRect(r2)


    def OnPaint(self, evt):
        """
        Handles the ``wx.EVT_PAINT`` event for :class:`ResizeWidget`.

        :param `evt`: a :class:`PaintEvent` event to be processed.

        """
        # draw the resize handle
        dc = wx.PaintDC(self)
        w, h = self.GetSize()
        points = [ (w - 1,                 h - self.RW_LENGTH),
                   (w - self.RW_THICKNESS, h - self.RW_LENGTH),
                   (w - self.RW_THICKNESS, h - self.RW_THICKNESS),
                   (w - self.RW_LENGTH,    h - self.RW_THICKNESS),
                   (w - self.RW_LENGTH,    h - 1),
                   (w - 1,                 h - 1),
                   (w - 1,                 h - self.RW_LENGTH),
                   ]
        dc.SetPen(wx.Pen(self.RW_PEN, 1))
        if self._resizeEnabled:
            fill = self.RW_FILL
        else:
            fill = self.RW_FILL2
        dc.SetBrush(wx.Brush(fill))
        dc.DrawPolygon(points)


    def _hitTest(self, pos):
        # is the position in the area to be used for the resize handle?
        w, h = self.GetSize()
        if ( w - self.RW_THICKNESS <= pos.x <= w
             and h - self.RW_LENGTH <= pos.y <= h ):
            return True
        if ( w - self.RW_LENGTH <= pos.x <= w
             and h - self.RW_THICKNESS <= pos.y <= h ):
            return True
        return False


    #=== Overridden virtuals from the base class ===
    def AddChild(self, child):
        """
        Add the child to manage.

        :param `child`: the child to manage.

        """
        assert self._managedChild is None, "Already managing a child widget, can only do one"
        self._managedChild = child
        wx.Panel.AddChild(self, child)

        # This little hack is needed because if this AddChild was called when
        # the widget was first created, then the OOR values will get reset
        # after this function call, and so the Python proxy object saved in
        # the window may be different than the child object we have now, so we
        # need to reset which proxy object we're using.  Look for it by ID.
        def _doAfterAddChild(self, id):
            if not self:
                return
            child = self.FindWindow(id)
            self._managedChild = child
            self.AdjustToChild()
            self._sendEvent()
        if self._reparenting:
            _doAfterAddChild(self, child.GetId())
        else:
            wx.CallAfter(_doAfterAddChild, self, child.GetId())

    def RemoveChild(self, child):
        """
        Remove the managed child.

        :param `child`: child to remove.

        """
        self._init()
        wx.Panel.RemoveChild(self, child)


    def DoGetBestSize(self):
        """Return the best size."""
        return self._bestSize


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