import os, string
import wx
import wx.lib.editor as editor

MNU_ABOUT=101
MNU_EXIT=110
MNU_OPEN=102
MNU_SAVEAS = 103
MNU_SAVE = 104
MNU_NEW = 105
MNU_CLOSE = 106
MNU_SETTAB = 107



def chomp(line):
    line = string.split(line, '\n')[0]
    return string.split(line, '\r')[0]

class document(wx.Panel):
    def __init__(self, parent,id):
        wx.Panel.__init__(self, parent, id)
        self.ed = editor.Editor(self, -1, style=wx.SUNKEN_BORDER)
        #self.ed.SetSize(self.GetClientSize())
        self.Bind(wx.EVT_SIZE, self.OnSize)



    def OnSize(self, event):
        self.ed.SetSize(self.GetClientSize())



#    def OnSetTab(self):
#        dlg = wx.TextEntryDialog(
#                frame, 'Number of spaces per tab:',
#                'Set tab value', 'spacespertab')
#    
#        dlg.SetValue(str(self.ed.SpacesPerTab))
#        
#        if dlg.ShowModal() == wx.ID_OK:
#            self.ed.SpacesPerTab = int(dlg.GetValue())
#    
#        dlg.Destroy()
    #def OnKeyDown(self,event):
    #    if event.GetKeyCode() == wx.WXK_TAB:
    #        self.ed.WriteText(tabvalue)
    #    else:
    #        print "no processor for %s" % str(event.GetKeyCode())
        
        
        
class myNotebook(wx.Notebook):
    def __init__(self, parent, ID, 
                pos = wx.DefaultPosition,
                size = wx.DefaultSize, 
                style = 0, name = "notebook"):
        wx.Notebook.__init__(self, parent, ID, pos, size, style, name)
        self.parent = parent
        self.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)

    
    def OnRightClick(self,e):
        popupmenu = wx.Menu()
        popupmenu.Append(MNU_SAVE,"&Save"," Save file")
        popupmenu.Append(MNU_CLOSE,"&Close"," Close file")
        x,y = e.GetPosition()
        index = self.HitTest(wx.Point(x,y))[0]
        if index != -1:
            self.SetSelection(index)
            self.PopupMenu(popupmenu, (x,y))
            
    def OnDoubleClick(self, e):
        x,y = e.GetPosition()
        index = self.HitTest(wx.Point(x,y))[0]
        if index == -1:
            self.parent.OnNew(e)
        else:
            self.SetSelection(index)
            self.parent.OnClose(e)



class MainWindow(wx.Frame):
    def __init__(self,parent,id,title):
        wx.Frame.__init__(self,parent,wx.ID_ANY, title, size = (800,600),
                                        style=wx.DEFAULT_FRAME_STYLE|
                                        wx.NO_FULL_REPAINT_ON_RESIZE)
        self.control = myNotebook(self, -1)
        self.numdocs = 0
        self.OnNew(None)
        self.buildMenu()
        self.Show(True)



    def buildMenu(self):
        # Setting up the menu.
        filemenu = wx.Menu()
        filemenu.Append(MNU_NEW,"&New"," Create a new file")
        filemenu.Append(MNU_OPEN,"&Open"," Open a file")
        filemenu.Append(MNU_SAVE,"&Save"," Save file")
        filemenu.Append(MNU_SAVEAS,"Save &as..."," Save as ...")
        filemenu.Append(MNU_CLOSE,"&Close"," Close file")
        filemenu.AppendSeparator()
        filemenu.Append(MNU_EXIT,"E&xit"," Terminate the program")
        
        editmenu = wx.Menu()
        editmenu.Append(MNU_SETTAB, "Set tab value", " Set the size of a tab")

        helpmenu = wx.Menu()
        helpmenu.Append(MNU_ABOUT, "&About"," Information about this program")

        menuBar = wx.MenuBar()
        menuBar.Append(filemenu,"&File")
        menuBar.Append(editmenu,"&Edit")
        menuBar.Append(helpmenu,"&Help")

        self.SetMenuBar(menuBar)

        wx.EVT_MENU(self, MNU_NEW, self.OnNew)
        wx.EVT_MENU(self, MNU_OPEN, self.OnOpen)
        wx.EVT_MENU(self, MNU_SAVE, self.OnSave)
        wx.EVT_MENU(self, MNU_SAVEAS, self.OnSaveAs)
        wx.EVT_MENU(self, MNU_CLOSE, self.OnClose)
        wx.EVT_MENU(self, MNU_SETTAB, self.OnSetTab)
        wx.EVT_MENU(self, MNU_ABOUT, self.OnAbout)
        wx.EVT_MENU(self, MNU_EXIT, self.OnExit)



    def OnNew(self,e):
        """ Create a new file"""
        self.numdocs += 1
        newpanel = document(self.control, wx.ID_ANY)
        self.control.AddPage(newpanel, "Document %s" % self.numdocs)



    def OnOpen(self,e):
        """ Open a file"""
        dlg = wx.FileDialog(self, "Open file", os.getcwd(), "", "*.*", wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            newpanel = document(self.control, wx.ID_ANY)
            newpanel.filename = dlg.GetFilename()
            newpanel.dirname = dlg.GetDirectory()
            f = open(os.path.join(newpanel.dirname,newpanel.filename),'r')
            filetext = [chomp(line) for line in f.readlines()]
            if filetext == []:
                #newpanel.ed.SetText("")
                pass
            else:
                newpanel.ed.SetText(filetext)
            self.control.AddPage(newpanel, newpanel.filename)            
            f.close()
        dlg.Destroy()



    def OnSave(self,e):
        """ Save a file"""
        page = self.control.GetPage(self.control.GetSelection())
        if hasattr(page, "dirname") and hasattr(page, "filename"):
            f=open(os.path.join(page.dirname,page.filename),'w')
            f.write(string.join(page.ed.GetText(), ""))
            f.close()
        else:
            self.OnSaveAs(e)
        


    def OnSaveAs(self,e):
        """ Save a file"""
        dlg = wx.FileDialog(frame, "Save file as ...", os.getcwd() , "", "*.*", wx.SAVE)
        if dlg.ShowModal() == wx.ID_OK:
            page = self.control.GetPage(self.control.GetSelection())
            page.filename=dlg.GetFilename()
            page.dirname=dlg.GetDirectory()
            f=open(os.path.join(page.dirname,page.filename),'w')
            f.write(string.join(page.ed.GetText()))
            f.close()
            self.control.SetPageText(self.control.GetSelection(), page.filename)
        dlg.Destroy()
        page.Refresh()



    def OnClose(self,e):
        """ Close a file"""
        self.control.DeletePage(self.control.GetSelection())



    def OnSetTab(self,e):
        dlg = wx.TextEntryDialog(self, 'Number of spaces per tab:', 'Set tab value')

        dlg.SetValue(str(self.control.GetPage(self.control.GetSelection()).ed.SpacesPerTab))

        if dlg.ShowModal() == wx.ID_OK:
            self.control.GetPage(self.control.GetSelection()).ed.SpacesPerTab = int(dlg.GetValue())
        dlg.Destroy()



    def OnAbout(self,e):
        d= wx.MessageDialog( self, " A sample editor \n"
                            " in wxPython","About Sample Editor", wx.OK)    # Create a message dialog box
        d.ShowModal()   # Shows it
        d.Destroy()     # finally destroy it when finished.



    def OnExit(self,e):
        self.Close(True)  # Close the frame.



if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MainWindow(None, wx.ID_ANY, "Sample editor")
    app.MainLoop()