# -*- coding: utf-8 -*-

import os
import wx
import wx.xrc as xrc
import ana.Reduction.D4Mat_Manyo as D4Mat
import vis.M2Plot as M2P
import vis.D2Vis as D2Vis
import vis.UtilPlot as UtilPlot
import threading
import time



################################################
#                D4MatSlicer
#    GUI program to treat D4Matrix on Manyo-lib
#          Y.Inamura
#(2011.05.02) ver03 Revise treating axes titles (requred Manyo-lib >2250)
#(2011.04.28) ver02 Add Rebin func.
#(2011.04.11) ver01 firat version
################################################
__version__ = 'ver03(20110502)'

############################
## Load XMl resources file
############################
__XRCRESOURCEFILE = os.path.join( os.environ["UTSUSEMI_BASE_DIR"],'vis','D4MatSlicerP.xrc' )
#__XRCRESOURCEFILE = 'D4MatGUI.xrc'
__res = None

def get_resources():
    """ This function provides access to the XML resources in this module."""
    global __res
    if __res == None:
        __init_resources()
    return __res

def __init_resources():
    global __res
    __res = xrc.EmptyXmlResource()

    __res.Load(__XRCRESOURCEFILE)

###################################
## Make New Matrix Window
###################################
class MakeNewMatrixFrame(wx.Frame):
    def __init__(self,parent):
        """
        """
        self.parent = parent
        
        self.frame = get_resources().LoadFrame(parent.frame, 'NewD4MatrixFrame')
        self.frame.Bind( wx.EVT_BUTTON, self.OnLoadParams, id=xrc.XRCID("btLoadParams"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnMakeNewMatrix, id=xrc.XRCID("btMakeNewMatrix"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnClose, id=xrc.XRCID("btClose"))
        
        mpanel = xrc.XRCCTRL( self.frame, "NewD4MatrixPanel" )
        self.D4MatRangeCtrl = []
        self.D4MatTitle = []
        for i in range(12):
            self.D4MatRangeCtrl.append( xrc.XRCCTRL( mpanel, ( "txt%d" % (i+1) ) ) )
            
        for i in range(4):
            self.D4MatTitle.append( xrc.XRCCTRL( mpanel, ( "v%dtitle" % (i+1) ) ) )

        self.frame.Bind(wx.EVT_CLOSE, self.OnClose)
        self.CommentHead = "D4MatGUI::MakeNewMatrix >>> "
        # show window
        self.frame.Show()

    #################################
    def OnLoadParams(self,evt):
        """
        """
        print self.CommentHead+"OnLoadParams"
        # open dialog
        dlg = wx.FileDialog(self.frame, 'Open VisCont Parameter file ...', os.getcwd(), style=wx.OPEN, wildcard='XML(*.xml)|*.xml')

        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return

        # get file path
        filepath = dlg.GetPath()
        dir = os.path.dirname(filepath)

        (ax_list,title_list) = self.parent.D4Mat.loadVisContParams(filepath)
        for i in range(4):
            ax = ax_list[i]
            self.D4MatRangeCtrl[ i*3 ].SetValue( str("%g" % ax[0]) )
            self.D4MatRangeCtrl[ i*3 + 1 ].SetValue( str("%g" % ax[1]) )
            self.D4MatRangeCtrl[ i*3 + 2 ].SetValue( str("%g" % ax[2]) )
            self.D4MatTitle[ i ].SetValue( title_list[i] )
        
        return

    #################################
    def OnMakeNewMatrix(self,evt):
        """
        """
        print self.CommentHead+"OnMakeNewMatrix"

        # open directory dialog
        dlg = wx.FileDialog( self.frame, 'Choose File to save D4Matrix parameters ...', defaultDir=os.getcwd(), defaultFile='D4Mat.xml', wildcard='xml File(*.xml)|*.xml',style=wx.SAVE )

        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return

        # get path
        filepath = dlg.GetPath()
        dir = os.path.dirname(filepath)
        #print "filepath=",filepath
        #print "dir=",dir
        
        ax_list=[]
        title_list=[]
        for ax in range(4):
            ra = []
            for i in range(3):
                ra.append( float( self.D4MatRangeCtrl[ ax*3 + i ].GetValue() ) )
            ax_list.append(ra)
            title_list.append( self.D4MatTitle[ax].GetValue() )

        pre_label = self.parent.StatusTextCtrl.GetLabel()
        self.parent.StatusTextCtrl.SetLabel( "Making New D4Matrix files..." )
        self.parent.frame.Refresh()
        self.parent.frame.Update()
        self.frame.Refresh()
        self.frame.Update()
        
        self.parent.D4Mat.new( ax_list[0], ax_list[1], ax_list[2], ax_list[3], title_list, str(filepath) )
        ##self.parent.D4Mat.D4Mat._MakeNewParamXml( str(filepath)+".xml" ) ##[inamura 110411]
        for ax in ax_list:
            print self.CommentHead,ax
        
        self.parent.D4Mat.close()
        self.parent._OpenD4Matrix(str(filepath))
        self.parent.StatusTextCtrl.SetLabel( pre_label )

        dlg = wx.MessageDialog(self.frame, "Making New D4Matrix files completed.","",wx.OK)
        ret = dlg.ShowModal()
        
        return

    ##########################################################
    def OnClose(self, evt):
        """
        Close button event
        @param  evt event information
        @retval None
        """        
        self.parent.StatusTextCtrl.SetLabel( "Done." )
        self.frame.Destroy()
        

###################################
## Rebin Matrix Window
###################################
class RebinMatrixFrame(wx.Frame):
    def __init__(self,parent):
        """
        """
        self.parent = parent

        if not self.parent.D4Mat.isOpened():
            dlg = wx.MessageDialog(self.parent.frame, "You need to open D4Matrix at first!!","Warning",wx.OK)
            ret = dlg.ShowModal()
            return
        
        self.frame = get_resources().LoadFrame(parent.frame, 'RebinD4MatrixFrame')
        self.frame.Bind( wx.EVT_BUTTON, self.OnRebinMatrix, id=xrc.XRCID("btRebinMatrix"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnClose, id=xrc.XRCID("btClose"))
        
        mpanel = xrc.XRCCTRL( self.frame, "RebinD4MatrixPanel" )
        self.D4MatRangeCtrl = []
        self.D4MatTitle = []
        self.RebinRatio = []
        for i in range(12):
            self.D4MatRangeCtrl.append( xrc.XRCCTRL( mpanel, ( "txt%d" % (i+1) ) ) )
            
        for i in range(4):
            self.RebinRatio.append( xrc.XRCCTRL( mpanel, ( "spn%dStepRatio" % (i+1) ) ) )
            self.D4MatTitle.append( xrc.XRCCTRL( mpanel, ( "v%dtitle" % (i+1) ) ) )

        self.frame.Bind(wx.EVT_CLOSE, self.OnClose)

        for i in range(4):
            self.D4MatRangeCtrl[ i*3 + 0 ].SetLabel( self.parent.D4MatRangeCtrl[ i*3 + 0 ].GetLabel() )
            self.D4MatRangeCtrl[ i*3 + 1 ].SetLabel( self.parent.D4MatRangeCtrl[ i*3 + 1 ].GetLabel() )
            self.D4MatRangeCtrl[ i*3 + 2 ].SetLabel( self.parent.D4MatRangeCtrl[ i*3 + 2 ].GetLabel() )
            self.D4MatTitle[ i ].SetValue( self.parent.D4MatTitle[ i ].GetValue() )

        self.CommentHead = "D4MatGUI::RebinMatrix >>> "
        
        # show window
        self.frame.Show()

    #################################
    def OnRebinMatrix(self,evt):
        """
        """
        print self.CommentHead+"OnRebinMatrix"

        # open directory dialog
        dlg = wx.FileDialog( self.frame, 'Choose File to save D4Matrix parameters ...', defaultDir=os.getcwd(), defaultFile='D4Mat.xml', wildcard='xml File(*.xml)|*.xml',style=wx.SAVE )

        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return

        # get path
        filepath2 = dlg.GetPath()
        
        # get path2
        ( dir1, filename1 ) = self.parent.D4Mat.putOpenedPath()
        filepath1 = os.path.join( dir1,filename1 )
        
        ax_list=[]
        title_list=[]
        ratio_list=[]
        for ax in range(4):
            ra = []
            for i in range(3):
                ra.append( float( self.D4MatRangeCtrl[ ax*3 + i ].GetLabel() ) )
            ratio_list.append( float( self.RebinRatio[ax].GetValue() ) )
            print self.CommentHead+"Ratio="+str( ratio_list[-1] )
            ra[2] = ra[2]*ratio_list[-1]
            ax_list.append(ra)
            title_list.append( self.D4MatTitle[ax].GetValue() )

        for ax in ax_list:
            print self.CommentHead,ax
            
        pre_label = self.parent.StatusTextCtrl.GetLabel()
        self.parent.StatusTextCtrl.SetLabel( "Making New D4Matrix files..." )
        self.parent.frame.Refresh()
        self.parent.frame.Update()
        self.frame.Refresh()
        self.frame.Update()
        
        self.parent.D4Mat.new( ax_list[0], ax_list[1], ax_list[2], ax_list[3], title_list, str(filepath2) )
        self.parent.D4Mat.close()

        self.parent.StatusTextCtrl.SetLabel( "Rebinning D4Matrix ..." )
        self.parent.frame.Refresh()
        self.parent.frame.Update()
        self.frame.Refresh()
        self.frame.Update()
        
        self.parent.D4Mat.rebin( filepath1, filepath2 )        
        
        self.parent._OpenD4Matrix(str(filepath2))
        self.parent.StatusTextCtrl.SetLabel( pre_label )

        dlg = wx.MessageDialog(self.frame, "Rebinning D4Matrix completed.","",wx.OK)
        ret = dlg.ShowModal()
        
        return
        
        
    ##########################################################
    def OnClose(self, evt):
        """
        Close button event
        @param  evt event information
        @retval None
        """ 
        self.parent.StatusTextCtrl.SetLabel( "Done." )
        self.frame.Destroy()
        
###################################
## Main Window to treat D4Mat
###################################
class D4MatSlicer(wx.Frame):
    __version__ = 'v110411'
    def __init__(self, parent):
        """
        Constructor
        @param parent parent window id
        
        """
        
        ## Make window and set Event handler
        self.frame = get_resources().LoadFrame(parent,"D4MatGUIMainFrame")

        ## bind Button
        self.frame.Bind( wx.EVT_BUTTON, self.OnOpenD4Matrix, id=xrc.XRCID("btOpenD4Matrix"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnCloseD4Matrix, id=xrc.XRCID("btCloseMatrix"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnClearColumn, id=xrc.XRCID("btClearColumn"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnSaveTitles, id=xrc.XRCID("btSaveTitles"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnCloseD4Matrix, id=xrc.XRCID("btCloseMatrix"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnAddSingleFile, id=xrc.XRCID("btAddSingleFile"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnAddFilesInDir, id=xrc.XRCID("btAddFilesInDir"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnRemoveFile, id=xrc.XRCID("btRemoveFile"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnAutoFill, id=xrc.XRCID("btAutoFill"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnSlice, id=xrc.XRCID("btSlice") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnOut3DText, id=xrc.XRCID("btOut3DText") )

        self.D4MatrixFilePathCtrl = xrc.XRCCTRL( self.frame, "stPathToD4MatrixFiles" )
        self.StatusTextCtrl = xrc.XRCCTRL( self.frame, "txtStatus" )
        
        self.ButtonCtrlList = []
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btOpenD4Matrix" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btClearColumn" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btSaveTitles" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btCloseMatrix" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAddSingleFile" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAddFilesInDir" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btRemoveFile" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAutoFill" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btSlice" ) )

        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.Enable(False)
        for i in range(2):
            self.ButtonCtrlList[i].Enable()
        
        mpanel = xrc.XRCCTRL( self.frame, "D4MatSetPanel" )
        self.D4MatRangeCtrl = []
        self.D4MatTitle = []
        for i in range(12):
            self.D4MatRangeCtrl.append( xrc.XRCCTRL( mpanel, ( "txt%d" % (i+1) ) ) )
            
        for i in range(4):
            self.D4MatTitle.append( xrc.XRCCTRL( mpanel, ( "v%dtitle" % (i+1) ) ) )
            

        spanel = xrc.XRCCTRL( self.frame, "SlicePanel" )
        self.SliceAxis = []
        self.SliceRange = []
        self.SliceFoldCB = []

        for i in range(4):
            self.SliceAxis.append( xrc.XRCCTRL( spanel, ( "v%dcb" % (i+1) ) ) )
            #self.SliceAxis[-1].Bind(wx.EVT_COMBOBOX, self.OnSliceAxis, self.SliceAxis[-1])
            self.SliceFoldCB.append( xrc.XRCCTRL( spanel, ( "cks%d" % (i+1) ) ) )
        for i in range(12):
            self.SliceRange.append( xrc.XRCCTRL( spanel, ( "txt%d" % (i+1) ) ) )

        menubar = get_resources().LoadMenuBar("MainMenuBar")
        self.frame.SetMenuBar( menubar )
        self.frame.Bind(wx.EVT_MENU, self.OnOpenMakeNewFrame, id=xrc.XRCID('menu_new_matrix'))
        self.frame.Bind(wx.EVT_MENU, self.OnOpenD4Matrix, id=xrc.XRCID('menu_open_matrix'))
        self.frame.Bind(wx.EVT_MENU, self.OnOpenRebinFrame, id=xrc.XRCID('menu_rebin_matrix'))
        #self.frame.Bind(wx.EVT_MENU, self.OnSaveDataAsText, id=xrc.XRCID('menu_saveas_text'))
        self.frame.Bind(wx.EVT_MENU, self.OnClose, id=xrc.XRCID('menu_exit'))
        
        self.FileListBox = xrc.XRCCTRL( self.frame, "lbFileList" )
        
        ## initialize
        for i in range(4):
            """
            self.D4MatRangeCtrl[ i*3 ].SetValue("-2.0")
            self.D4MatRangeCtrl[ i*3 + 1 ].SetValue("2.0")
            self.D4MatRangeCtrl[ i*3 + 2 ].SetValue("0.05")
            """
            self.D4MatRangeCtrl[ i*3 ].SetLabel("-2.0")
            self.D4MatRangeCtrl[ i*3 + 1 ].SetLabel("2.0")
            self.D4MatRangeCtrl[ i*3 + 2 ].SetLabel("0.05")
            if i != 3:
                self.D4MatTitle[ i ].SetValue( ("Q%d" % (i+1) ) )
            else:
                self.D4MatTitle[ i ].SetValue( "hw" )
                
                            
        self.frame.Show()

        self.D4Mat = D4Mat.D4Mat()
        self.ParamFilePath = ""
        self.CommentHead = "D4MatGUI >>> "
        self.M2Plot = None

    #################################        
    def OnOpenD4Matrix(self,evt):
        """
        """
        print self.CommentHead,"OnOpenD4Matrix"
        # open dialog
        dlg = wx.FileDialog(self.frame, 'Open D4Matrix param file ...', os.getcwd(), style=wx.OPEN, wildcard='XML(*.xml)|*.xml')

        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return

        # get file path
        self.ParamFilePath = str( dlg.GetPath() )
        #dir = os.path.dirname(filepath)
        self._OpenD4Matrix()

    ################################
    def _OpenD4Matrix(self,filepath=""):
        if filepath=="":
            if self.ParamFilePath == "":
                print self.CommentHead + " Not set param file path.."
                return
        else:
            if os.path.exists( filepath ):
                self.ParamFilePath = filepath
            else:
                print self.CommentHead + " Not set param file path.."
                return
        
        ret = self.D4Mat.open(self.ParamFilePath)
        if (ret!=-1):
            self.D4MatrixFilePathCtrl.SetLabel(self.ParamFilePath)
        else:
            return

        for i in range(4):
            vv = self.D4Mat.D4Mat.PutAxRange(i)
            """
            self.D4MatRangeCtrl[ i*3 ].SetValue(str(vv[0]))
            self.D4MatRangeCtrl[ i*3 + 1 ].SetValue(str(vv[1]))
            self.D4MatRangeCtrl[ i*3 + 2 ].SetValue(str(vv[2]))
            """
            self.D4MatRangeCtrl[ i*3 ].SetLabel(str(vv[0]))
            self.D4MatRangeCtrl[ i*3 + 1 ].SetLabel(str(vv[1]))
            self.D4MatRangeCtrl[ i*3 + 2 ].SetLabel(str(vv[2]))
            sv = self.D4Mat.D4Mat.PutAxTitle(i)
            self.D4MatTitle[ i ].SetValue( sv )

        self.FileListBox.Clear()
        FileCompsVec = self.D4Mat.D4Mat.PutFileComponents()
        for i in range(FileCompsVec.size()):
            self.FileListBox.Append( FileCompsVec[i] )
        
        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.Enable(True)
        

    #################################
    def OnCloseD4Matrix(self,evt):
        """
        """
        print self.CommentHead+"OnCloseMatrix"
        
        self._CloseD4Matrix()

        
    #################################
    def OnClearColumn(self,evt):
        """
        """
        print self.CommentHead+"OnClearColumn"
        
        for i in range(4):
            vv = self.D4Mat.D4Mat.PutAxRange(i)
            """
            self.D4MatRangeCtrl[ i*3 ].SetValue(str(vv[0]))
            self.D4MatRangeCtrl[ i*3 + 1 ].SetValue(str(vv[1]))
            self.D4MatRangeCtrl[ i*3 + 2 ].SetValue(str(vv[2]))
            """
            self.D4MatRangeCtrl[ i*3 ].SetLabel(str(vv[0]))
            self.D4MatRangeCtrl[ i*3 + 1 ].SetLabel(str(vv[1]))
            self.D4MatRangeCtrl[ i*3 + 2 ].SetLabel(str(vv[2]))
            sv = self.D4Mat.D4Mat.PutAxTitle(i)
            self.D4MatTitle[ i ].SetValue( sv )

    #################################
    def OnSaveTitles(self,evt):
        """
        """
        titles = []
        for i in range(4):
            tt = self.D4MatTitle[ i ].GetValue()
            titles.append( tt )
        self.D4Mat.setTitles( titles, True )

    #################################
    def OnAddSingleFile(self,evt):
        """
        """
        print self.CommentHead+"OnAddSingleFile"

        # open dialog
        dlg = wx.FileDialog(self.frame, 'Choose VisualCont2 output file ...', os.getcwd(),
                            style=wx.OPEN, wildcard='Binary(*.vbin)|*.vbin|TEXT(*.txt)|*.txt')

        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return
        
        filepath = str( dlg.GetPath() )
        self.StatusTextCtrl.SetLabel( "Loading file %s" % (filepath ) )
        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.Enable(False)

        self.frame.Refresh()
        self.frame.Update()
        
        self.D4Mat.addFromFile( filepath )
        self.StatusTextCtrl.SetLabel( "Done." )
        
        self.FileListBox.Append( filepath )

        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.Enable(True)
        

    #################################
    def OnAddFilesInDir(self,evt):
        """
        """
        print self.CommentHead+"OnAddFilesInDir"
        
        #dlg = wx.DirDialog(self.frame, "Select Directory including VisualCont2 output files ...",os.getcwd(), style=wx.OPEN)
        dlg = wx.DirDialog(self.frame, "Select Directory including VisualCont2 output files ...",os.getcwd())
        if dlg.ShowModal() !=wx.ID_OK:
            return
        
        print self.CommentHead,"DIR=",dlg.GetPath()

        #check selected dir
        filedir = str(dlg.GetPath())
        if not os.path.exists( filedir ):
            print self.CommnetHead + "Cannot find such directory, "+filedir
            raise
        
        #show progress bar
        pdg = wx.ProgressDialog("Loading","Loading VisualCont2 output text files :",len( os.listdir(filedir) ))
        #start sub-thread
        #th = threading.Thread( target=self.D4Mat.addFromTextDir,args=(str( dlg.GetPath() ), ) )
        th = threading.Thread( target=self.D4Mat.addFromDirectry,args=(str( dlg.GetPath() ), ) )
        #th.setDaemon(True)
        th.start()
        # progress
        pdg.Update(self.D4Mat.progress)
        while self.D4Mat.progress <= self.D4Mat.progress_max:
            wx.Sleep(0.5)
            pdg.Update(self.D4Mat.progress)
        pdg.Destroy()
        
        #self.D4Mat.addFromTextDir( str( dlg.GetPath() ) )

        """
        self.FileListBox.Clear()
        
        FileCompsVec = self.D4Mat.D4Mat.PutFileComponents()
        for i in range(FileCompsVec.size()):
            self.FileListBox.Append( FileCompsVec[i] )
        """
        for file in self.D4Mat.AddedFileList:
            self.FileListBox.Append( file )
        
    #################################
    def OnRemoveFile(self,evt):
        """
        """
        print self.CommentHead+"OnRemoveFile"
        selected_list = self.FileListBox.GetSelections()
        
        if len(selected_list)==0:
            return
        else:
            print self.CommentHead,"selected ",selected_list
            print self.CommentHead,"len=",len(selected_list)
            last_index = len(selected_list)-1
            for i in range(last_index+1):
                ind = selected_list[ last_index - i ]
                filepath = self.FileListBox.GetString(ind)
                print self.CommentHead,"Removing File = ",filepath
                ret = self.D4Mat.subtractText( filepath )
                if ret==0:
                    self.FileListBox.Delete(ind)
                

    #################################
    def OnAutoFill(self,evt):
        """
        """
        print self.CommentHead+"OnAutoFill"
        
        #for i in range(12):
        #    self.SliceRange[i].SetValue( self.D4MatRangeCtrl[i].GetValue() )
        for i in range(4):
            vv = self.D4Mat.D4Mat.PutAxRange(i)
            for j in range(3):
                self.SliceRange[ 3*i + j ].SetValue( str(vv[j]) )


    #################################
    def OnSlice(self,evt):
        """
        """
        print self.CommentHead+"OnSlice"
        Axr = []
        type_axes = []
        foldings = []
        for i in range(4):
            ax = self.SliceAxis[i].GetSelection()
            if ax == 0:
                type_axes.append("X")
            elif ax == 1:
                type_axes.append("Y")
            elif ax == 2:
                type_axes.append("T")
            else:
                raise
            
            if self.SliceFoldCB[i].GetValue():
                foldings.append(1)
            else:
                foldings.append(0)
            
            ar = []
            ar.append( float( self.SliceRange[i*3].GetValue() ) )
            ar.append( float( self.SliceRange[i*3+1].GetValue() ) )
            Axr.append(ar)

        self.D4Mat.sliceMat(Axr[0],Axr[1],Axr[2],Axr[3], type_axes, foldings )

        d2 = M2P.D2Matrix()
        map = d2.ReadMatrix( self.D4Mat.SlicedECM )

        titles = ["","","","",""]
        titles[0] = "D4Matrix Slice"
        
        for i,c in enumerate(type_axes):
            title = self.D4MatTitle[i].GetValue()
            if c=="X":
                titles[2] = title
            elif c=="Y":
                titles[3] = title
            else:
                titles[1] += "Ax%d : %s\n" % (i,title)
                titles[1] += "     from %s to %s\n" % (self.SliceRange[i*3].GetValue(),self.SliceRange[i*3+1].GetValue())
        
        titles[4] = "Intensity"
        
        if self.M2Plot == None:
            self.M2Plot = Plot2DMap(0, "D4MatSlicer", self.frame)
            
        self.M2Plot.PlotMap( titles, map)
        
    #################################
    def OnOut3DText(self,evt):
        """
        """
        print self.CommentHead+"OnSlice"
        # open dialog
        dlg = wx.FileDialog(self.frame, 'Choose 3D text output file ...', os.getcwd(),
                            style=wx.SAVE, wildcard='TEXT(*.txt)|*.txt')
        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return
        
        filepath = str( dlg.GetPath() )
        self.StatusTextCtrl.SetLabel( "Data Slicing and save file %s" % (filepath ) )
        
        Axr = []
        type_axes = []
        foldings = []
        for i in range(4):
            ax = self.SliceAxis[i].GetSelection()
            if ax == 0:
                type_axes.append("X")
            elif ax == 1:
                type_axes.append("Y")
            elif ax == 2:
                type_axes.append("T")
            elif ax == 3:
                type_axes.append("Z")
            else:
                raise
            
            if self.SliceFoldCB[i].GetValue():
                foldings.append(1)
            else:
                foldings.append(0)
            
            ar = []
            ar.append( float( self.SliceRange[i*3].GetValue() ) )
            ar.append( float( self.SliceRange[i*3+1].GetValue() ) )
            Axr.append(ar)
            
        import Manyo as mm
        a1v = mm.ListToDoubleVector( Axr[0] )
        a2v = mm.ListToDoubleVector( Axr[1] )
        a3v = mm.ListToDoubleVector( Axr[2] )
        a4v = mm.ListToDoubleVector( Axr[3] )
        def_axes = mm.MakeStringVector()
        fld = mm.ListToInt4Vector( foldings )
        for Axtype in type_axes:
            def_axes.append(Axtype)

        self.D4Mat.D4Mat.OutputText3D(a1v, a2v, a3v, a4v, def_axes, fld, str(filepath) )
        self.StatusTextCtrl.SetLabel( "Ready" )
        
    #################################
    def OnOpenMakeNewFrame(self,evt):
        """
        """
        print self.CommentHead+"OnOpenMakeNewFrame"
        self.StatusTextCtrl.SetLabel( "Opening window for Making New D4Matrix." )
        dlg = MakeNewMatrixFrame(self)
        #self.StatusTextCtrl.SetLabel( "Done." )

        
    #################################
    def OnOpenRebinFrame(self,evt):
        """
        """
        print self.CommentHead+"OnOpenRebinFrame"
        self.StatusTextCtrl.SetLabel( "Opening window for Rebin D4Matrix." )
        dlg = RebinMatrixFrame(self)
        #self.StatusTextCtrl.SetLabel( "Done." )
        

    #################################
    def OnSaveDataAsText(self,evt):
        """
        """
        print self.CommentHead+"OnSaveDataAsText"


    #################################
    def OnClose(self,evt):
        """
        """
        print self.CommentHead+"OnClose"
        self._CloseD4Matrix()
        self.frame.Destroy()


    ################################
    def _CloseD4Matrix(self):
        """
        """
        self.D4Mat.close()
        
        self.ParamFilePath = ""
        self.D4MatrixFilePathCtrl.SetLabel("Not selected.")
        for i in range(2,len(self.ButtonCtrlList)):
            self.ButtonCtrlList[i].Enable(False)
        self.FileListBox.Clear()



#######################################
#  Plot2DMap
####################################### 
class Plot2DMap(object):
    """
    2次元マップ表示クラス
    """ 
    #########################################################
    def __init__(self, num, code, frame):
        """
        コンストラクタ
        @param  num  タブ No.
        @param  code  マップ画面タイトルに付する記号
        @param  frame  親フレーム
        @retval 無し
        """ 
        self.frame = frame
        self.code = code
        self.d2 = None
        if num == 0:
            self.ifi = UtilPlot.IFEvtProp(0)
            self.pno = 0  
        else:
            self.pno = (num+1) * 10  
            self.ifi = UtilPlot.IFEvtProp(self.pno) 

    #########################################
    def PlotMap(self, labels, map):
        """
        2D マップ表示
        @param panel タブのインスタンス
        @param map　2D データ
        @retval 無し
        """
        # D2 プロッタが表示されているか
        if self.d2 == None:
            # 2Dプロッタフレームクローズイベントのリスナー登録
            self.ifi.AddListner('2dclosed',  self.OnNotify2DClose)
            self.d2 = D2Vis.MapD2Frame(self.frame , map, self.pno, self.code) 
        else:
            # データ変更
            self.ifi.NotifyEvent(self, "changedata", map) 

        self.ifi.NotifyEvent(self, "title", (labels[0], labels[1]))
        self.ifi.NotifyEvent(self, "scalelabel", (labels[2], labels[3], labels[4]))

        self.plotNow = (map, labels[0], labels[1])  
 
                
    #########################################
    def OnNotify2DClose(self, *args):
        """
        2Dプロッタクローズイベント受信処理
        @param evt　　イベント
        @retval 無し
        """
        self.d2 = None

    #########################################
    def Request2DClose(self):
        """
        2Dプロッタクローズ要求処理
        @param  無し
        @retval 無し
        """
         # 2Dプロッタが開いているなら
        if self.d2 == None:
             # 2Dプロッタのクローズ要求を出す　
            self.ifi.NotifyEvent(self, "close")


#######################################
#  Splash 
#######################################
class UtsusemiSplashScreen(wx.SplashScreen):
    def __init__(self,splash_path):

        bmp = wx.Image(splash_path).ConvertToBitmap()
        wx.SplashScreen.__init__(self,bmp,
                                 wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT,
                                 5000, None, -1)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.fc = wx.FutureCall( 2000, self.ShowMain)

    def OnClose(self, evt):
        evt.Skip()
        self.Hide()
        if self.fc.IsRunning():
            self.fc.Stop()
            self.ShowMain()

    def ShowMain(self):
        pass


###############################
if __name__=='__main__':
    app = wx.App(False)
    splash_path = os.path.join( os.environ["UTSUSEMI_BASE_DIR"],"ana","Reduction","LOGO_utsusemi_s.png" )
    if os.path.exists(splash_path):
        splash = UtsusemiSplashScreen(splash_path)
        splash.Show()
    
    frame = D4MatSlicer(None)
    app.MainLoop()
