Source

wxPython / samples / doodle / superdoodle.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# superdoodle.py
"""
This module implements the SuperDoodle demo application.  It takes the
DoodleWindow previously presented and reuses it in a much more
intelligent Frame.  This one has a menu and a statusbar, is able to
save and reload doodles, clear the workspace, and has a simple control
panel for setting color and line thickness in addition to the popup
menu that DoodleWindow provides.  There is also a nice About dialog
implmented using an wx.html.HtmlWindow.
"""

import sys, os, cPickle

import wx    
import wx.html
from wx.lib import buttons # for generic button classes
from doodle import DoodleWindow

from wx.lib.mixins.inspection import InspectionMixin
from wx.lib.softwareupdate import SoftwareUpdate

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

# There are standard IDs for the menu items we need in this app, or we
# could have used wx.NewId() to autogenerate some new unique ID values
# instead.

idNEW    = wx.ID_NEW
idOPEN   = wx.ID_OPEN
idSAVE   = wx.ID_SAVE
idSAVEAS = wx.ID_SAVEAS
idCLEAR  = wx.ID_CLEAR
idEXIT   = wx.ID_EXIT
idABOUT  = wx.ID_ABOUT



class DoodleFrame(wx.Frame):
    """
    A DoodleFrame contains a DoodleWindow and a ControlPanel and manages
    their layout with a wx.BoxSizer.  A menu and associated event handlers
    provides for saving a doodle to a file, etc.
    """
    title = "Do a doodle"
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, -1, self.title, size=(800,600),
                         style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE)
        self.SetIcon(wx.Icon('mondrian.ico'))
        self.CreateStatusBar()
        self.MakeMenu()
        self.filename = None

        self.doodle = DoodleWindow(self, -1)
        cPanel = ControlPanel(self, -1, self.doodle)

        # Create a sizer to layout the two windows side-by-side.
        # Both will grow vertically, the doodle window will grow
        # horizontally as well.
        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(cPanel, 0, wx.EXPAND)
        box.Add(self.doodle, 1, wx.EXPAND)

        # Tell the frame that it should layout itself in response to
        # size events using this sizer.
        self.SetSizer(box)


    def SaveFile(self):
        if self.filename:
            data = self.doodle.GetLinesData()
            f = open(self.filename, 'w')
            cPickle.dump(data, f)
            f.close()


    def ReadFile(self):
        if self.filename:
            try:
                f = open(self.filename, 'r')
                data = cPickle.load(f)
                f.close()
                self.doodle.SetLinesData(data)
            except cPickle.UnpicklingError:
                wx.MessageBox("%s is not a doodle file." % self.filename,
                             "oops!", style=wx.OK|wx.ICON_EXCLAMATION)


    def MakeMenu(self):
        # create the file menu
        menu1 = wx.Menu()

        # Using the "\tKeyName" syntax automatically creates a
        # wx.AcceleratorTable for this frame and binds the keys to
        # the menu items.
        menu1.Append(idOPEN, "&Open\tCtrl-O", "Open a doodle file")
        menu1.Append(idSAVE, "&Save\tCtrl-S", "Save the doodle")
        menu1.Append(idSAVEAS, "Save &As", "Save the doodle in a new file")
        menu1.AppendSeparator()
        menu1.Append(idCLEAR, "&Clear", "Clear the current doodle")
        menu1.AppendSeparator()
        menu1.Append(idEXIT, "E&xit", "Terminate the application")

        # and the help menu
        menu2 = wx.Menu()
        if hasattr(sys, 'frozen'):
            item = menu2.Append(-1, "Check for Update...")
            self.Bind(wx.EVT_MENU, self.OnMenuCheckForUpdate, item)
            
        menu2.Append(idABOUT, "&About\tCtrl-H", "Display the gratuitous 'about this app' thingamajig")

        # and add them to a menubar
        menuBar = wx.MenuBar()
        menuBar.Append(menu1, "&File")
        menuBar.Append(menu2, "&Help")
        self.SetMenuBar(menuBar)

        self.Bind(wx.EVT_MENU,   self.OnMenuOpen, id=idOPEN)
        self.Bind(wx.EVT_MENU,   self.OnMenuSave, id=idSAVE)
        self.Bind(wx.EVT_MENU, self.OnMenuSaveAs, id=idSAVEAS)
        self.Bind(wx.EVT_MENU,  self.OnMenuClear, id=idCLEAR)
        self.Bind(wx.EVT_MENU,   self.OnMenuExit, id=idEXIT)
        self.Bind(wx.EVT_MENU,  self.OnMenuAbout, id=idABOUT)



    wildcard = "Doodle files (*.ddl)|*.ddl|All files (*.*)|*.*"

    def OnMenuOpen(self, event):
        dlg = wx.FileDialog(self, "Open doodle file...", os.getcwd(),
                           style=wx.OPEN, wildcard = self.wildcard)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetPath()
            self.ReadFile()
            self.SetTitle(self.title + ' -- ' + self.filename)
        dlg.Destroy()


    def OnMenuSave(self, event):
        if not self.filename:
            self.OnMenuSaveAs(event)
        else:
            self.SaveFile()


    def OnMenuSaveAs(self, event):
        dlg = wx.FileDialog(self, "Save doodle as...", os.getcwd(),
                           style=wx.SAVE | wx.OVERWRITE_PROMPT,
                           wildcard = self.wildcard)
        if dlg.ShowModal() == wx.ID_OK:
            filename = dlg.GetPath()
            if not os.path.splitext(filename)[1]:
                filename = filename + '.ddl'
            self.filename = filename
            self.SaveFile()
            self.SetTitle(self.title + ' -- ' + self.filename)
        dlg.Destroy()


    def OnMenuClear(self, event):
        self.doodle.SetLinesData([])
        self.SetTitle(self.title)


    def OnMenuExit(self, event):
        self.Close()


    def OnMenuAbout(self, event):
        dlg = DoodleAbout(self)
        dlg.ShowModal()
        dlg.Destroy()

    def OnMenuCheckForUpdate(self, event):
        wx.GetApp().CheckForUpdate(parentWindow=self)

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


