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

import os
import sys
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
import vis.VisContMParams as VCP
import Manyo.Utsusemi as mu
import Manyo as m


################################################
#                D4MatSlicer
#    GUI program to treat D4Matrix on Manyo-lib
#          Y.Inamura
#(2016.06.21-23) ver05 Improve SliceMat and add VirtualD4Mat
#(2016.05.23) ver041 Improve OutputText3D to change treating MASKVALUE
#(2015.04.16) ver04 Add OutputText3D 
#(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__ = 'ver05(20160623)'

############################
## Load XMl resources file
############################
__XRCRESOURCEFILE = os.path.join( os.environ["UTSUSEMI_BASE_DIR"],'vis','D4MatSlicer.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 >>> "
        
        # Justify the alignment of controls on OSX and Windows
        if sys.platform == "darwin":
            self.frame.SetSizeWH( 460,200 )
        if sys.platform=="win32":
            self.frame.SetSizeWH( 455,220 )
        
        # 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()
        flag,msg = self.parent._OpenD4Matrix(str(filepath))
        if not flag:
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return

        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 >>> "
        
        # Justify the alignment of controls on OSX and Windows
        if sys.platform == "darwin":
            self.frame.SetSizeWH( 510,220 )
        if sys.platform=="win32":
            self.frame.SetSizeWH( 510,220 )
        
        # 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 )        
        
        flag,msg = self.parent._OpenD4Matrix(str(filepath2))
        if not flag:
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return

        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()

##[inamura 160523]-->
#########################################
#       SetSaveAsTextDialog
#########################################
class SetSaveAsTextDialog(wx.Dialog):
    """
    SaveAsText 設定ダイアログクラス
    """
    ##########################################################
    def __init__(self, parent, frame):
        """
        コンストラクタ
        @param  parent   親ウィンドウ
        @param  dataobj
        @retval 無し
        """ 
        
        self.parent = parent
        self.frame = frame
        
        # リソース取得      
        self.dialog = get_resources().LoadDialog(frame,"Dg2DSaveAsText")
        
        # チェックボックス
        self.ckIgnoreMask = xrc.XRCCTRL(self.dialog,'ckIgnoreMask')
        
        # チェックボックスのイベントハンドラ登録
        self.ckIgnoreMask.Bind(wx.EVT_CHECKBOX, self.OnIgnoreMask, self.ckIgnoreMask)
        
        # コンボボックス
        self.chMaskVal = xrc.XRCCTRL(self.dialog, 'chMaskValue')
        
        # コンボボックスのイベントハンドラ登録
        self.chMaskVal.Bind(wx.EVT_CHOICE, self.OnMaskVal, self.chMaskVal)
        
        # テキストボックスのコントローラ取得        
        self.txMaskVal = xrc.XRCCTRL(self.dialog, 'txMaskValue')
        
        # ボタンのイベントハンドラを登録
        self.btnSave = xrc.XRCCTRL( self.dialog, 'btSave' )
        self.btnCancel = xrc.XRCCTRL( self.dialog, 'btCancel' )
        self.btnSave.Bind(wx.EVT_BUTTON, self.OnSave, self.btnSave )
        self.btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel )
        
        #[X]ボタン押下時のイベントハンドラ登録
        self.dialog.Bind(wx.EVT_CLOSE, self.OnCancel)
        
        # Set Values
        self.initialize()
        
        # ダイアログ表示
        self.dialog.Show()
        
    ##########################################################
    def initialize(self):
        """
        """
        self.isIgnoreMask = True
        self.useGivenMaskVal = True
        self.ckIgnoreMask.SetValue(True)
        self.chMaskVal.Enable(False)
        self.txMaskVal.Enable(False)
        return
        
    ##########################################################
    def OnIgnoreMask(self, event=None):
        """
        IgnoreMask チェックボックスイベント処理
        @param   event イベント情報   
        @retval 無し
        """ 
        # チェックされたのか
        self.isIgnoreMask = self.ckIgnoreMask.GetValue()
        if self.isIgnoreMask:
            # MaskValue テキストボックスを選択不可
            self.chMaskVal.Enable(False)
            self.txMaskVal.Enable(False)
        else:  
            self.chMaskVal.Enable(True)
            self.txMaskVal.Enable(False)
            index = self.chMaskVal.GetSelection()
            if index==0:
                self.txMaskVal.Enable(True)
                
    ##########################################################
    def OnMaskVal(self, event=None):
        """
        
        """
        self._CtrlParts(True)
        
    ##########################################################
    def OnSave(self, event=None):
        """
        """
        self._CtrlParts(False)
        maskval = 0.0
        if (not self.isIgnoreMask) and self.useGivenMaskVal:
            try:
                maskval = float( self.txMaskVal.GetValue() )
            except:
                msg = "Given Mask Value is invalid (%s)"%(self.txMaskVal.GetValue())
                dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
                dial.ShowModal()
                self._CtrlParts(True)
                return
        

        maskValStr = "MASKVAL"
        if (self.useGivenMaskVal):
            maskValStr = self.txMaskVal.GetValue()
        
        # 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() )
        filepath = str( dlg.GetFilename() )
        self.parent.StatusTextCtrl.SetLabel( "Out3D saves file %s" % (filepath ) )
        self.parent.frame.Refresh()
        self.parent.frame.Update()
        
        Axr = []
        type_axes = []
        foldings = []
        for i in range(4):
            #ax = self.parent.SliceAxis[i].GetSelection() #[inamura 160616]
            ax = self.parent.SliceAxis[i].GetCurrentSelection()
            if ax == 0:
                type_axes.append("X")
            elif ax == 1:
                type_axes.append("Y")
            elif ax == 2:
                type_axes.append("Z")  ##[inamura 160616]
            elif ax == 3:
                type_axes.append("T")  ##[inamura 160616]
            else:
                raise
            
            ##[inamura 160616]-->
            #if self.parent.SliceFoldCB[i].GetValue():
            #    foldings.append(1)
            #else:
            #    foldings.append(0)
            foldings.append( float( self.parent.SliceFoldCB[i].GetValue() ) )
            ##<--[inamura 160616]
            ar = []
            ar.append( float( self.parent.SliceRange[i*3].GetValue() ) )
            ar.append( float( self.parent.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 )  ##[inamura 160616]
        fld = mm.ListToDoubleVector( foldings )
        for Axtype in type_axes:
            def_axes.append(Axtype)


        self.parent.D4Mat.D4Mat.OutputText3D(a1v, a2v, a3v, a4v, def_axes, fld, str(filepath), self.isIgnoreMask, str(maskValStr) )
        self.parent.StatusTextCtrl.SetLabel( "Ready" )

        msg = "Finished Save 3D data to text file : "+filepath
        dial = wx.MessageDialog(None, msg, "Message", wx.OK | wx.ICON_INFORMATION )
        dial.ShowModal()
        self._CtrlParts(True)
        self.OnCancel()

    ##########################################################
    def _CtrlParts(self, isEnable=True):
        """
        """
        if not isEnable in [True,False]:
            return
            
        if isEnable:
            self.btnSave.Enable(True)
            self.btnCancel.Enable(True)
            self.ckIgnoreMask.Enable(True)
            if self.isIgnoreMask:
                self.chMaskVal.Enable(False)
                self.txMaskVal.Enable(False)
            else:
                self.chMaskVal.Enable(True)
                self.txMaskVal.Enable(False)
                index = self.chMaskVal.GetSelection()
                self.useGivenMaskVal = True
                if index==0:
                    self.txMaskVal.Enable(True)
                    pass
                elif index==1:
                    self.txMaskVal.SetValue( str(0.0) )
                elif index==2:
                    self.txMaskVal.SetValue( str(-1.0) )
                else:
                    self.useGivenMaskVal = False
                    self.txMaskVal.SetValue( "" )
        else:
            self.ckIgnoreMask.Enable(False)
            self.chMaskVal.Enable(False)
            self.txMaskVal.Enable(False)
            self.btnSave.Enable(False)
            self.btnCancel.Enable(False)
            
            
    ##########################################################
    def OnCancel(self, evt=None):
        """
        Cancel ボタンイベント処理
        @param  evt イベント情報
        @retval 無し
        """ 
        
        self.dialog.Destroy()        

#[inamrua 160621]-->
###################################
## Make Virtual Matrix Window
###################################
class MakeVirtualD4MatrixFrame(wx.Frame):
    def __init__(self,parent):
        """
        """
        self.parent = parent
        
        self.frame = get_resources().LoadFrame(parent.frame, 'VirtualD4MatrixFrame')
        self.frame.Bind( wx.EVT_BUTTON, self.OnLoadParams, id=xrc.XRCID("btLoadParams"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnSaveParams, id=xrc.XRCID("btSaveParams"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnFillRangeVirtualMatrix, id=xrc.XRCID("btFillRange"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnMakeVirtualMatrix, id=xrc.XRCID("btMakeVirtualMatrix"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnClear, id=xrc.XRCID("btClr"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnMakeNewD4Mat, id=xrc.XRCID("btMakeNewD4Mat"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnEstimateSize, id=xrc.XRCID("btEstimateD4MatSize"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnClose, id=xrc.XRCID("btClose"))
        self.BtnCtrls=[]
        self.BtnCtrls.append( xrc.XRCCTRL( self.frame, "btLoadParams" ) )
        self.BtnCtrls.append( xrc.XRCCTRL( self.frame, "btSaveParams" ) )
        self.BtnCtrls.append( xrc.XRCCTRL( self.frame, "btFillRange" ) )
        self.BtnCtrls.append( xrc.XRCCTRL( self.frame, "btMakeVirtualMatrix" ) )
        self.BtnCtrls.append( xrc.XRCCTRL( self.frame, "btClr" ) )
        self.BtnCtrls.append( xrc.XRCCTRL( self.frame, "btMakeNewD4Mat") )
        self.BtnCtrls.append( xrc.XRCCTRL( self.frame, "btEstimateD4MatSize" ) )
        self.BtnCtrls.append( xrc.XRCCTRL( self.frame, "btClose" ) )
        
        mpanel = xrc.XRCCTRL( self.frame, "VirtualD4MatrixPanel" )
        mpanel0 = xrc.XRCCTRL( self.frame, "panel0" )
        mpanel1 = xrc.XRCCTRL( self.frame, "panel1" )
        mpanel2 = xrc.XRCCTRL( self.frame, 'panel2')
        mpanel3 = xrc.XRCCTRL( self.frame, 'panel3')
        mpanel4 = xrc.XRCCTRL( self.frame, 'panel4')
        
        self.minfo = []
        self.minfo.append( xrc.XRCCTRL(mpanel0,"txEi") )
        self.minfo.append( xrc.XRCCTRL(mpanel0,"txminhw") )
        self.minfo.append( xrc.XRCCTRL(mpanel0,"txmaxhw") )
        self.minfo.append( xrc.XRCCTRL(mpanel0,"txdeltahw") )
        self.minfo.append( xrc.XRCCTRL(mpanel0,"txminphi") )
        self.minfo.append( xrc.XRCCTRL(mpanel0,"txmaxphi") )
        self.minfo.append( xrc.XRCCTRL(mpanel0,"txdeltaphi") )
        
        self.runnotxt = xrc.XRCCTRL(mpanel0, 'txrunno' )
        
        # サンプル情報テキストボックスのコントロールを取得
        self.sinfo = []
        for i in range(15):
            ii = i+1
            txt = "txt%d" % ii
            self.sinfo.append(xrc.XRCCTRL(mpanel1, txt)) 

        self.chrotax1 = xrc.XRCCTRL(mpanel1, 'chRotateAxis1st') 
        self.chrotax2 = xrc.XRCCTRL(mpanel1, 'chRotateAxis2nd')
        self.chrotax3 = xrc.XRCCTRL(mpanel1, 'chRotateAxis3rd')            
        self.chRotationSteps = [self.chrotax1,self.chrotax2,self.chrotax3]


        self.chrotax1.Bind(wx.EVT_CHOICE, self.OnChoiceRotateAxes, self.chrotax1) 
        self.chrotax2.Bind(wx.EVT_CHOICE, self.OnChoiceRotateAxes, self.chrotax2) 
        self.chrotax3.Bind(wx.EVT_CHOICE, self.OnChoiceRotateAxes, self.chrotax3) 
        
        # Projectionテキストボックスのコントロールを取得

        self.uv = []
        for i in range(4):
            uv0 = []
            for j in range(5):
               ii = i*5+j+1
               txt = "ptxt%d" % ii
               uv0.append( xrc.XRCCTRL(mpanel2, txt)) 
            self.uv.append(uv0)



        self.D4MatTitle = []
        for i in range(4):
            self.D4MatTitle.append( xrc.XRCCTRL( mpanel2, ( "ptxt%d"%( i*5 + 5 ) ) ) )
            
        self.D4MatRangeCtrl = []        
        for i in range(12):
            self.D4MatRangeCtrl.append( xrc.XRCCTRL( mpanel4, ( "txt%d" % (i+1) ) ) )
           
        self.frame.Bind(wx.EVT_CLOSE, self.OnClose)
        self.CommentHead = "D4MatGUI::MakeVirtualMat >>> "
        
        menubar = get_resources().LoadMenuBar("MakeVirtualMenuBar")
        self.frame.SetMenuBar( menubar )
        self.frame.Bind(wx.EVT_MENU, self.OnLoadParams, id=xrc.XRCID('menu_load_params'))
        self.frame.Bind(wx.EVT_MENU, self.OnSaveParams, id=xrc.XRCID('menu_save_params'))
        self.frame.Bind(wx.EVT_MENU, self.OnClose, id=xrc.XRCID('menu_exit'))

        # Justify the alignment of controls on OSX and Windows
        if sys.platform == "darwin":
            self.frame.SetSizeWH( 510, 750 )
        if sys.platform=="win32":
            self.frame.SetSizeWH( 490, 755 )

        # 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)

        if not os.path.exists(filepath):
            msg = " Cannot find XML file(%s)" % (filepath)
            print self.CommentHead+"::OnLoadParams >>"+msg
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return

        vcp = VCP.VisContMParams(filepath)
        try:
            lc=vcp.Header['SimpleLatticeConsts']
            uv=vcp.Header['SampleUvec']
            vv=vcp.Header['SampleVvec']
        except:
            msg = "File is invalid. ("+filepath+")"
            print self.CommentHead+"::OnLoadParams >>"+msg
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return

            
        self.sinfo[0].SetValue( "%6.4f" % lc[0] )
        self.sinfo[1].SetValue( "%6.4f" % lc[1] )
        self.sinfo[2].SetValue( "%6.4f" % lc[2] )
        self.sinfo[3].SetValue( "%6.4f" % lc[3] )
        self.sinfo[4].SetValue( "%6.4f" % lc[4] )
        self.sinfo[5].SetValue( "%6.4f" % lc[5] )
        self.sinfo[6].SetValue( "%6.4f" % uv[0] )
        self.sinfo[7].SetValue( "%6.4f" % uv[1] )
        self.sinfo[8].SetValue( "%6.4f" % uv[2] )
        self.sinfo[9].SetValue( "%6.4f" % vv[0] )
        self.sinfo[10].SetValue( "%6.4f" % vv[1] )
        self.sinfo[11].SetValue( "%6.4f" % vv[2] )
        
        ro_list = vcp.Header["SampleRotateSteps"]
        ro_axis_dic={ "Y":1,"Z":2,"X":3 }
        for i,a_rot in enumerate(ro_list):
            ax_num=0
            try:
                ax_num = ro_axis_dic[ a_rot[0] ]
            except:
                pass
            self.chRotationSteps[i].Enable(True)
            self.chRotationSteps[i].SetSelection( ax_num )
            self.sinfo[12+i].SetValue( "%6.4f" % float(a_rot[1]) )
            self.sinfo[12+i].Enable(True)
            if (i+1)<len(self.chRotationSteps):
                self.chRotationSteps[i+1].Enable(True)
            
        ## Projection infor
        for id in range(4):
            for col in range(4):
                self.uv[id][col].SetValue( "%g" % (vcp.proj_axes[str(id)][col]) )
            self.uv[id][4].SetValue( vcp.proj_axes[str(id)][4] )
            
        ## D4Matrix range
        for id in range(4):
            range_axis = vcp.paxis_info[str(id)][1]
            self.D4MatRangeCtrl[3*id + 0].SetValue( "%g" % ( range_axis[0] ) )
            self.D4MatRangeCtrl[3*id + 1].SetValue( "%g" % ( range_axis[1] ) )
            self.D4MatRangeCtrl[3*id + 2].SetValue( "%g" % ( range_axis[2] ) )
            self.D4MatTitle[ id ].SetValue( vcp.proj_axes[str(id)][4] )

        return

    #################################
    def OnSaveParams(self,evt):
        """
        """
        print self.CommentHead+"OnSaveParams"
        
        sample=[]
        for i in range(15):
            anum = self.sinfo[i].GetValue().strip()
            try:
                num = float(anum)
            except:
                raise UtilPlot.PlotException('Common', 'C027', ("Sample Info",))
            sample.append(num)
        
        Header = {}
        Header['SimpleLatticeConsts']=sample[:6]
        Header['SampleUvec']=sample[6:9]
        Header['SampleVvec']=sample[9:12]
        ##[inamura 150527]-->
        #Header['SampleRotatePhi']=sample[12]
        rotationSteps=[]
        for i,rax in zip([0,1,2],self.chRotationSteps):
            if rax.IsEnabled():
                ax_num = rax.GetCurrentSelection()
                if ax_num == 1:
                    rotationSteps.append( ["Y", sample[12+i] ] )
                elif ax_num == 2:
                    rotationSteps.append( ["Z", sample[12+i] ] )
                elif ax_num == 3:
                    rotationSteps.append( ["X", sample[12+i] ] )
                else:
                    break
        Header['SampleRotateSteps']=rotationSteps
        ##<--[inamura 150527]
        
        # Make parameters to give to VisContParams
        ## axisInfo
        axisInfo = []
        for id in range(4):
            a_list = []
            for col in range(4):
                a_list.append( float( self.uv[id][col].GetValue() ) )
            a_list.append( self.uv[id][4].GetValue() )
            axisInfo.append(a_list)

        ## sliceInfo
        type_list = ["x","x","x","x"]

        fold_list = [-1.0,-1.0,-1.0,-1.0]
        
        sliceInfo = []
        for id in range(4):
            a_list = [type_list[id]]
            for i in range(3):
                a_list.append( float( self.D4MatRangeCtrl[3*id + i].GetValue() ) )
            a_list.append( fold_list[id] )
            sliceInfo.append( a_list )

        # make instance
        vcp=VCP.VisContMParams()

        # set parameters
        vcp.SetAllInfo( Header, axisInfo, sliceInfo, [] ) #[inamura 1307xx]

        # open dialog
        dlg = wx.FileDialog(self.frame, 'Save Parameter File  ...', os.getcwd(), style=wx.SAVE, wildcard='XML(*.xml)|*.xml')

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

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

        # show parameters to be checked
        #vcp.ShowParams()

        # save to XML file
        vcp.SaveXML( savefile )

    #################################
    def OnFillRangeVirtualMatrix(self,evt):
        """
        """
        print self.CommentHead+"OnFillRangeVirtualMatrix"
        runNo = int(self.runnotxt.GetValue())
        UGH = mu.UtsusemiGetNeunetHistogram()
        if UGH.SetRunNo( str(runNo) ):
            pass
        else:
            raise UserWarning, "runNo is invalid"
        UGH.SetDetParam("psd")
        
        Ei = float( self.minfo[0].GetValue() )
        minhw = float( self.minfo[1].GetValue() )
        maxhw = float( self.minfo[2].GetValue() )
        deltahw = float( self.minfo[3].GetValue() )
        if deltahw<=0.0 or minhw>maxhw or maxhw>=Ei :
            msg = "Energy Arguments are invalid."
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return
            
        minPhi = float( self.minfo[4].GetValue() )
        maxPhi = float( self.minfo[5].GetValue() )
        delPhi = float( self.minfo[6].GetValue() )
        if delPhi==0.0:
            delPhi=1.0;
            self.minfo[6].SetValue( str(delPhi) )
            
        hist_param = "hw,%f,%f,%f,%f"%(Ei,minhw,maxhw,deltahw)
        if UGH.SetConversionParameter( hist_param ):
            pass
        else:
            raise UserWarning, "hist param (%s) is invalid"%(hist_param)
        
        pfiles = UGH.MakeTempInfoFiles()
        if pfiles.size()<2:
            raise UserWarning, "fails to make tmp parameter files."
        
        btn_status = []
        for abtn in self.BtnCtrls:
            btn_status.append( abtn.IsEnabled() )
            abtn.Disable()
        self.frame.Update()

        lc = m.MakeDoubleVector(6)
        for i in range(6):
            lc[i] = float(self.sinfo[i].GetValue())

        uv = m.MakeDoubleVector(3)
        vv = m.MakeDoubleVector(3)
        for i in range(3):
            uv[i] = float(self.sinfo[6+i].GetValue())
            vv[i] = float(self.sinfo[9+i].GetValue())

        rotSteps = m.MakeDoubleVector()
        ## self.chRotationSteps is [self.chrotax1,self.chrotax2,self.chrotax3]
        for i in range(3):
            if self.sinfo[12+i].IsEnabled():
                axis_num = -1.0
                if self.chRotationSteps[i].GetCurrentSelection()==1:   # if Y-axis
                    axis_num = 1.0                             # 1 means Y-axis in VisualCalcSqe
                elif self.chRotationSteps[i].GetCurrentSelection()==2: # if Z-axis
                    axis_num = 2.0                             # 2 means Z-axis in VisualCalcSqe
                elif self.chRotationSteps[i].GetCurrentSelection()==3: # if X-axis
                    axis_num = 0.0                             # 0 means X-axis in VisualCalcSqe
                else:
                    break
                if axis_num > -1.0:
                    rotSteps.append( axis_num )                # axis number
                    rotSteps.append( float( self.sinfo[12+i].GetValue() ) )   # angle
            else:
                break

        va = m.MakeDoubleVector(16)
        titles = m.MakeStringVector(4)
        for id in range(4):
            for col in range(4):
                va[id*4 + col] = float( self.uv[id][col].GetValue() )
            print "id=",id,self.uv[id][4].GetValue()
            titles[id]= str( self.uv[id][4].GetValue() )

        hw_info = m.MakeDoubleVector(4)
        hw_info[0] = Ei
        hw_info[1] = deltahw
        hw_info[2] = minhw
        hw_info[3] = maxhw
        
        if minPhi>maxPhi:
            tmp_phi = minPhi
            minPhi = maxPhi
            maxPhi = tmp_phi
        if delPhi<0:
            delPhi = -1.0*delPhi
        
        phi_steps = m.MakeDoubleVector()
        phi = minPhi
        while( phi<maxPhi ):
            phi_steps.push_back( phi )
            phi += delPhi
        
        stime = time.time()        
        self.parent.D4Mat.D4Mat._CalcVirtualAngleInfo( pfiles[0], pfiles[1] )
        est_ranges=self.parent.D4Mat.D4Mat.EstimateRangeOfVirtualMat(lc, uv, vv, rotSteps, va, hw_info, phi_steps)
        print "  Allocation is finish : cost = ",time.time()-stime

        for i in range(4):
            self.D4MatRangeCtrl[ i*3 ].SetValue("%5.2f"%(est_ranges[i*2]))
            self.D4MatRangeCtrl[ i*3 + 1 ].SetValue("%5.2f"%(est_ranges[i*2+1]))
        self.D4MatRangeCtrl[ 11 ].SetValue("%5.2f"%(deltahw))
        
        self.parent.FileListBox.Clear()
        
        for btn_ctrl in self.parent.ButtonCtrlList:
            btn_ctrl.Enable(True)
        self.parent.isEnableSlice=True       #[inamura 170228]
        self.parent.CheckEnableSliceButton() #[inamura 170228]

        #for i in [4,5,6,9,10,11]:
        for i in [4,5,6,8,9,10]:
            self.parent.ButtonCtrlList[i].Enable(False)
            
        for astatus,abtn in zip(btn_status,self.BtnCtrls):
            abtn.Enable(astatus)
        self.frame.Update()
        
        return
        
    #################################
    def OnMakeVirtualMatrix(self,evt):
        """
        """
        print self.CommentHead+"OnMakeVirtualMatrix"
        runNo = int(self.runnotxt.GetValue())
        UGH = mu.UtsusemiGetNeunetHistogram()
        if UGH.SetRunNo( str(runNo) ):
            pass
        else:
            raise UserWarning, "runNo is invalid"
        UGH.SetDetParam("psd")
        
        Ei = float( self.minfo[0].GetValue() )
        minhw = float( self.minfo[1].GetValue() )
        maxhw = float( self.minfo[2].GetValue() )
        deltahw = float( self.minfo[3].GetValue() )
        if deltahw<=0.0 or minhw>maxhw or maxhw>=Ei :
            msg = "Energy Arguments are invalid."
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return
        
        minPhi = float( self.minfo[4].GetValue() )
        maxPhi = float( self.minfo[5].GetValue() )
        delPhi = float( self.minfo[6].GetValue() )
        if delPhi==0.0:
            delPhi=1.0;
            self.minfo[6].SetValue( str(delPhi) )
        
        hist_param = "hw,%f,%f,%f,%f"%(Ei,minhw,maxhw,deltahw)
        if UGH.SetConversionParameter( hist_param ):
            pass
        else:
            raise UserWarning, "hist param (%s) is invalid"%(hist_param)
        
        pfiles = UGH.MakeTempInfoFiles()
        if pfiles.size()<2:
            raise UserWarning, "fails to make tmp parameter files."
        
        btn_status = []
        for abtn in self.BtnCtrls:
            btn_status.append( abtn.IsEnabled() )
            abtn.Disable()
        self.frame.Update()
        
        lc = m.MakeDoubleVector(6)
        for i in range(6):
            lc[i] = float(self.sinfo[i].GetValue())

        uv = m.MakeDoubleVector(3)
        vv = m.MakeDoubleVector(3)
        for i in range(3):
            uv[i] = float(self.sinfo[6+i].GetValue())
            vv[i] = float(self.sinfo[9+i].GetValue())

        rotSteps = m.MakeDoubleVector()
        ## self.chRotationSteps is [self.chrotax1,self.chrotax2,self.chrotax3]
        for i in range(3):
            if self.sinfo[12+i].IsEnabled():
                axis_num = -1.0
                if self.chRotationSteps[i].GetCurrentSelection()==1:   # if Y-axis
                    axis_num = 1.0                             # 1 means Y-axis in VisualCalcSqe
                elif self.chRotationSteps[i].GetCurrentSelection()==2: # if Z-axis
                    axis_num = 2.0                             # 2 means Z-axis in VisualCalcSqe
                elif self.chRotationSteps[i].GetCurrentSelection()==3: # if X-axis
                    axis_num = 0.0                             # 0 means X-axis in VisualCalcSqe
                else:
                    break
                if axis_num > -1.0:
                    rotSteps.append( axis_num )                # axis number
                    rotSteps.append( float( self.sinfo[12+i].GetValue() ) )   # angle
            else:
                break

        va = m.MakeDoubleVector(16)
        titles = m.MakeStringVector(4)
        for id in range(4):
            for col in range(4):
                va[id*4 + col] = float( self.uv[id][col].GetValue() )
            print "id=",id,self.uv[id][4].GetValue()
            titles[id]= str( self.uv[id][4].GetValue() )

        hw_info = m.MakeDoubleVector(4)
        hw_info[0] = Ei
        hw_info[1] = deltahw
        hw_info[2] = minhw
        hw_info[3] = maxhw
        
        if minPhi>maxPhi:
            tmp_phi = minPhi
            minPhi = maxPhi
            maxPhi = tmp_phi
        if delPhi<0:
            delPhi = -1.0*delPhi
        
        phi_steps = m.MakeDoubleVector()
        phi = minPhi
        while( phi<maxPhi ):
            phi_steps.push_back( phi )
            phi += delPhi
        
        ranges = []
        for id in range(4):
            tmp = m.MakeDoubleVector(3)
            tmp[0] = float( self.D4MatRangeCtrl[3*id + 0].GetValue() )
            tmp[1] = float( self.D4MatRangeCtrl[3*id + 1].GetValue() )
            tmp[2] = float( self.D4MatRangeCtrl[3*id + 2].GetValue() )
            ranges.append( tmp )
            
        print "---------------------------------------"
        print "wfile, dfile=",pfiles[0], pfiles[1]
        print "lc = ",lc[0],lc[1],lc[2],lc[3],lc[4],lc[5]
        print "uv = ",uv[0],uv[1],uv[2]
        print "vv = ",vv[0],vv[1],vv[2]

        stime = time.time()        
        self.parent.D4Mat.D4Mat._CalcVirtualAngleInfo( pfiles[0], pfiles[1] )
        self.parent.D4Mat.D4Mat.AllocateVirtualMat(lc, uv, vv, rotSteps, va, hw_info, phi_steps,ranges[0],ranges[1],ranges[2],ranges[3],titles )
        print "  Allocation is finish : cost = ",time.time()-stime

        for i in range(4):
            vv = self.parent.D4Mat.D4Mat.PutAxRange(i)
            self.parent.D4MatRangeCtrl[ i*3 ].SetLabel(str(vv[0]))
            self.parent.D4MatRangeCtrl[ i*3 + 1 ].SetLabel(str(vv[1]))
            self.parent.D4MatRangeCtrl[ i*3 + 2 ].SetLabel(str(vv[2]))
            sv = self.parent.D4Mat.D4Mat.PutAxTitle(i)
            self.parent.D4MatTitle[ i ].SetValue( sv )
        
        self.parent.FileListBox.Clear()
        
        for btn_ctrl in self.parent.ButtonCtrlList:
            btn_ctrl.Enable(True)
        self.parent.isEnableSlice=True       #[inamura 170228]
        self.parent.CheckEnableSliceButton() #[inamura 170228]

        #for i in [4,5,6,9,10,11]:
        for i in [4,5,6,8,9,10]:
            self.parent.ButtonCtrlList[i].Enable(False)
        
        dlg = wx.MessageDialog(self.frame, "Making Virtual D4Matrix completed.","",wx.OK)
        ret = dlg.ShowModal()
        
        self.parent.D4MatrixFilePathCtrl.SetLabel("VIRTUAL D4Matrix Mode")
        self.parent.VirtualD4MatTextCtrl.SetLabel("VIRTUAL ( Ei=%g hw=[%g:%g:%g], Angle=[%g:%g:%g] )"%(Ei,minhw,maxhw,deltahw,minPhi,maxPhi,delPhi))
        self.parent.FileListBox.Clear()
        self.parent.FileListBox.Append( "Virtual Mode" )
        self.parent.OnAutoFill(None)
        
        for astatus,abtn in zip(btn_status,self.BtnCtrls):
            abtn.Enable(astatus)
        self.frame.Update()

        return
        
    #########################################
    def OnChoiceRotateAxes(self, evt):
        """
        CHOICE Event
        ##[inamura 150526]
        @param evt    Event
        @retval None
        """
        bt = evt.GetEventObject()
        if bt==self.chrotax1:
            if self.chrotax1.GetCurrentSelection()==0:
                self.sinfo[12].Enable(False)
                self.chrotax2.Enable(False)
                self.sinfo[13].Enable(False)
                self.chrotax3.Enable(False)
                self.sinfo[14].Enable(False)
            else:
                self.sinfo[12].Enable(True)
                self.chrotax2.Enable(True)
                if self.chrotax2.GetCurrentSelection()==0:
                    self.sinfo[13].Enable(False)
                    self.chrotax3.Enable(False)
                    self.sinfo[14].Enable(False)
                else:
                    self.sinfo[13].Enable(True)
                    self.chrotax3.Enable(True)
                    if self.chrotax3.GetCurrentSelection()==0:
                        self.sinfo[14].Enable(False)
                    else:
                        self.sinfo[14].Enable(True)
                        
        elif bt==self.chrotax2:
            if self.chrotax1.GetCurrentSelection()==0:
                self.sinfo[13].Enable(False)
                self.chrotax3.Enable(True)
                self.sinfo[14].Enable(False)
            else:
                if bt.GetCurrentSelection()==0:
                    self.sinfo[13].Enable(False)
                    self.chrotax3.Enable(False)
                    self.sinfo[14].Enable(False)
                else:
                    self.chrotax3.Enable(True)
                    self.sinfo[13].Enable(True)
                    if self.chrotax3.GetCurrentSelection()==0:
                        self.sinfo[14].Enable(False)
                    else:
                        self.sinfo[14].Enable(True)
                        
        else:
            if (self.chrotax1.GetCurrentSelection()==0) or (self.chrotax2.GetCurrentSelection()==0) or (bt.GetCurrentSelection()==0):
                self.sinfo[14].Enable(False)
            else:
                self.sinfo[14].Enable(True)
        
            

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

    #################################
    def OnMakeNewD4Mat(self,evt):
        """
        """
        # 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()
        
        btn_status = []
        for abtn in self.BtnCtrls:
            btn_status.append( abtn.IsEnabled() )
            abtn.Disable()
        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()
        flag,msg = self.parent._OpenD4Matrix(str(filepath))
        if not flag:
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return

        self.parent.StatusTextCtrl.SetLabel( pre_label )
        
        for astatus,abtn in zip(btn_status,self.BtnCtrls):
            abtn.Enable(astatus)
        self.frame.Update()

        dlg = wx.MessageDialog(self.frame, "Making New D4Matrix files completed. Push OK to close this VirtualD4Mat Setting","",wx.OK)
        ret = dlg.ShowModal()
        self.parent.VirtualD4MatTextCtrl.SetLabel("No Info")
        self.OnClose(None)

        
    #################################
    def OnEstimateSize(self,evt):
        """
        """
        num_list=[]
        for ax in range(4):
            ra = []
            for i in range(3):
                ra.append( float( self.D4MatRangeCtrl[ ax*3 + i ].GetValue() ) )
            num = int( (ra[1]-ra[0])/ra[2] )
            num_list.append(num)
        
        size_bit = (num_list[0]+1)*(num_list[1]+1)*(num_list[2]+1)*(num_list[3]+1)*3.0*32.0
        size_MB = size_bit/8.0/1024.0/1024.0
        msg = "Estimated Size of D4Matrix data is %f MB"%size_MB
        dlg = wx.MessageDialog(self.frame, msg,"",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()



#<--[inamrua 160621]

##<-[inamura 160523]        
###################################
## 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.OnMakeVirtualMat, id=xrc.XRCID("btMakeVirtualMat")) #[inamura 160621]
        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.OnAutoFill, id=xrc.XRCID("btAutoFillAx1") ) #[inamura 160616]
        self.frame.Bind( wx.EVT_BUTTON, self.OnAutoFill, id=xrc.XRCID("btAutoFillAx2") ) #[inamura 160616]
        self.frame.Bind( wx.EVT_BUTTON, self.OnAutoFill, id=xrc.XRCID("btAutoFillAx3") ) #[inamura 160616]
        self.frame.Bind( wx.EVT_BUTTON, self.OnAutoFill, id=xrc.XRCID("btAutoFillAx4") ) #[inamura 160616]
        self.frame.Bind( wx.EVT_BUTTON, self.OnSlice, id=xrc.XRCID("btSlice") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnSlice3d, id=xrc.XRCID("btSlice3D") ) #[inamura 160616]
        self.frame.Bind( wx.EVT_BUTTON, self.OnOut3DText, id=xrc.XRCID("btOut3DText") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnDumpToText, id=xrc.XRCID("btDumpToText") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnDumpToBin, id=xrc.XRCID("btDumpToBin") )

        self.D4MatrixFilePathCtrl = xrc.XRCCTRL( self.frame, "stPathToD4MatrixFiles" )
        self.StatusTextCtrl = xrc.XRCCTRL( self.frame, "txtStatus" )
        self.VirtualD4MatTextCtrl = xrc.XRCCTRL( self.frame, "txtvmsg" ) #[inamura 160627]
        
        self.ButtonCtrlList = []
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btOpenD4Matrix" ) ) # 0
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btClearColumn" ) )  # 1
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btSaveTitles" ) )   # 2
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btCloseMatrix" ) )  # 3
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAddSingleFile" ) )# 4
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAddFilesInDir" ) )# 5
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btRemoveFile" ) )   # 6
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAutoFill" ) )     # 7
        #self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btSlice" ) )        # 8
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btOut3DText" ) )    # 9->8
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btDumpToText" ) )   # 10->9
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btDumpToBin" ) )    # 11->10
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAutoFillAx1" ) ) ##[inamura 160616]
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAutoFillAx2" ) ) ##[inamura 160616]
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAutoFillAx3" ) ) ##[inamura 160616]
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAutoFillAx4" ) ) ##[inamura 160616]
        ##[inamura 170227]-->
        #self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btSlice3D" ) )
        self.SliceButtonCtrlList=[xrc.XRCCTRL( self.frame, "btSlice" ), xrc.XRCCTRL( self.frame, "btSlice3D" ) ]
        self.isEnableSlice = False
        ##<--[inamura 170227]
        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.Enable(False)
        self.SliceButtonCtrlList[0].Enable(False) #[inamura 170227]
        self.SliceButtonCtrlList[1].Enable(False) #[inamura 170227]
        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 = []
        self.SliceFoldDiag = []

        self.cbdiagfold = xrc.XRCCTRL(spanel, 'cbDiagFoldType')
        self.cbdiagfold.Bind(wx.EVT_CHOICE, self.OnComboDiagFold, self.cbdiagfold)
        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, ( "txtFold%d" % (i+1) ) ) )     ##[inamura 160616]
            self.SliceFoldDiag.append( xrc.XRCCTRL( spanel, ( "ckbUseAx%1dFold" % (i+1) ) ) )
        for i in range(12):
            self.SliceRange.append( xrc.XRCCTRL( spanel, ( "txt%d" % (i+1) ) ) )

        ## Axis type bind #[inamura 170228]-->
        for i in range(4):
            self.SliceAxis[i].Bind(wx.EVT_CHOICE, self.OnChangeSliceAxis, self.SliceAxis[i])
        #<--[inamura 170228]
        
        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" )
                
                            
        # Justify the alignment of controls on OSX
        if sys.platform == "darwin":
            self.frame.SetSizeWH(540,740)
        if sys.platform =="win32":
            self.frame.SetSizeWH(540,720)

        self.frame.Show()
        
        self.D4Mat = D4Mat.D4Mat()
        self.ParamFilePath = ""
        self.CommentHead = "D4MatGUI >>> "
        self.M2Plot = None
        self.MakeVirtualFrame = None
        self.SliceViewer3d = None #[inamura 170227]

    #################################        
    def OnOpenD4Matrix(self,evt):
        """
        """
        print self.CommentHead,"OnOpenD4Matrix"
        ##[inamura 160621]-->
        # isVirtual? 
        if self.D4Mat.D4Mat.isVirtualMode():
            dlg = wx.MessageDialog(self.frame, "Now You use Virtual Matrix. Are you sure to delete it ?", 'Question', wx.YES_NO|wx.NO_DEFAULT|wx.ICON_QUESTION)
            if dlg.ShowModal() !=wx.ID_YES:
                return
        try:
            if self.MakeVirtualFrame != None:
                self.MakeVirtualFrame.OnClose(None)
        except:
            pass
        self.VirtualD4MatTextCtrl.SetLabel("No Info")
        ##<--[inamura 160621]
        # 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)
        flag,msg = self._OpenD4Matrix()
        if not flag:
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return


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

        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)
        self.isEnableSlice=True       #[inamura 170228]
        self.CheckEnableSliceButton() #[inamura 170228]
        
        self.OnAutoFill()
        return (True,"")

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

        
    #[inamrua 160621]-->
    #################################
    def OnMakeVirtualMat(self,evt):
        """
        """
        print self.CommentHead+"OnMakeVirtualMat"
        if self.D4Mat.D4Mat.isMatOpened():
            dlg = wx.MessageDialog(self.frame, "Now You open D4Matrix. Are you sure to close it ?", 'Question', wx.YES_NO|wx.NO_DEFAULT|wx.ICON_QUESTION)
            if dlg.ShowModal() !=wx.ID_YES:
                return
        try:
            self.OnCloseD4Matrix(None)
        except:
            pass
            
        self.StatusTextCtrl.SetLabel( "Opening window for Making Virtual or New D4Matrix." )
        self.MakeVirtualFrame = MakeVirtualD4MatrixFrame(self)
        
    #<--[inamura 160621]
    #################################
    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.isEnableSlice=False       #[inamura 170228]
        self.CheckEnableSliceButton() #[inamura 170228]

        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)
        self.isEnableSlice=True       #[inamura 170228]
        self.CheckEnableSliceButton() #[inamura 170228]
        

    #################################
    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
        self.D4Mat.progress=0 #[inamura 180412]
        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(True):                           ##[inamura 170116]-->
            wx.Sleep(0.5)
            if (self.D4Mat.progress > self.D4Mat.progress_max):
                break                          ##<--[inamura 170116]
            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 )
        
        ##[inamura 170116]-->
        msg = "Finished: Load vbin files in "+filedir
        dial = wx.MessageDialog(None, msg, "Message", wx.OK | wx.ICON_INFORMATION )
        dial.ShowModal()
        return
        ##<--[inamura 170116]
        
    #################################
    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=None):
        """
        """
        print self.CommentHead+"OnAutoFill"
        #[inamura 160621]-->
        if (evt==None):
            bt_name = "btAutoFill"
        else:
            bt_name = evt.GetEventObject().GetName()
        bt_list = None
        if bt_name=="btAutoFill":
            bt_list=[0,1,2,3]
        elif bt_name=="btAutoFillAx1":
            bt_list=[0]
        elif bt_name=="btAutoFillAx2":
            bt_list=[1]
        elif bt_name=="btAutoFillAx3":
            bt_list=[2]
        elif bt_name=="btAutoFillAx4":
            bt_list=[3]
        else:
            return
        #<--[inamura 160621]
        #for i in range(12):
        #    self.SliceRange[i].SetValue( self.D4MatRangeCtrl[i].GetValue() )
        #for i in range(4): #[inamura 160616]
        for i in bt_list:
            vv = self.D4Mat.D4Mat.PutAxRange(i)
            for j in range(3):
                self.SliceRange[ 3*i + j ].SetValue( str(vv[j]) )

    #[inamura 170228]-->
    #################################
    def OnChangeSliceAxis(self,evt):
        """
        """
        self.CheckEnableSliceButton()

    #########################################
    def CheckEnableSliceButton(self):
        """
        """
        if self.isEnableSlice:
            flags = [0,0,0,0]
            for i in range(4):
                curNo = self.SliceAxis[i].GetCurrentSelection()
                flags[curNo] +=1
            if flags==[1,1,0,2]:
                self.SliceButtonCtrlList[0].Enable(True)
                self.SliceButtonCtrlList[1].Enable(False)
            elif flags==[1,1,1,1]:
                self.SliceButtonCtrlList[0].Enable(False)
                self.SliceButtonCtrlList[1].Enable(True)
            else:
                self.SliceButtonCtrlList[0].Enable(False)
                self.SliceButtonCtrlList[1].Enable(False)
        else:
            self.SliceButtonCtrlList[0].Enable(False)
            self.SliceButtonCtrlList[1].Enable(False)
            
        if self.D4Mat.D4Mat.isVirtualMode():
            self.SliceButtonCtrlList[1].Enable(False)
    #<--[inamura 170228]
    #########################################
    def OnComboDiagFold(self, evt):
        """
        """
        index = 0
        if isinstance( evt, int ):
            index = evt
        else:
            bt = evt.GetEventObject()
            index = bt.GetSelection()
        
        if index==0:
            for obj in self.SliceFoldDiag:
                obj.SetValue(False)
                obj.Enable(False)
        else:
            for obj in self.SliceFoldDiag:
                obj.Enable(True)
    
    #################################
    def OnSlice(self,evt):
        """
        """
        print self.CommentHead+"OnSlice"
        #[inamura 160630]--> #check X,Y and Z
        flags=[0,0,0,0]
        for i in range(4):
            ax = self.SliceAxis[i].GetCurrentSelection()
            if ax == 0: # X
                flags[0]+=1
            elif ax == 1: # Y
                flags[1]+=1
            elif ax == 2: # Z
                flags[2]+=1
            elif ax == 3: # T
                flags[3]+=1
            else:
                raise
        if flags!=[1,1,0,2]:
            msg = "Axis type selections are invalid."
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return
        #<--[inamrua 160630]
        
        Axr = []
        type_axes = []
        foldings = []
        for i in range(4):
            #ax = self.SliceAxis[i].GetSelection() #[inamura 160616]
            ax = self.SliceAxis[i].GetCurrentSelection() 
            if ax == 0:
                type_axes.append("X")
            elif ax == 1:
                type_axes.append("Y")
            elif ax == 2:
                type_axes.append("Z") #[inamura 160616]
            elif ax == 3:
                type_axes.append("T")
            else:
                raise
            
            #[inamura 160616]-->
            #if self.SliceFoldCB[i].GetValue():
            #    foldings.append(1)
            #else:
            #    foldings.append(0)
            foldings.append( float( self.SliceFoldCB[i].GetValue() ) )
            #<--[inamura 160616]
            
            ar = []
            ar.append( float( self.SliceRange[i*3].GetValue() ) )
            ar.append( float( self.SliceRange[i*3+1].GetValue() ) )
            Axr.append(ar)
        
        DiagCond = self.cbdiagfold.GetSelection()
        print "### DiagCond = ",DiagCond
        if DiagCond==wx.NOT_FOUND:
            print "Not Secected"
        elif (DiagCond==1) or (DiagCond==2) or (DiagCond==3):
            foldings.append( float( DiagCond ) )
            ax_fold = []
            for i in range(len(self.SliceFoldDiag)):
                if self.SliceFoldDiag[i].GetValue():
                    ax_fold.append(i)
            if len(ax_fold)!=2:
                print "the number of Checked must be 2"
                return
            else:
                foldings.append( float( ax_fold[0] ) )
                foldings.append( float( ax_fold[1] ) )
        else:
            foldings.append(-1.0)
            foldings.append(0.0)
            foldings.append(0.0)

        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())
        tmp_str = "Fold:"
        cnt_fld = 0
        for j in range(4):
            if float(self.SliceFoldCB[j].GetValue())!=-1.0:
                if cnt_fld>1:
                    tmp_str += "\n      Ax%d[%g]"%(j+1,float(self.SliceFoldCB[j].GetValue()))
                else:
                    tmp_str += " Ax%d[%g]"%(j+1,float(self.SliceFoldCB[j].GetValue()))
                cnt_fld+=1

        if tmp_str=="Fold:":
            pass
        else:
            titles[1] += tmp_str
        
        titles[4] = "Intensity"
        
        if self.M2Plot == None:
            self.M2Plot = Plot2DMap(0, "D4MatSlicer", self.frame)
            
        self.M2Plot.PlotMap( titles, map, type_axes)

    ##[inamura 170227]-->
    #################################
    def OnSlice3d(self,evt):
        """
        """
        #print self.CommentHead+"OnSlice3d"
        flags=[0,0,0,0]
        for i in range(4):
            ax = self.SliceAxis[i].GetCurrentSelection()
            if ax == 0: # X
                flags[0]+=1
            elif ax == 1: # Y
                flags[1]+=1
            elif ax == 2: # Z
                flags[2]+=1
            elif ax == 3: # T
                flags[3]+=1
            else:
                raise
        if flags!=[1,1,1,1]:
            msg = "Axis type selections are invalid."
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return
        
        Axr = []
        type_axes = []
        foldings = []
        name_axes = ["-","-","-"]
        for i in range(4):
            ax = self.SliceAxis[i].GetCurrentSelection()
            if ax == 0:
                type_axes.append("X")
                name_axes[0] = self.D4MatTitle[i].GetValue()
            elif ax == 1:
                type_axes.append("Y")
                name_axes[1] = self.D4MatTitle[i].GetValue()
            elif ax == 2:
                type_axes.append("Z")
                name_axes[2] = self.D4MatTitle[i].GetValue()
            elif ax == 3:
                type_axes.append("T")
            else:
                raise
            
            foldings.append( float( self.SliceFoldCB[i].GetValue() ) )
            
            ar = []
            ar.append( float( self.SliceRange[i*3].GetValue() ) )
            ar.append( float( self.SliceRange[i*3+1].GetValue() ) )
            Axr.append(ar)

        keys_axes = ["Vx","Vy","Vz"]
        print "Keys=",keys_axes[0],keys_axes[1],keys_axes[2]
        self.D4Mat.sliceMat3d(Axr[0],Axr[1],Axr[2],Axr[3], type_axes, foldings, keys_axes )
        
        import vis.SliceViewer3D as SV
        if self.SliceViewer3d==None:
            self.SliceViewer3d = SV.SliceViewer()
        
        if self.SliceViewer3d.setData( 0, self.D4Mat.SlicedECM, "Sliced data in D4MatSlicer" ):
            pass
        else:
            del self.SliceViewer3d
            self.SliceViewer3d = SV.SliceViewer()
            self.SliceViewer3d.setData( 0, self.D4Mat.SlicedECM, "Sliced data in D4MatSlicer" )

        titles = []
        for a_name in name_axes:
            titles.append( a_name.replace(" ","") )
        self.SliceViewer3d.setAxesTitles( titles[0], titles[1], titles[2] )
        
    ##<--[inamura 170227]
        
    #################################
    def OnOut3DText(self,evt):
        """
        """
        print self.CommentHead+"OnOut3DText"
        #[inamura 160630]--> #check X,Y and Z
        flags=[0,0,0,0]
        for i in range(4):
            ax = self.SliceAxis[i].GetCurrentSelection()
            if ax == 0: # X
                flags[0]+=1
            elif ax == 1: # Y
                flags[1]+=1
            elif ax == 2: # Z
                flags[2]+=1
            elif ax == 3: # T
                flags[3]+=1
            else:
                raise
        if flags!=[1,1,1,1]:
            msg = "Invalid axis types. You must choose axes X,Y,Z and T for each."
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return
        #<--[inamrua 160630]
        
        self.MaskValInfo=[True,False,0.0] # [<Ignore Points with MaskVal>, <Use Given MasVal>, <MaskVal>]
        dlg = SetSaveAsTextDialog( self, self.frame )
        
        """
        maskValStr=""        
        if (self.MaskValInfo[1]):
            maskValStr = str( self.MaskValInfo[2] )
        else:
            maskValStr = "MASKVALUE"

        # 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() )
        filepath = str( dlg.GetFilename() )
        self.StatusTextCtrl.SetLabel( "Out3D saves file %s" % (filepath ) )
        self.frame.Refresh()
        self.frame.Update()
        
        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.D4Mat.D4Mat.OutputText3D(a1v, a2v, a3v, a4v, def_axes, fld, str(filepath), self.MaskValInfo[0], maskValStr )
        self.StatusTextCtrl.SetLabel( "Ready" )
        """

    #################################
    def OnDumpToText(self,env):
        """
        """
        self.DumpToFile(True)
    #################################
    def OnDumpToBin(self,env):
        """
        """
        self.DumpToFile(False)
    #################################
    def DumpToFile(self,isText):
        """
        """
        print self.CommentHead+"OnSlice::DumpToFile"
        
        Axr = []
        type_axes = []
        foldings = []
        flag_axes = [0,0,0,0]
        for i in range(4):
            #ax = self.SliceAxis[i].GetSelection() #[inamura 160616]
            ax = self.SliceAxis[i].GetCurrentSelection()
            if ax == 0:
                type_axes.append("X")
                flag_axes[0] +=1
            elif ax == 1:
                type_axes.append("Y")
                flag_axes[1] +=1
            elif ax == 2:
                type_axes.append("Z") #[inamura 160616]
                flag_axes[2] +=1
            elif ax == 3:
                type_axes.append("T") #[inamura 160616]
                flag_axes[3] +=1
            else:
                raise
            
            ##[inamura 160616]-->
            #if self.SliceFoldCB[i].GetValue():
            #    foldings.append(1)
            #else:
            #    foldings.append(0)
            foldings.append( float( self.SliceFoldCB[i].GetValue() ) )
            #<--[inamura 160616]
            
            ar = []
            ar.append( float( self.SliceRange[i*3].GetValue() ) )
            ar.append( float( self.SliceRange[i*3+1].GetValue() ) )
            Axr.append(ar)
            
        if flag_axes!=[1,1,1,1]:
            msg = "Invalid axes types. You must choose X,Y,Z and T for each."
            dial = wx.MessageDialog(None, msg, "Warning", wx.OK | wx.ICON_EXCLAMATION )
            dial.ShowModal()
            return

        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 ) #[inamura 160616]
        fld = mm.ListToDoubleVector( foldings ) #[inamura 160616]
        for Axtype in type_axes:
            def_axes.append(Axtype)
        
        # open dialog
        dlg = None
        if (isText):
            dlg = wx.FileDialog(self.frame, 'Choose Dump Text output file ...', os.getcwd(),
                                style=wx.SAVE, wildcard='TEXT(*.txt)|*.txt')
        else:
            dlg = wx.FileDialog(self.frame, 'Choose Dump Binary output file ...', os.getcwd(),
                                style=wx.SAVE, wildcard='BIN(*.bin)|*.bin')
        
        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return
        
        btn_status = []
        for abtn in self.ButtonCtrlList:
            btn_status.append( abtn.IsEnabled() )
            abtn.Disable()
        self.SliceButtonCtrlList[0].Disable() ##[inamura 170228]
        self.SliceButtonCtrlList[1].Disable() ##[inamura 170228]

        #filepath = str( dlg.GetPath() )
        filepath = str( dlg.GetFilename() )
        self.StatusTextCtrl.SetLabel( "Dumping To save file %s" % (filepath ) )
        self.frame.Refresh()
        self.frame.Update()
        
        self.D4Mat.D4Mat.DumpD4MatToFile(a1v, a2v, a3v, a4v, def_axes, fld, str(filepath), isText )
        self.StatusTextCtrl.SetLabel( "Ready" )
        
        for astatus,abtn in zip(btn_status,self.ButtonCtrlList):
            abtn.Enable(astatus)
        self.CheckEnableSliceButton() #[inamura 170228]
        
        self.frame.Update()
        msg = "Finished Save 4D data to file file : "+filepath
        dial = wx.MessageDialog(None, msg, "Message", wx.OK | wx.ICON_INFORMATION )
        dial.ShowModal()


        
    #################################
    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.isEnableSlice=False       #[inamura 170228]
        self.CheckEnableSliceButton() #[inamura 170228]
        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
        self.type_axes=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, type_axes):
        """
        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) 
            self.type_axes=type_axes[:] ##[inamura 160823]
        else:
            # データ変更
            if self.type_axes==None or self.type_axes!=type_axes:
                self.ifi.NotifyEvent(self, "changedata", map)
                self.type_axes=type_axes[:]
            else:
                self.ifi.NotifyEvent(self, "updatedata", map) 
                self.type_axes=type_axes[:] ##[inamura 160823]

        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" )
    splash_path = os.path.join( os.environ["UTSUSEMI_BASE_DIR"],"ana","Reduction","LOGO_utsusemi_3_c_short.png" )
    if os.path.exists(splash_path):
        splash = UtsusemiSplashScreen(splash_path)
        splash.Show()
    
    frame = D4MatSlicer(None)
    app.MainLoop()
