# generated by wxGlade 0.3.2 on Mon Apr 12 02:14:33 2004

####(c)www.stani.be-------------------------------------------------------------

import _spe.info
INFO=_spe.info.copy()

INFO['description']=\
"""File browser as tab."""

__doc__=INFO['doc']%INFO

####wxGlade---------------------------------------------------------------------

CURRENT = "Current folder"

import wx
import _spe.help

class wxgPanel(wx.Panel):
    def __init__(self, *args, **kwds):
        # begin wxGlade: wxgPanel.__init__
        kwds["style"] = wx.TAB_TRAVERSAL
        wx.Panel.__init__(self, *args, **kwds)
        self.split = wx.SplitterWindow(self, -1)
        self.sideBar = wx.Panel(self.split, -1)
        self.folderNew = wx.BitmapButton(self.sideBar, -1, wx.Bitmap("folder_new.png", wx.BITMAP_TYPE_ANY))
        self.folderDelete = wx.BitmapButton(self.sideBar, -1, wx.Bitmap("folder_delete.png", wx.BITMAP_TYPE_ANY))
        self.depthLabel = wx.StaticText(self.sideBar, -1, "Depth")
        self.depth = wx.SpinCtrl(self.sideBar, -1, "0", min=0, max=100)
        self.folderList = wx.ListBox(self.sideBar, -1, choices=["Current folder"])
        self.fileList = wx.ListCtrl(self.split, -1, style=wx.LC_LIST)

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: wxgPanel.__set_properties
        self.folderNew.SetSize((24, 24))
        self.folderDelete.SetSize((24, 24))
        self.folderList.SetSelection(0)
        self.split.SplitVertically(self.sideBar, self.fileList, 229)
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: wxgPanel.__do_layout
        main = wx.BoxSizer(wx.HORIZONTAL)
        sideBarSizer = wx.BoxSizer(wx.VERTICAL)
        controls = wx.BoxSizer(wx.HORIZONTAL)
        controls.Add(self.folderNew, 0, 0, 0)
        controls.Add(self.folderDelete, 0, 0, 0)
        controls.Add(self.depthLabel, 0, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 10)
        controls.Add(self.depth, 1, wx.LEFT|wx.EXPAND, 4)
        sideBarSizer.Add(controls, 0, wx.EXPAND, 0)
        sideBarSizer.Add(self.folderList, 1, wx.EXPAND, 0)
        self.sideBar.SetAutoLayout(1)
        self.sideBar.SetSizer(sideBarSizer)
        sideBarSizer.Fit(self.sideBar)
        sideBarSizer.SetSizeHints(self.sideBar)
        main.Add(self.split, 1, wx.EXPAND, 0)
        self.SetAutoLayout(1)
        self.SetSizer(main)
        main.Fit(self)
        main.SetSizeHints(self)
        # end wxGlade

# end of class wxgPanel

####Custom----------------------------------------------------------------------

import os,types
import sm.osx, sm.scriptutils

##if sys.platform == 'win32':
##    wx.LC_LIST  = wx.LC_LIST|wx.LC_SMALL_ICON
##else:
##    wx.LC_LIST  = wx.LC_LIST