class ControlPanel(wx.Panel):
    """
    This class implements a very simple control panel for the DoodleWindow.
    It creates buttons for each of the colours and thickneses supported by
    the DoodleWindow, and event handlers to set the selected values.  There is
    also a little window that shows an example doodleLine in the selected
    values.  Nested sizers are used for layout.
    """

    BMP_SIZE = 16
    BMP_BORDER = 3

    def __init__(self, parent, ID, doodle):
        wx.Panel.__init__(self, parent, ID, style=wx.RAISED_BORDER)

        numCols = 4
        spacing = 4

        btnSize = wx.Size(self.BMP_SIZE + 2*self.BMP_BORDER,
                          self.BMP_SIZE + 2*self.BMP_BORDER)

        # Make a grid of buttons for each colour.  Attach each button
        # event to self.OnSetColour.  The button ID is the same as the
        # key in the colour dictionary.
        self.clrBtns = {}
        colours = doodle.menuColours
        keys = colours.keys()
        keys.sort()
        cGrid = wx.GridSizer(cols=numCols, hgap=2, vgap=2)
        for k in keys:
            bmp = self.MakeBitmap(colours[k])
            b = buttons.GenBitmapToggleButton(self, k, bmp, size=btnSize )
            b.SetBezelWidth(1)
            b.SetUseFocusIndicator(False)
            self.Bind(wx.EVT_BUTTON, self.OnSetColour, b)
            cGrid.Add(b, 0)
            self.clrBtns[colours[k]] = b
        self.clrBtns[colours[keys[0]]].SetToggle(True)


        # Make a grid of buttons for the thicknesses.  Attach each button
        # event to self.OnSetThickness.  The button ID is the same as the
        # thickness value.
        self.thknsBtns = {}
        tGrid = wx.GridSizer(cols=numCols, hgap=2, vgap=2)
        for x in range(1, doodle.maxThickness+1):
            b = buttons.GenToggleButton(self, x, str(x), size=btnSize)
            b.SetBezelWidth(1)
            b.SetUseFocusIndicator(False)
            self.Bind(wx.EVT_BUTTON, self.OnSetThickness, b)
            tGrid.Add(b, 0)
            self.thknsBtns[x] = b
        self.thknsBtns[1].SetToggle(True)

        # Make a colour indicator window, it is registerd as a listener
        # with the doodle window so it will be notified when the settings
        # change
        ci = ColourIndicator(self)
        doodle.AddListener(ci)
        doodle.Notify()
        self.doodle = doodle

        # Make a box sizer and put the two grids and the indicator
        # window in it.
        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(cGrid, 0, wx.ALL, spacing)
        box.Add(tGrid, 0, wx.ALL, spacing)
        box.Add(ci, 0, wx.EXPAND|wx.ALL, spacing)
        self.SetSizer(box)
        self.SetAutoLayout(True)

        # Resize this window so it is just large enough for the
        # minimum requirements of the sizer.
        box.Fit(self)



    def MakeBitmap(self, colour):
        """
        We can create a bitmap of whatever we want by simply selecting
        it into a wx.MemoryDC and drawing on it.  In this case we just set
        a background brush and clear the dc.
        """
        bmp = wx.EmptyBitmap(self.BMP_SIZE, self.BMP_SIZE)
        dc = wx.MemoryDC()
        dc.SelectObject(bmp)
        dc.SetBackground(wx.Brush(colour))
        dc.Clear()
        dc.SelectObject(wx.NullBitmap)
        return bmp


    def OnSetColour(self, event):
        """
        Use the event ID to get the colour, set that colour in the doodle.
        """
        colour = self.doodle.menuColours[event.GetId()]
        if colour != self.doodle.colour:
            # untoggle the old colour button
            self.clrBtns[self.doodle.colour].SetToggle(False)
        # set the new colour
        self.doodle.SetColour(colour)


    def OnSetThickness(self, event):
        """
        Use the event ID to set the thickness in the doodle.
        """
        thickness = event.GetId()
        if thickness != self.doodle.thickness:
            # untoggle the old thickness button
            self.thknsBtns[self.doodle.thickness].SetToggle(False)
        # set the new colour
        self.doodle.SetThickness(thickness)



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

