# -*- coding: iso-8859-1 -*-#
#!/usr/bin/env python2.4

import wx

# This has been set up to optionally use the wx.BufferedDC if
# USE_BUFFERED_DC is True, it will be used. Otherwise, it uses the raw
# wx.Memory DC , etc.

USE_BUFFERED_DC = 1

class BufferedWindow(wx.Window):

    """

    A Buffered window class.

    To use it, subclass it and define a Draw(DC) method that takes a DC
    to draw to. In that method, put the code needed to draw the picture
    you want. The window will automatically be double buffered, and the
    screen will be automatically updated when a Paint event is received.

    When the drawing needs to change, you app needs to call the
    UpdateDrawing() method. Since the drawing is stored in a bitmap, you
    can also save the drawing to file by calling the
    SaveToFile(self,file_name,file_type) method.

    """


    def __init__(self, parent, id,
                 pos = wx.DefaultPosition,
                 size = wx.DefaultSize,
                 style = wx.NO_FULL_REPAINT_ON_RESIZE):
        wx.Window.__init__(self, parent, id, pos, size, style)

        wx.EVT_PAINT(self, self.OnPaint)
        wx.EVT_SIZE(self, self.OnSize)


        # OnSize called to make sure the buffer is initialized.
        # This might result in OnSize getting called twice on some
        # platforms at initialization, but little harm done.
        self.OnSize(None)

    def Draw(self,dc):
        ## just here as a place holder.
        ## This method should be over-ridden when subclassed
        pass

    def OnPaint(self, event):
        # All that is needed here is to draw the buffer to screen
        if USE_BUFFERED_DC:
            dc = wx.BufferedPaintDC(self, self._Buffer)
        else:
            dc = wx.PaintDC(self)
            dc.DrawBitmap(self._Buffer,0,0)

    def OnSize(self,event):
        # The Buffer init is done here, to make sure the buffer is always
        # the same size as the Window
        Size  = self.GetClientSizeTuple()

        # Make new offscreen bitmap: this bitmap will always have the
        # current drawing in it, so it can be used to save the image to
        # a file, or whatever.
        self._Buffer = wx.EmptyBitmap(*Size)
        self.UpdateDrawing()

    def SaveToFile(self,FileName,FileType):
        ## This will save the contents of the buffer
        ## to the specified file. See the wxWindows docs for 
        ## wx.Bitmap::SaveFile for the details
        self._Buffer.SaveFile(FileName,FileType)

    def UpdateDrawing(self):
        """
        This would get called if the drawing needed to change, for whatever reason.

        The idea here is that the drawing is based on some data generated
        elsewhere in the system. If that data changes, the drawing needs to
        be updated.

        """

        if USE_BUFFERED_DC:
            dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer)
            self.Draw(dc)
        else:
            # update the buffer
            dc = wx.MemoryDC()
            dc.SelectObject(self._Buffer)
            self.Draw(dc)
            # update the screen
            wx.ClientDC(self).DrawBitmap(self._Buffer,0,0)

class DrawWindow(BufferedWindow):
    def __init__(self, parent, id = -1):
        ## Any data the Draw() function needs must be initialized before
        ## calling BufferedWindow.__init__, as it will call the Draw
        ## function.

        #self.font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        self.font = wx.FFont(9, wx.MODERN,\
                        wx.FONTFLAG_LIGHT|\
                        wx.FONTFLAG_ANTIALIASED,
                        "Courier")
        
        BufferedWindow.__init__(self, parent, id)
                
        
    def Draw(self, dc):
        """"""
        dc.SetBackground( wx.Brush("white") )
        dc.Clear() # make sure you clear the bitmap!
        
        penWidth = 2
        width = 200
        height = 50
        x = 50
        y = 50
        
        dc.SetPen(wx.Pen("black", 1))
        dc.DrawLines([(50,102), (260,102)])
        
        gc = wx.GraphicsContext.Create(dc)
                
        # Create a rounded rectangle+text in bitmap.
        # NOTE:
        bitmap = wx.EmptyBitmapRGBA(width+penWidth,
                                    height+penWidth,
                                    0, 0, 0, 0)
        mdc = wx.MemoryDC(bitmap)
        gc1 = wx.GraphicsContext.Create(mdc)
        gc1.PushState()
        gc1.SetPen(wx.Pen("black", penWidth))
        gc1.SetBrush(wx.Brush("light gray"))
        gc1.DrawRoundedRectangle(penWidth/2, penWidth/2, width, height, 5)
        gc1.SetFont(self.font, wx.RED)
        gc1.DrawText("BITMAP FONT: I should be in red color :-(!!!", 0, 0)
        gc1.PopState()
        mdc.SelectObject(wx.NullBitmap)
        del mdc
        
        # draw bitmap
        gc.DrawBitmap(bitmap, 150, y, width+penWidth/2, height+penWidth/2)
        gc.SetFont(self.font, wx.RED)
        gc.DrawText("SHAPE DRAW : I don't have any problem dude!!!", 0, 0)

class TestFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Double Buffered Test",
                         wx.DefaultPosition,
                         size=(500,500),
                         style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
        
        self.Window = DrawWindow(self)

    def OnQuit(self,event):
        self.Close(True)


class DemoApp(wx.App):
    def OnInit(self):
        #wx.InitAllImageHandlers() # called so a PNG can be saved      
        frame = TestFrame()
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

if __name__ == "__main__":
    print "about to initialize the app"
    app = DemoApp(0)
    app.MainLoop()