class Panel(wxgPanel):
    #---constructors
    def __init__(self, panel, *args, **kwds):
        """Arguments come from the parent frame."""
        wx.Bitmap           = panel.app.bitmap
        wx.LC_LIST          = panel.LIST_STYLE
        wxgPanel.__init__(self, parent=panel, id=-1)
        self.panel          = panel
        self.imageList      = wx.ImageList(16,16)
        self.pyIcon         = self.imageList.Add(wx.Bitmap('source_py.png'))
        self.fileList.SetImageList(self.imageList, wx.IMAGE_LIST_SMALL)
        self.split.SetMinimumPaneSize(1)
        self.SetDropTarget(DropAdd(self.add))
        self.SetHelpText(_spe.help.BROWSER)
        self.__events__()


    #---events
    def __events__(self):
        wx.EVT_BUTTON(self.folderNew,-1,self.onFolderNew)
        wx.EVT_BUTTON(self.folderDelete,-1,self.onFolderDelete)
        wx.EVT_LISTBOX(self.folderList,-1, self.onFolderSelect)
        wx.EVT_LIST_ITEM_SELECTED(self.fileList,-1,self.onFileSelect)
        wx.EVT_LIST_ITEM_RIGHT_CLICK(self.fileList,-1,self.onFileRightClick)
        wx.EVT_LIST_ITEM_MIDDLE_CLICK(self.fileList,-1,self.onFileMiddleClick)
        self.folderList.GetSelection()

    def onFileSelect(self,event):
        file=self.files[event.GetIndex()][1]
        self.panel.openList(file)

    def onFileRightClick(self,event):
        file=self.files[event.GetIndex()][1]
        sm.scriptutils.run(file)

    def onFileMiddleClick(self,event):
        file=self.files[event.GetIndex()][1]
        sm.scriptutils.importMod(file)

    def onFolderNew(self,event):
        """When add button clicked, add directory with browse dir dialog."""
        folder = self.folderList.GetStringSelection()
        if folder == 'Current folder':
            folder = self.getCurrentFolder()
        
        print "-----name : ", folder
        dlg = wx.DirDialog(self,defaultPath=folder )        
        if dlg.ShowModal() == wx.ID_OK:
            dir = dlg.GetPath()
            self.add(dir)
        dlg.Destroy()

    def onFolderDelete(self,event):
        """When remove button clicked, remove folder from listbox"""
        index = self.folderList.GetSelection()
        self.deleteFolder(index)

    def onFolderSelect(self,event):
        """Display a list of files when the user clicks a folder."""
        ## Todo: Figure out why this event gets called twice.
        # When SPE is launched the first time you click on any folder in the browser
        #  it generates two selection events.  However after that first click events
        #  get generated normally.
        if not self.depth: return
        self.panel.busyShow()
        recursion=self.depth.GetValue()
        folder=event.GetString()
        
        print "this is the value of folder here : ",folder
        if folder == 'Current folder':
            folder = self.getCurrentFolder()
            self.add(folder)

        if not os.path.exists(folder):
            index = event.GetInt()
            self.deleteFolder(index)

        self.setFileList(folder, recursion)

        self.panel.busyHide()

    #---methods
    #---New Methods added by Sam Widmer
    def deleteFolder(self, index):
        """Delete the folder listbox item @ index and clear the file listcontrol
        this method also will not delete the Current folder item"""
        if index > 0:
            self.folderList.Delete(index)
            self.setFileList('',0)

    def getCurrentFolder(self):
        """Returns the folder path that the 'Current folder' item references"""
        try:
            filename = self.panel.childActive.fileName
        except:
            filename = ''

        if filename in ('unnamed', ''):
            folder = os.getcwd()
        else:
            folder = os.path.dirname(self.panel.childActive.fileName)
        return folder

    def setFileList(self, folder, recursion):
        """Set self.files, clear and add files to the files listcontrol"""
        self.fileList.DeleteAllItems()
        self.files = []
        try:
            self.fileList.SetColumnWidth(-1,300)
        except:
            pass

        if os.path.exists(folder):
            flen = len(folder)+1
            if folder[-1] in ['\\','/']: flen -= 1
            self.files=[(file[flen:], file)
                        for file in sm.osx.listdirR(folder,recursion,['.py','.pyw'])]
            self.files.sort()
            for i, file in enumerate(self.files):
                self.fileList.InsertImageStringItem(i, file[0], self.pyIcon)
    # End of new methods

    def add(self,folders):
        """Add folders to the listbox."""
        if type(folders) not in [types.ListType,types.TupleType]:
            folders=[folders]
        already = self.getFolders()
        for folder in folders:
            if folder not in already:
                if os.path.exists(folder):
                    self.folderList.Append(folder)

    def getFolders(self):
        return [self.folderList.GetString(index) for index in range(self.folderList.GetCount())]

class DropAdd(wx.FileDropTarget):
    """Adds a file to browser when dropped on browser tab."""
    def __init__(self,add):
        wx.FileDropTarget.__init__(self)
        self.add=add
    def OnDropFiles(self,x,y,fileNames):
        fileNames=[dir for dir in fileNames if os.path.isdir(dir)]
        if fileNames:
            self.add(fileNames)
            return 1
        else: return 0
        