class ColourIndicator(wx.Window):
    """
    An instance of this class is used on the ControlPanel to show
    a sample of what the current doodle line will look like.
    """
    def __init__(self, parent):
        wx.Window.__init__(self, parent, -1, style=wx.SUNKEN_BORDER)
        self.SetBackgroundColour(wx.WHITE)
        self.SetMinSize( (45, 45) )
        self.colour = self.thickness = None
        self.Bind(wx.EVT_PAINT, self.OnPaint)


    def Update(self, colour, thickness):
        """
        The doodle window calls this method any time the colour
        or line thickness changes.
        """
        self.colour = colour
        self.thickness = thickness
        self.Refresh()  # generate a paint event


    def OnPaint(self, event):
        """
        This method is called when all or part of the window needs to be
        redrawn.
        """
        dc = wx.PaintDC(self)
        if self.colour:
            sz = self.GetClientSize()
            pen = wx.Pen(self.colour, self.thickness)
            dc.BeginDrawing()
            dc.SetPen(pen)
            dc.DrawLine(10, sz.height/2, sz.width-10, sz.height/2)
            dc.EndDrawing()


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

class DoodleAbout(wx.Dialog):
    """ An about box that uses an HTML window """

    text = '''
<html>
<body bgcolor="#ACAA60">
<center><table bgcolor="#455481" width="100%%" cellspacing="0"
cellpadding="0" border="1">
<tr>
    <td align="center"><h1>SuperDoodle %s</h1></td>
</tr>
</table>
</center>
<p><b>SuperDoodle</b> is a demonstration program for <b>wxPython</b> that
will hopefully teach you a thing or two.  Just follow these simple
instructions: </p>
<p>
<ol>
  <li><b>Read</b> the Source...
  <li><b>Learn</b>...
  <li><b>Do!</b>
</ol>

<p><b>SuperDoodle</b> and <b>wxPython</b> are brought to you by
<b>Robin Dunn</b> and <b>Total Control Software</b>, Copyright
&copy; 1997-2011.</p>
</body>
</html>
''' 

    def __init__(self, parent):
        wx.Dialog.__init__(self, parent, -1, 'About SuperDoodle',
                          size=(420, 380) )

        html = wx.html.HtmlWindow(self, -1)
        import version
        html.SetPage(self.text % version.VERSION)
        button = wx.Button(self, wx.ID_OK, "Okay")

        # constraints for the html window
        lc = wx.LayoutConstraints()
        lc.top.SameAs(self, wx.Top, 5)
        lc.left.SameAs(self, wx.Left, 5)
        lc.bottom.SameAs(button, wx.Top, 5)
        lc.right.SameAs(self, wx.Right, 5)
        html.SetConstraints(lc)

        # constraints for the button
        lc = wx.LayoutConstraints()
        lc.bottom.SameAs(self, wx.Bottom, 5)
        lc.centreX.SameAs(self, wx.CentreX)
        lc.width.AsIs()
        lc.height.AsIs()
        button.SetConstraints(lc)

        self.SetAutoLayout(True)
        self.Layout()
        self.CentreOnParent(wx.BOTH)


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

class DoodleApp(wx.App, InspectionMixin, SoftwareUpdate):
    def OnInit(self):
        BASEURL='http://wxPython.org/software-update-test/'
        self.InitUpdates(BASEURL, 
                         BASEURL + 'ChangeLog.txt',
                         icon=wx.Icon('mondrian.ico'))
        self.Init() # for InspectionMixin
        
        frame = DoodleFrame(None)
        frame.Show(True)
        self.SetTopWindow(frame)
        self.SetAppDisplayName('SuperDoodle')
        return True

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

if __name__ == '__main__':
    app = DoodleApp(redirect=False)
    app.MainLoop()