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

from __future__ import print_function
import os
import sys

import utsusemi.ana.Reduction.D4MatQ_Manyo as D4Mat
import threading
import time
import Manyo.Utsusemi as mu
import Manyo
import uGao.M2PlotPlus as D2Vis
import uGao.uGaoUtil as UtilQt
import uGao.MPlot as mp
import Cmm

PYSIDEVER = 1
try:
    from PySide6 import QtCore, QtGui, QtWidgets
    from PySide6.QtGui import QAction
    PYSIDEVER = 6
except:
    try:
        from PySide2 import QtCore, QtGui, QtWidgets
        from PySide2.QtWidgets import QAction
        PYSIDEVER = 2
    except:
        from PySide import QtCore, QtGui
        import PySide.QtGui as QtWidgets
        from PySide.QtGui import QAction

if mu.UtsusemiEnvGetDebugMode():
    mu.UtsusemiMessage("D4MatSlicer PySide Ver={}".format(PYSIDEVER))

if QtCore.__version__ < '5.0.0':
    from utsusemi.vis.ui_D4matSlicerQ import Ui_D4matSlicerQtMain, Ui_D4matSlicerQtSub, Ui_NewD4MatrixFrame, Ui_D4matSlicerQRebin, Ui_DgSaveAsText
else:
    if PYSIDEVER == 2:
        from utsusemi.vis.ui2_D4matSlicerQ import Ui_D4matSlicerQtMain, Ui_D4matSlicerQtSub, Ui_NewD4MatrixFrame, Ui_D4matSlicerQRebin, Ui_DgSaveAsText
    elif PYSIDEVER == 6:
        from utsusemi.vis.ui6_D4matSlicerQ import Ui_D4matSlicerQtMain, Ui_D4matSlicerQtSub, Ui_NewD4MatrixFrame, Ui_D4matSlicerQRebin, Ui_DgSaveAsText


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

###################################
# Make New Matrix Window
###################################


class MakeNewMatrixFrame(QtWidgets.QMainWindow):
    def __init__(self, parent):
        """
        """
        super(MakeNewMatrixFrame, self).__init__(parent)

        self.parent = parent

        self.frame = Ui_NewD4MatrixFrame()
        if self.frame is None:
            return
        self.frame.setupUi(self)

        # button
        self.btLoadParams = self.findChild(
            QtWidgets.QPushButton, u"btLoadParams")
        self.btMakeNewMatrix = self.findChild(
            QtWidgets.QPushButton, u"btMakeNewMatrix")
        self.btClose = self.findChild(QtWidgets.QPushButton, u"btClose")
        self.btLoadParams.clicked.connect(self.OnLoadParams)
        self.btMakeNewMatrix.clicked.connect(self.OnMakeNewMatrix)
        self.btClose.clicked.connect(self.OnClose)

        self.D4MatRangeCtrl = []
        self.D4MatTitle = []
        self.D4MatUnit = []
        for i in range(12):
            self.D4MatRangeCtrl.append(self.findChild(
                QtWidgets.QLineEdit, "dtxt%d" % (i + 1)))

        for i in range(4):
            self.D4MatTitle.append(self.findChild(
                QtWidgets.QLineEdit, "v%dtitle" % (i + 1)))
            self.D4MatUnit.append(self.findChild(
                QtWidgets.QLineEdit, "v%dunit" % (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.resize(QtGui.QSize(460, 200))
        if sys.platform == "win32":
            self.resize(QtGui.QSize(444, 220))

        # show window
        self.show()

    #################################
    def OnLoadParams(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnLoadParams")
        # open dialog
        filepath, filt = QtWidgets.QFileDialog().getOpenFileName(
            self, u"Open VisCont Parameter file ...", os.getcwd(), filter="XML (*.xml)")

        filepath = str(filepath)
        if filepath == "":
            return

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

        return

    #################################
    def OnMakeNewMatrix(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnMakeNewMatrix")

        # open directory dialog
        filepath, filt = QtWidgets.QFileDialog().getSaveFileName(self, u"Choose File to save D4Matrix parameters ...",
                                                                 os.getcwd(), filter=u"XML (*.xml)", selectedFilter=u"D4Mat.xml")

        if filepath == "":
            return

        ax_list = []
        title_list = []
        unit_list = []
        for ax in range(4):
            ra = []
            for i in range(3):
                ra.append(float(self.D4MatRangeCtrl[ax * 3 + i].text()))
            ax_list.append(ra)
            title_list.append(self.D4MatTitle[ax].text())
            unit_list.append(self.D4MatUnit[ax].text())

        pre_label = self.parent.StatusTextCtrl.text()
        self.parent.StatusTextCtrl.setText(u"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, unit_list, str(filepath))
        # self.parent.D4Mat.D4Mat._MakeNewParamXml( str(filepath)+".xml" ) ##[inamura 110411]
        for ax in ax_list:
            mu.UtsusemiMessage(self.CommentHead + " {}".format(ax))

        self.parent.D4Mat.close()
        flag, msg = self.parent._OpenD4Matrix(str(filepath))
        if not flag:
            ret = QtWidgets.QMessageBox().information(
                self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return

        self.parent.StatusTextCtrl.setText(pre_label)

        ret = QtWidgets.QMessageBox().information(self, u"Message",
                                                  "Making New D4Matrix files completed.", QtWidgets.QMessageBox.Ok)
        # ret = dlg.ShowModal()

        return

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


###################################
# Rebin Matrix Window
###################################
class RebinMatrixFrame(QtWidgets.QMainWindow):
    def __init__(self, parent):
        """
        """
        super(RebinMatrixFrame, self).__init__(parent)

        self.parent = parent

        self.frame = Ui_D4matSlicerQRebin()
        if self.frame is None:
            return
        self.frame.setupUi(self)

        if not self.parent.D4Mat.isOpened():
            ret = QtWidgets.QMessageBox().critical(self, u"Warning",
                                                   u"You need to open D4Matrix at first!!", QtWidgets.QMessageBox.Ok)
            return

        # button
        self.btRebinMatrix = self.findChild(
            QtWidgets.QPushButton, u"btRebinMatrix")
        self.btRebinMatrix.clicked.connect(self.OnRebinMatrix)
        self.btClose = self.findChild(QtWidgets.QPushButton, u"btClose")
        self.btClose.clicked.connect(self.OnClose)

        self.D4MatRangeCtrl = []
        self.D4MatTitle = []
        self.RebinRatio = []
        for i in range(12):
            self.D4MatRangeCtrl.append(self.findChild(
                QtWidgets.QLabel, u"txt%d" % (i + 1)))

        for i in range(4):
            self.RebinRatio.append(self.findChild(
                QtWidgets.QSpinBox, u"spn%dStepRatio" % (i + 1)))
            self.D4MatTitle.append(self.findChild(
                QtWidgets.QLineEdit, u"v%dtitle" % (i + 1)))

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

        for i in range(4):
            self.D4MatRangeCtrl[i * 3 + 0].setText(self.parent.D4MatRangeCtrl[i * 3 + 0].text())
            self.D4MatRangeCtrl[i * 3 + 1].setText(self.parent.D4MatRangeCtrl[i * 3 + 1].text())
            self.D4MatRangeCtrl[i * 3 + 2].setText(self.parent.D4MatRangeCtrl[i * 3 + 2].text())
            self.D4MatTitle[i].setText(self.parent.D4MatTitle[i].text())

        self.D4MatUnit = []
        for i in range(4):
            self.D4MatUnit.append(self.parent.D4MatTitle[i].text())

        self.CommentHead = "D4MatGUI::RebinMatrix >>> "

        # Justify the alignment of controls on OSX and Windows
        if sys.platform == "darwin":
            # self.frame.SetSizeWH( 510,220 )
            self.resize(QtCore.QSize(510, 220))
        if sys.platform == "win32":
            # self.frame.SetSizeWH( 510,220 )
            self.resize(QtCore.QSize(510, 220))

        # show window
        self.show()

    #################################
    def OnRebinMatrix(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnRebinMatrix")

        # open directory dialog
        filepath2, filt = QtWidgets.QFileDialog().getSaveFileName(self, u"Choose File to save D4Matrix parameters ...",
                                                                  os.getcwd(), filter=u"XML (*.xml)", selectedFilter=u"D4Mat.xml")

        if filepath2 == "":
            return

        # 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].text()))
            ratio_list.append(float(self.RebinRatio[ax].text()))
            mu.UtsusemiMessage(self.CommentHead + "Ratio=" + str(ratio_list[-1]))
            ra[2] = ra[2] * ratio_list[-1]
            ax_list.append(ra)
            title_list.append(self.D4MatTitle[ax].text())

        for ax in ax_list:
            mu.UtsusemiMessage(self.CommentHead + " {}".format(ax))

        pre_label = self.parent.StatusTextCtrl.text()
        self.parent.StatusTextCtrl.setText("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, self.D4MatUnit, str(filepath2))
        self.parent.D4Mat.close()

        self.parent.StatusTextCtrl.setText("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:
            ret = QtWidgets.QMessageBox().critical(
                self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return

        self.parent.StatusTextCtrl.setText(pre_label)

        ret = QtWidgets.QMessageBox().information(
            self, u"Info", u"Rebinning D4Matrix completed.", QtWidgets.QMessageBox.Ok)

        return

    ##########################################################

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

# [inamura 160523]-->
#########################################
#       SetSaveAsTextDialog
#########################################


class SetSaveAsTextDialog(QtWidgets.QDialog):
    """
    SaveAsText 設定ダイアログクラス
    """
    ##########################################################

    def __init__(self, parent, frame):
        """
        コンストラクタ
        @param  parent   親ウィンドウ
        @param  dataobj
        @retval 無し
        """
        super(SetSaveAsTextDialog, self).__init__(parent)
        self.dialog = Ui_DgSaveAsText()
        if self.dialog is None:
            return
        self.dialog.setupUi(self)

        self.parent = parent
        # self.frame = frame

        # リソース取得

        # チェックボックス
        self.ckIgnoreMask = self.findChild(
            QtWidgets.QCheckBox, u'ckIgnoreMask')

        # チェックボックスのイベントハンドラ登録
        self.ckIgnoreMask.stateChanged.connect(self.OnIgnoreMask)

        # コンボボックス
        self.chMaskVal = self.findChild(QtWidgets.QComboBox, u'chMaskValue')

        # コンボボックスのイベントハンドラ登録
        self.chMaskVal.activated.connect(self.OnMaskVal)

        # テキストボックスのコントローラ取得
        self.txMaskVal = self.findChild(QtWidgets.QLineEdit, u'txMaskValue')

        # ボタンのイベントハンドラを登録
        self.btnSave = self.findChild(QtWidgets.QPushButton, u"btSave")
        self.btnCancel = self.findChild(QtWidgets.QPushButton, u"btCancel")
        self.btnSave.clicked.connect(self.OnSave)
        self.btnCancel.clicked.connect(self.OnCancel)

        # [X]ボタン押下時のイベントハンドラ登録
        # self.dialog.Bind(wx.EVT_CLOSE, self.OnCancel)

        # Set Values
        self.initialize()

        # ダイアログ表示
        self.show()

    ##########################################################
    def initialize(self):
        """
        """
        self.isIgnoreMask = True
        self.useGivenMaskVal = True
        self.ckIgnoreMask.setCheckState(QtCore.Qt.Checked)  # True
        self.chMaskVal.setEnabled(False)
        self.txMaskVal.setEnabled(False)

        return

    ##########################################################
    def OnIgnoreMask(self, event=None):
        """
        IgnoreMask チェックボックスイベント処理
        @param   event イベント情報
        @retval 無し
        """
        # チェックされたのか
        if self.ckIgnoreMask.checkState() == QtCore.Qt.Checked:
            self.isIgnoreMask = True
        else:
            self.isIgnoreMask = False
        if self.isIgnoreMask:
            # MaskValue テキストボックスを選択不可
            self.chMaskVal.setEnabled(False)
            self.txMaskVal.setEnabled(False)
        else:
            self.chMaskVal.setEnabled(True)
            self.txMaskVal.setEnabled(False)
            index = self.chMaskVal.currentIndex()
            if index == 0:
                self.txMaskVal.setEnabled(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.text())
            except:
                msg = "Given Mask Value is invalid (%s)" % (
                    self.txMaskVal.text())
                but = QtWidgets.QMessageBox().warning(
                    self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
                self._CtrlParts(True)
                return

        maskValStr = "MASKVAL"
        if (self.useGivenMaskVal):
            maskValStr = self.txMaskVal.text()

        # open dialog
        filepath, filt = QtWidgets.QFileDialog().getSaveFileName(
            self, u"Choose 3D text output file ...", os.getcwd(), filter="Text Files (*.txt)")

        # cancel?
        if filepath == "":
            return

        self.parent.StatusTextCtrl.setText("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].currentIdnex()
            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].text()))
            # <--[inamura 160616]
            ar = []
            ar.append(float(self.parent.SliceRange[i * 3].text()))
            ar.append(float(self.parent.SliceRange[i * 3 + 1].text()))
            Axr.append(ar)

        a1v = Manyo.ListToDoubleVector(Axr[0])
        a2v = Manyo.ListToDoubleVector(Axr[1])
        a3v = Manyo.ListToDoubleVector(Axr[2])
        a4v = Manyo.ListToDoubleVector(Axr[3])
        def_axes = Manyo.MakeStringVector()
        # fld = Manyo.ListToInt4Vector( foldings )  ##[inamura 160616]
        fld = Manyo.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.setText("Ready")

        msg = "Finished Save 3D data to text file : " + filepath

        but = QtWidgets.QMessageBox().information(
            self, u"Message", msg, QtWidgets.QMessageBox.Ok)
        self._CtrlParts(True)
        self.OnCancel()

    ##########################################################
    def _CtrlParts(self, isEnable=True):
        """
        """
        if not isinstance(isEnable, bool):
            return

        if isEnable:
            self.btnSave.setEnabled(True)
            self.btnCancel.setEnabled(True)
            self.ckIgnoreMask.setEnabled(True)
            if self.isIgnoreMask:
                self.chMaskVal.setEnabled(False)
                self.txMaskVal.setEnabled(False)
            else:
                self.chMaskVal.setEnabled(True)
                self.txMaskVal.setEnabled(False)
                index = self.chMaskVal.currentIndex()
                self.useGivenMaskVal = True
                if index == 0:
                    self.txMaskVal.setEnabled(True)
                    pass
                elif index == 1:
                    self.txMaskVal.setText(str(0.0))
                elif index == 2:
                    self.txMaskVal.setText(str(-1.0))
                else:
                    self.useGivenMaskVal = False
                    self.txMaskVal.setText("")
        else:
            self.ckIgnoreMask.setEnabled(False)
            self.chMaskVal.setEnabled(False)
            self.txMaskVal.setEnabled(False)
            self.btnSave.setEnabled(False)
            self.btnCancel.setEnabled(False)

    ##########################################################

    def OnCancel(self, evt=None):
        """
        Cancel ボタンイベント処理
        @param  evt イベント情報
        @retval 無し
        """

        self.close()

# [inamrua 160621]-->
###################################
# Make Virtual Matrix Window
###################################


class MakeVirtualD4MatrixFrame(QtWidgets.QMainWindow):
    def __init__(self, parent):
        """
        """
        super(MakeVirtualD4MatrixFrame, self).__init__(parent)
        self.parent = parent

        self.frame = Ui_D4matSlicerQtSub()
        if self.frame is None:
            return
        self.frame.setupUi(self)

        # button
        btLoadParams = self.findChild(QtWidgets.QPushButton, u"btLoadParams")
        btSaveParams = self.findChild(QtWidgets.QPushButton, u"btSaveParams")
        btFillRange = self.findChild(QtWidgets.QPushButton, u"btFillRange")
        btMakeVirtualMatrix = self.findChild(
            QtWidgets.QPushButton, u"btMakeVirtualMatrix")
        btClr = self.findChild(QtWidgets.QPushButton, u"btClr")
        btMakeNewD4Mat = self.findChild(
            QtWidgets.QPushButton, u"btMakeNewD4Mat")
        btEstimateD4MatSize = self.findChild(
            QtWidgets.QPushButton, u"btEstimateD4MatSize")
        btClose = self.findChild(QtWidgets.QPushButton, u"btClose")

        btLoadParams.clicked.connect(self.OnLoadParams)
        btSaveParams.clicked.connect(self.OnSaveParams)
        btFillRange.clicked.connect(self.OnFillRangeVirtualMatrix)
        btMakeVirtualMatrix.clicked.connect(self.OnMakeVirtualMatrix)
        btClr.clicked.connect(self.OnClear)
        btMakeNewD4Mat.clicked.connect(self.OnMakeNewD4Mat)
        btEstimateD4MatSize.clicked.connect(self.OnEstimateSize)
        btClose.clicked.connect(self.OnClose)

        self.BtnCtrls = [btLoadParams, btSaveParams, btFillRange,
                         btMakeVirtualMatrix, btClr, btMakeNewD4Mat, btEstimateD4MatSize, btClose]

        # lineEditor
        list_LineEdit = ["txEi", "txminhw", "txmaxhw",
                         "txdeltahw", "txminphi", "txmaxphi", "txdeltaphi"]
        self.minfo = []
        for a_title in list_LineEdit:
            self.minfo.append(self.findChild(
                QtWidgets.QLineEdit, u"%s" % (a_title)))

        self.runnotxt = self.findChild(QtWidgets.QLineEdit, u"txrunno")

        # サンプル情報テキストボックスのコントロールを取得
        self.sinfo = []
        for i in range(15):
            ii = i + 1
            txt = u"txt%d" % ii
            self.sinfo.append(self.findChild(QtWidgets.QLineEdit, txt))

        self.chrotax1 = self.findChild(QtWidgets.QComboBox, "chRotateAxis1st")
        self.chrotax2 = self.findChild(QtWidgets.QComboBox, "chRotateAxis2nd")
        self.chrotax3 = self.findChild(QtWidgets.QComboBox, "chRotateAxis3rd")
        self.chrotax1.activated.connect(
            lambda: self.OnChoiceRotateAxes(self.chrotax1))
        self.chrotax2.activated.connect(
            lambda: self.OnChoiceRotateAxes(self.chrotax2))
        self.chrotax3.activated.connect(
            lambda: self.OnChoiceRotateAxes(self.chrotax3))
        self.chRotationSteps = [self.chrotax1, self.chrotax2, 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(self.findChild(QtWidgets.QLineEdit, txt))
            self.uv.append(uv0)

        self.D4MatTitle = []
        for i in range(4):
            self.D4MatTitle.append(self.findChild(
                QtWidgets.QLineEdit, "ptxt%d" % (i * 5 + 5)))
        self.D4MatUnit = []
        for i in range(4):
            self.D4MatUnit.append(self.findChild(
                QtWidgets.QLineEdit, "ptxt%d" % (21 + i)))

        self.D4MatRangeCtrl = []
        for i in range(12):
            self.D4MatRangeCtrl.append(self.findChild(
                QtWidgets.QLineEdit, "dtxt%d" % (i + 1)))

        self.InitializeValues()

        # self.frame.Bind(wx.EVT_CLOSE, self.OnClose)
        self.CommentHead = "D4MatGUI::MakeVirtualMat >>> "

        # Ei or Ef label
        self.labelEiEf = self.findChild(QtWidgets.QLabel, u"label")
        if self.parent.D4Mat.D4Mat.isDirectGeometry():
            self.labelEiEf.setText("Ei (meV) :")
        else:
            self.labelEiEf.setText("Ef (meV) :")
            self.minfo[0].setText("{}".format(self.parent.D4Mat.D4Mat.PutEf()))

        menu_Load_XtalParams = self.findChild(
            QAction, u"actionLoad_XtalParams")
        menu_Save_XtalParams = self.findChild(
            QAction, u"actionSave_XtalParams")
        menu_Exit = self.findChild(QAction, u"actionExit")
        menu_Load_XtalParams.triggered.connect(self.OnLoadParams)
        menu_Save_XtalParams.triggered.connect(self.OnSaveParams)
        menu_Exit.triggered.connect(self.OnClose)

        # Justify the alignment of controls on OSX and Windows
        if sys.platform == "darwin":
            self.resize(QtCore.QSize(550, 750))
        if sys.platform == "win32":
            self.resize(QtCore.QSize(550, 740))

        # show window
        self.show()

    #################################
    def InitializeValues(self):
        """
        Initialize values and status of lineEdit and combobox
        """
        self.sinfo[0].setText("1.0")
        self.sinfo[1].setText("1.0")
        self.sinfo[2].setText("1.0")
        self.sinfo[3].setText("90.0")
        self.sinfo[4].setText("90.0")
        self.sinfo[5].setText("90.0")
        self.sinfo[6].setText("0.0")
        self.sinfo[7].setText("1.0")
        self.sinfo[8].setText("0.0")
        self.sinfo[9].setText("0.0")
        self.sinfo[10].setText("0.0")
        self.sinfo[11].setText("1.0")

        self.chRotationSteps[0].setEnabled(True)
        self.chRotationSteps[1].setEnabled(False)
        self.chRotationSteps[2].setEnabled(False)
        self.sinfo[12].setEnabled(False)
        self.sinfo[13].setEnabled(False)
        self.sinfo[14].setEnabled(False)

        for id in range(4):
            for col in range(4):
                self.uv[id][col].setText(u"0")
                if id == col:
                    self.uv[id][col].setText(u"1")
        self.uv[0][4].setText("Qa")
        self.uv[1][4].setText("Qb")
        self.uv[2][4].setText("Qc")
        self.uv[3][4].setText("Energy")
        self.D4MatUnit[0].setText("rlu")
        self.D4MatUnit[1].setText("rlu")
        self.D4MatUnit[2].setText("rlu")
        self.D4MatUnit[3].setText("meV")
        for id in range(3):
            self.uv[id][3].setEnabled(False)
        for col in range(3):
            self.uv[3][col].setEnabled(False)

        for i in range(7):
            self.minfo[i].setText("0.0")

        self.runnotxt.setText("999999")

        for i in range(4):
            self.D4MatRangeCtrl[i * 3 + 0].setText("-1.0")
            self.D4MatRangeCtrl[i * 3 + 1].setText("1.0")
            self.D4MatRangeCtrl[i * 3 + 2].setText("0.05")

    #################################
    def OnLoadParams(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnLoadParams")

        # open dialog
        fullpath, filt = QtWidgets.QFileDialog().getOpenFileName(
            self, u'Open VisCont Parameter file ...', os.getcwd(), filter="XML (*.xml)")

        # cancel?
        if fullpath == "":
            return

        # get file path
        filepath = str(fullpath)

        if not os.path.exists(filepath):
            msg = " Cannot find XML file(%s)" % (filepath)
            mu.UtsusemiWarning(self.CommentHead + "::OnLoadParams >>" + msg)
            but = QtWidgets.QMessageBox().warning(
                self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return

        # make instance and load file and analysis XML parameter
        vcp = mu.UtsusemiSqeCalcXtalParams()
        if vcp.LoadFile(filepath):
            pass
        else:
            msg = " This file is NOT XtalParam file ({})".format(filepath)
            mu.UtsusemiWarning(self.CommentHead + "::OnLoadParams >>" + msg)
            but = QtWidgets.QMessageBox().warning(
                self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return
        lc = vcp.PutLatticeConsts()
        uv = vcp.PutUVector()
        vv = vcp.PutVVector()
        rv = vcp.PutRotateSteps()
        ro_list = []
        if rv.size() != 0:
            for i in range(int(rv.size() / 2)):
                ax_dic = {0: "X", 1: "Y", 2: "Z"}
                ax_id = int(rv[2 * i])   # axis 0="X", 1="Y", 2="Y"
                ax_val = rv[2 * i + 1]
                ro_list.append((ax_dic[ax_id], ax_val))

        self.sinfo[0].setText("%6.4f" % lc[0])
        self.sinfo[1].setText("%6.4f" % lc[1])
        self.sinfo[2].setText("%6.4f" % lc[2])
        self.sinfo[3].setText("%6.4f" % lc[3])
        self.sinfo[4].setText("%6.4f" % lc[4])
        self.sinfo[5].setText("%6.4f" % lc[5])
        self.sinfo[6].setText("%6.4f" % uv[0])
        self.sinfo[7].setText("%6.4f" % uv[1])
        self.sinfo[8].setText("%6.4f" % uv[2])
        self.sinfo[9].setText("%6.4f" % vv[0])
        self.sinfo[10].setText("%6.4f" % vv[1])
        self.sinfo[11].setText("%6.4f" % vv[2])

        ro_axis_dic = {"Y": 1, "Z": 2, "X": 3}
        self.chRotationSteps[0].setEnabled(True)
        self.chRotationSteps[1].setEnabled(False)
        self.chRotationSteps[2].setEnabled(False)
        self.sinfo[12].setEnabled(False)
        self.sinfo[13].setEnabled(False)
        self.sinfo[14].setEnabled(False)
        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].setEnabled(True)
            self.chRotationSteps[i].setCurrentIndex(ax_num)
            self.sinfo[12 + i].setText(u"%6.4f" % float(a_rot[1]))
            self.sinfo[12 + i].setEnabled(True)
            if (i + 1) < len(self.chRotationSteps):
                self.chRotationSteps[i + 1].setEnabled(True)

        # Projection infor
        proj_axes = vcp.PutViewAxes()
        proj_labels = vcp.PutViewAxesLabels()
        proj_units = vcp.PutViewAxesUnits()
        for id in range(4):
            for col in range(4):
                self.uv[id][col].setText(u"%g" % (proj_axes[4 * id + col]))
            self.uv[id][4].setText(proj_labels[id])

        # D4Matrix range
        for id in range(4):
            range_axis = vcp.PutAxRange(id, False)
            self.D4MatRangeCtrl[3 * id + 0].setText("%g" % (range_axis[0]))
            self.D4MatRangeCtrl[3 * id + 1].setText("%g" % (range_axis[1]))
            self.D4MatRangeCtrl[3 * id + 2].setText("%g" % (range_axis[2]))
            self.D4MatTitle[id].setText(proj_labels[id])
            self.D4MatUnit[id].setText(proj_units[id])

        del vcp
        return

    #################################
    def OnSaveParams(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnSaveParams")

        sample = []
        for i in range(15):
            anum = self.sinfo[i].text().strip()
            if anum == "":
                anum = "0"
            try:
                num = float(anum)
            except:
                raise UtilQt.PlotException('Common', 'C027', ("Sample Info",))
            sample.append(num)

        # make instance
        vcp = mu.UtsusemiSqeCalcXtalParams()
        vcp.SetLatticeConstants(sample[:6])
        vcp.SetUVvector(sample[6:9], sample[9:12])

        rotationSteps = []
        for i, rax in zip([0, 1, 2], self.chRotationSteps):
            if rax.isEnabled():
                ax_num = rax.currentIndex()
                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

        for a_step in rotationSteps:
            vcp.AddRotationStep(a_step[0], float(a_step[1]))

        # 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].text()))
            a_list.append(self.uv[id][4].text())
            a_list.append(self.D4MatUnit[id].text())
            axisInfo.append(a_list)
        vcp.SetProjectionAxes(
            axisInfo[0], axisInfo[1], axisInfo[2], axisInfo[3])

        # 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].text()))
            a_list.append(fold_list[id])
            sliceInfo.append(a_list)

        for i in range(4):
            vcp.SetSliceAxis("%1d" % (
                i), type_list[i], sliceInfo[i][1], sliceInfo[i][2], sliceInfo[i][3], fold_list[i])

        # open dialog
        filepath, filt = QtWidgets.QFileDialog().getSaveFileName(
            self, u"Save Parameter File  ...", os.getcwd(), filter="XML (*.xml)")

        # if cancel?
        if filepath == "":
            return

        # get file path
        savefile = str(filepath)

        # save to XML file
        vcp.SaveFile(savefile)
        del vcp

    #################################
    def OnFillRangeVirtualMatrix(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnFillRangeVirtualMatrix")
        runNo = int(self.runnotxt.text())
        Ei = float(self.minfo[0].text())
        minhw = float(self.minfo[1].text())
        maxhw = float(self.minfo[2].text())
        deltahw = float(self.minfo[3].text())
        minPhi = float(self.minfo[4].text())
        maxPhi = float(self.minfo[5].text())
        delPhi = float(self.minfo[6].text())
        if delPhi == 0.0:
            delPhi = 1.0
            self.minfo[6].setText(str(delPhi))

        if self.parent.D4Mat.D4Mat.isDirectGeometry():
            if deltahw <= 0.0 or minhw > maxhw or maxhw >= Ei:
                msg = "Energy Arguments are invalid."
                but = QtWidgets.QMessageBox().warning(
                    self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
                return
            UGH = mu.UtsusemiGetNeunetHistogram()
            if UGH.SetRunNo(str(runNo)):
                pass
            else:
                raise UserWarning("runNo is invalid")
            UGH.SetDetParam("psd")

            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.")
        else:
            DAT = None
            if mu.UtsusemiEnvGetInstCode() == "DNA":
                hw_param = "{}/{}/{}".format(deltahw, minhw, maxhw)
                lambda_param = "6.321/4.15"
                DAT = Cmm.GetHistogramHW(runNo=0, HwParam=hw_param, LambdaParam=lambda_param, t0_offset=12325.0,
                                         useT0ModCorr=False, TimeParam="-1.0/-1.0", UseFastChopper=True, tofOffsetFile="nofile", isHistogram=False)
                # Cmm.DoMask(DAT,"maskTY.txt")

        btn_status = []
        for abtn in self.BtnCtrls:
            btn_status.append(abtn.isEnabled())
            abtn.setEnabled(False)
        # self.frame.Update()

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

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

        rotSteps = Manyo.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].currentIndex() == 1:   # if Y-axis
                    axis_num = 1.0                             # 1 means Y-axis in VisualCalcSqe
                elif self.chRotationSteps[i].currentIndex() == 2:  # if Z-axis
                    axis_num = 2.0                             # 2 means Z-axis in VisualCalcSqe
                elif self.chRotationSteps[i].currentIndex() == 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].text()))   # angle
            else:
                break

        va = Manyo.MakeDoubleVector(16)
        titles = Manyo.MakeStringVector(4)
        for id in range(4):
            for col in range(4):
                va[id * 4 + col] = float(self.uv[id][col].text())
            # print("id={}".format(id,self.uv[id][4].text()))
            titles[id] = str(self.uv[id][4].text())

        hw_info = Manyo.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 = Manyo.MakeDoubleVector()
        phi = minPhi
        while(phi <= maxPhi):
            phi_steps.push_back(phi)
            phi += delPhi

        stime = time.time()
        if self.parent.D4Mat.D4Mat.isDirectGeometry():
            self.parent.D4Mat.D4Mat._CalcVirtualAngleInfo(pfiles[0], pfiles[1])
        elif DAT is not None:
            self.parent.D4Mat.D4Mat._CalcVirtualAngleInfo(DAT)
        else:
            msg = "D4MatSlicer::OnFillRangeVirtualMatrix >>> DAT of DNA is None"
            raise UserWarning(msg)

        est_ranges = self.parent.D4Mat.D4Mat.EstimateRangeOfVirtualMat(
            lc, uv, vv, rotSteps, va, hw_info, phi_steps)
        mu.UtsusemiMessage(
            "  Allocation is finish : cost = {}".format(time.time() - stime))

        for i in range(4):
            self.D4MatRangeCtrl[i * 3].setText("%g" % (est_ranges[i * 2]))
            self.D4MatRangeCtrl[i * 3 + 1].setText("%g" % (est_ranges[i * 2 + 1]))
        self.D4MatRangeCtrl[11].setText("%g" % (deltahw))

        self.parent.FileListBox.clear()

        for btn_ctrl in self.parent.ButtonCtrlList:
            btn_ctrl.setEnabled(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].setEnabled(False)

        for astatus, abtn in zip(btn_status, self.BtnCtrls):
            abtn.setEnabled(astatus)
        # self.frame.Update()

        return

    #################################
    def OnMakeVirtualMatrix(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnMakeVirtualMatrix")
        runNo = int(self.runnotxt.text())
        Ei = float(self.minfo[0].text())
        minhw = float(self.minfo[1].text())
        maxhw = float(self.minfo[2].text())
        deltahw = float(self.minfo[3].text())
        minPhi = float(self.minfo[4].text())
        maxPhi = float(self.minfo[5].text())
        delPhi = float(self.minfo[6].text())
        if delPhi == 0.0:
            delPhi = 1.0
            self.minfo[6].setText(str(delPhi))

        if self.parent.D4Mat.D4Mat.isDirectGeometry():
            if deltahw <= 0.0 or minhw > maxhw or maxhw >= Ei:
                msg = "Energy Arguments are invalid."
                but = QtWidgets.QMessageBox().warning(
                    self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
                return
            UGH = mu.UtsusemiGetNeunetHistogram()
            if UGH.SetRunNo(str(runNo)):
                pass
            else:
                raise UserWarning("runNo is invalid")
            UGH.SetDetParam("psd")

            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.")
        else:
            DAT = None
            if mu.UtsusemiEnvGetInstCode() == "DNA":
                hw_param = "{}/{}/{}".format(deltahw, minhw, maxhw)
                lambda_param = "6.321/4.15"
                DAT = Cmm.GetHistogramHW(runNo=0, HwParam=hw_param, LambdaParam=lambda_param, t0_offset=12325.0,
                                         useT0ModCorr=False, TimeParam="-1.0/-1.0", UseFastChopper=True, tofOffsetFile="nofile", isHistogram=False)

        btn_status = []
        for abtn in self.BtnCtrls:
            btn_status.append(abtn.isEnabled())
            abtn.setEnabled(False)
        # self.frame.Update()

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

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

        rotSteps = Manyo.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].currentIndex() == 1:   # if Y-axis
                    axis_num = 1.0                             # 1 means Y-axis in VisualCalcSqe
                elif self.chRotationSteps[i].currentIndex() == 2:  # if Z-axis
                    axis_num = 2.0                             # 2 means Z-axis in VisualCalcSqe
                elif self.chRotationSteps[i].currentIndex() == 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].text()))   # angle
            else:
                break

        va = Manyo.MakeDoubleVector(16)
        titles = Manyo.MakeStringVector(4)
        units = Manyo.MakeStringVector(4)
        for id in range(4):
            for col in range(4):
                va[id * 4 + col] = float(self.uv[id][col].text())
            # print("id= {}".format(id,self.uv[id][4].text()))
            titles[id] = str(self.uv[id][4].text())
            units[id] = str(self.D4MatUnit[id].text())

        hw_info = Manyo.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 = Manyo.MakeDoubleVector()
        phi = minPhi
        while(phi < maxPhi):
            phi_steps.push_back(phi)
            phi += delPhi

        ranges = []
        for id in range(4):
            tmp = Manyo.MakeDoubleVector(3)
            tmp[0] = float(self.D4MatRangeCtrl[3 * id + 0].text())
            tmp[1] = float(self.D4MatRangeCtrl[3 * id + 1].text())
            tmp[2] = float(self.D4MatRangeCtrl[3 * id + 2].text())
            ranges.append(tmp)

        # print("---------------------------------------")
        # print("wfile, dfile= {}, {}".format(pfiles[0], pfiles[1]))
        # print("lc = {}, {}, {}, {}, {}, {}".format(lc[0],lc[1],lc[2],lc[3],lc[4],lc[5]))
        # print("uv = {}, {}, {}".format(uv[0],uv[1],uv[2]))
        # print("vv = {}, {}, {}".format(vv[0],vv[1],vv[2]))

        stime = time.time()
        if self.parent.D4Mat.D4Mat.isDirectGeometry():
            self.parent.D4Mat.D4Mat._CalcVirtualAngleInfo(pfiles[0], pfiles[1])
        elif DAT is not None:
            self.parent.D4Mat.D4Mat._CalcVirtualAngleInfo(DAT)
        else:
            msg = "D4MatSlicer::OnMakeVirtualMatrix >>> DAT of DNA is None"
            raise UserWarning(msg)

        self.parent.D4Mat.D4Mat.AllocateVirtualMat(
            lc, uv, vv, rotSteps, va, hw_info, phi_steps, ranges[0], ranges[1], ranges[2], ranges[3], titles, units)
        mu.UtsusemiMessage(
            self.CommentHead + "  Allocation is finish : cost = {}".format(time.time() - stime))

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

        self.parent.FileListBox.clear()

        for btn_ctrl in self.parent.ButtonCtrlList:
            btn_ctrl.setEnabled(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].setEnabled(False)

        ret = QtWidgets.QMessageBox().information(
            self, u"Message", "Making Virtual D4Matrix completed.", QtWidgets.QMessageBox.Ok)

        self.parent.D4MatrixFilePathCtrl.setText("VIRTUAL D4Matrix Mode")
        self.parent.VirtualD4MatTextCtrl.setText("VIRTUAL ( Ei=%g hw=[%g:%g:%g], Angle=[%g:%g:%g] )" % (
            Ei, minhw, maxhw, deltahw, minPhi, maxPhi, delPhi))
        self.parent.FileListBox.clear()
        new_line = QtWidgets.QTreeWidgetItem()
        new_line.setText(0, "Virtual Mode")
        self.parent.FileListBox.addTopLevelItem(new_line)
        self.parent.OnAutoFill(None)

        for astatus, abtn in zip(btn_status, self.BtnCtrls):
            abtn.setEnabled(astatus)
        # self.frame.Update()

        return

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

        elif bt == self.chrotax2:
            if self.chrotax1.currentIndex() == 0:
                self.sinfo[13].setEnabled(False)
                self.chrotax3.setEnabled(True)
                self.sinfo[14].setEnabled(False)
            else:
                if bt.currentIndex() == 0:
                    self.sinfo[13].setEnabled(False)
                    self.chrotax3.setEnabled(False)
                    self.sinfo[14].setEnabled(False)
                else:
                    self.chrotax3.setEnabled(True)
                    self.sinfo[13].setEnabled(True)
                    if self.chrotax3.currentIndex() == 0:
                        self.sinfo[14].setEnabled(False)
                    else:
                        self.sinfo[14].setEnabled(True)

        else:
            if (self.chrotax1.currentIndex() == 0) or (self.chrotax2.currentIndex() == 0) or (bt.currentIndex() == 0):
                self.sinfo[14].setEnabled(False)
            else:
                self.sinfo[14].setEnabled(True)

    ##########################################################

    def OnClear(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnClear")

    #################################
    def OnMakeNewD4Mat(self, evt=None):
        """
        """
        # open directory dialog
        fullpath, filt = QtWidgets.QFileDialog.getSaveFileName(
            self, "Choose File to save D4Matrix parameters ...", os.getcwd(), filter='XML (*.xml)')

        # cancel?
        if fullpath == "":
            return

        # get path
        filepath = fullpath
        dir = os.path.dirname(filepath)
        # print "filepath=",filepath
        # print "dir=",dir

        ax_list = []
        title_list = []
        unit_list = []
        for ax in range(4):
            ra = []
            for i in range(3):
                ra.append(float(self.D4MatRangeCtrl[ax * 3 + i].text()))
            ax_list.append(ra)
            title_list.append(self.D4MatTitle[ax].text())
            unit_list.append(self.D4MatUnit[ax].text())

        pre_label = self.parent.StatusTextCtrl.text()
        self.parent.StatusTextCtrl.setText("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.setEnabled(False)
        # self.frame.Update()

        self.parent.D4Mat.new(
            ax_list[0], ax_list[1], ax_list[2], ax_list[3], title_list, unit_list, str(filepath))
        # self.parent.D4Mat.D4Mat._MakeNewParamXml( str(filepath)+".xml" ) ##[inamura 110411]
        for ax in ax_list:
            mu.UtsusemiMessage(self.CommentHead + " {}".format(ax))

        self.parent.D4Mat.close()
        flag, msg = self.parent._OpenD4Matrix(str(filepath))
        if not flag:
            but = QtWidgets.QMessageBox().warning(
                self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return

        self.parent.StatusTextCtrl.setText(pre_label)

        for astatus, abtn in zip(btn_status, self.BtnCtrls):
            abtn.setEnabled(astatus)
        # self.frame.Update()

        dlg = QtWidgets.QMessageBox().information(self, u"Message",
                                                  "Making New D4Matrix files completed. Push OK to close this VirtualD4Mat Setting.", QtWidgets.QMessageBox.Ok)

        self.parent.VirtualD4MatTextCtrl.setText("No Info")
        self.OnClose(None)

    #################################
    def OnEstimateSize(self, evt=None):
        """
        """
        num_list = []
        for ax in range(4):
            ra = []
            for i in range(3):
                ra.append(float(self.D4MatRangeCtrl[ax * 3 + i].text()))
            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 = u"Estimated Size of D4Matrix data is %f MB" % size_MB
        dlg = QtWidgets.QMessageBox().information(
            self, u"Message", msg, QtWidgets.QMessageBox.Ok)
        return

    ##########################################################
    def OnClose(self, evt=None):
        """
        Close button event
        @param  evt event information
        @retval None
        """
        self.parent.StatusTextCtrl.setText("Done.")
        self.close()


# <--[inamrua 160621]
# <-[inamura 160523]
###################################
# Main Window to treat D4Mat
###################################
class D4MatSlicer(QtWidgets.QMainWindow):
    __version__ = 'v110411'

    def __init__(self, parent, Ef=0.0):
        """
        Constructor
        @param parent parent window id

        """

        # Make window and set Event handler
        super(D4MatSlicer, self).__init__(parent)
        self.frame = Ui_D4matSlicerQtMain()
        if self.frame is None:
            return
        self.frame.setupUi(self)

        # bind Button
        btOpenD4Matrix = self.findChild(
            QtWidgets.QPushButton, u"btOpenD4Matrix")
        btOpenD4Matrix.clicked.connect(self.OnOpenD4Matrix)
        btCloseMatrix = self.findChild(QtWidgets.QPushButton, u"btCloseMatrix")
        btCloseMatrix.clicked.connect(self.OnCloseD4Matrix)
        btMakeVirtualMat = self.findChild(
            QtWidgets.QPushButton, u"btMakeVirtualMat")
        btMakeVirtualMat.clicked.connect(self.OnMakeVirtualMat)
        btClearColumn = self.findChild(QtWidgets.QPushButton, u"btClearColumn")
        btClearColumn.clicked.connect(self.OnClearColumn)
        btSaveTitles = self.findChild(QtWidgets.QPushButton, u"btSaveTitles")
        btSaveTitles.clicked.connect(self.OnSaveTitles)
        btCloseMatrix = self.findChild(QtWidgets.QPushButton, u"btCloseMatrix")
        btCloseMatrix.clicked.connect(self.OnCloseD4Matrix)
        btAddSingleFile = self.findChild(
            QtWidgets.QPushButton, u"btAddSingleFile")
        btAddSingleFile.clicked.connect(self.OnAddSingleFile)
        btAddFilesInDir = self.findChild(
            QtWidgets.QPushButton, u"btAddFilesInDir")
        btAddFilesInDir.clicked.connect(self.OnAddFilesInDir)
        btRemoveFile = self.findChild(QtWidgets.QPushButton, u"btRemoveFile")
        btRemoveFile.clicked.connect(self.OnRemoveFile)
        btAutoFill = self.findChild(QtWidgets.QPushButton, u"btAutoFill")
        btAutoFill.clicked.connect(lambda: self.OnAutoFill("btAutoFill"))
        btAutoFillAx1 = self.findChild(QtWidgets.QPushButton, u"btAutoFillAx1")
        btAutoFillAx1.clicked.connect(lambda: self.OnAutoFill("btAutoFillAx1"))
        btAutoFillAx2 = self.findChild(QtWidgets.QPushButton, u"btAutoFillAx2")
        btAutoFillAx2.clicked.connect(lambda: self.OnAutoFill("btAutoFillAx2"))
        btAutoFillAx3 = self.findChild(QtWidgets.QPushButton, u"btAutoFillAx3")
        btAutoFillAx3.clicked.connect(lambda: self.OnAutoFill("btAutoFillAx3"))
        btAutoFillAx4 = self.findChild(QtWidgets.QPushButton, u"btAutoFillAx4")
        btAutoFillAx4.clicked.connect(lambda: self.OnAutoFill("btAutoFillAx4"))
        btSlice = self.findChild(QtWidgets.QPushButton, u"btSlice")
        btSlice.clicked.connect(self.OnSlice)
        btSlice3D = self.findChild(QtWidgets.QPushButton, u"btSlice3D")
        btSlice3D.clicked.connect(self.OnSlice3d)
        btBack = self.findChild(QtWidgets.QToolButton, u"btBack")
        btForward = self.findChild(QtWidgets.QToolButton, u"btForward")
        btOut3DText = self.findChild(QtWidgets.QPushButton, u"btOut3DText")
        btOut3DText.clicked.connect(self.OnOut3DText)
        btDumpToText = self.findChild(QtWidgets.QPushButton, u"btDumpToText")
        btDumpToText.clicked.connect(self.OnDumpToText)
        btDumpToBin = self.findChild(QtWidgets.QPushButton, u"btDumpToBin")
        btDumpToBin.clicked.connect(self.OnDumpToBin)

        self.D4MatrixFilePathCtrl = self.findChild(
            QtWidgets.QLabel, u"stPathToD4MatrixFiles")
        self.StatusTextCtrl = self.findChild(QtWidgets.QLabel, u"txtStatus")
        self.VirtualD4MatTextCtrl = self.findChild(
            QtWidgets.QLabel, u"txtvmsg")

        self.ButtonCtrlList = []
        self.ButtonCtrlList.append(btOpenD4Matrix)  # 0
        self.ButtonCtrlList.append(btClearColumn)  # 1
        self.ButtonCtrlList.append(btSaveTitles)   # 2
        self.ButtonCtrlList.append(btCloseMatrix)  # 3
        self.ButtonCtrlList.append(btAddSingleFile)  # 4
        self.ButtonCtrlList.append(btAddFilesInDir)  # 5
        self.ButtonCtrlList.append(btRemoveFile)   # 6
        self.ButtonCtrlList.append(btAutoFill)     # 7
        self.ButtonCtrlList.append(btOut3DText)    # 9->8
        self.ButtonCtrlList.append(btDumpToText)   # 10->9
        self.ButtonCtrlList.append(btDumpToBin)    # 11->10
        self.ButtonCtrlList.append(btAutoFillAx1)  # [inamura 160616]
        self.ButtonCtrlList.append(btAutoFillAx2)  # [inamura 160616]
        self.ButtonCtrlList.append(btAutoFillAx3)  # [inamura 160616]
        self.ButtonCtrlList.append(btAutoFillAx4)  # [inamura 160616]
        # [inamura 170227]-->
        # self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btSlice3D" ) )
        self.SliceButtonCtrlList = [btSlice, btSlice3D, btBack, btForward]
        self.isEnableSlice = False
        # <--[inamura 170227]
        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.setEnabled(False)
        self.SliceButtonCtrlList[0].setEnabled(False)  # [inamura 170227]
        self.SliceButtonCtrlList[1].setEnabled(False)  # [inamura 170227]
        self.SliceButtonCtrlList[2].setEnabled(False)
        self.SliceButtonCtrlList[3].setEnabled(False)
        for i in range(2):
            self.ButtonCtrlList[i].setEnabled(True)

        # mpanel = xrc.XRCCTRL( self.frame, "D4MatSetPanel" )
        self.D4MatRangeCtrl = []
        self.D4MatTitle = []
        self.D4MatUnit = []
        for i in range(12):
            self.D4MatRangeCtrl.append(self.findChild(
                QtWidgets.QLabel, u"txt%d" % (i + 1)))

        for i in range(4):
            self.D4MatTitle.append(self.findChild(
                QtWidgets.QLineEdit, u"v%dtitle" % (i + 1)))
            self.D4MatUnit.append(self.findChild(
                QtWidgets.QLineEdit, u"v%dunit" % (i + 1)))

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

        self.cbdiagfold = self.findChild(
            QtWidgets.QComboBox, u'cbDiagFoldType')
        self.cbdiagfold.activated.connect(self.OnComboDiagFold)
        for i in range(4):
            self.SliceAxis.append(self.findChild(
                QtWidgets.QComboBox, u"v%dcb" % (i + 1)))
            # self.SliceAxis[-1].Bind(wx.EVT_COMBOBOX, self.OnSliceAxis, self.SliceAxis[-1])
            self.SliceFoldCB.append(self.findChild(
                QtWidgets.QLineEdit, u"txtFold%d" % (i + 1)))
            self.SliceFoldDiag.append(self.findChild(
                QtWidgets.QCheckBox, u"ckbUseAx%1dFold" % (i + 1)))
        for i in range(12):
            self.SliceRange.append(self.findChild(
                QtWidgets.QLineEdit, u"stxt%d" % (i + 1)))

        # Axis type bind #[inamura 170228]-->
        for i in range(4):
            self.SliceAxis[i].activated.connect(self.OnChangeSliceAxis)
        # <--[inamura 170228]

        # menu
        menu_NewMatrix = self.findChild(QAction, u"actionMake_New_Matrix")
        menu_OpenMatrix = self.findChild(QAction, u"actionOpen_Matrix")
        menu_RebinMatrix = self.findChild(QAction, u"actionRebin_Matrix")
        menu_SaveAsText = self.findChild(QAction, u"actionSave_as_Text")
        menu_Exit = self.findChild(QAction, u"actionExit")
        menu_NewMatrix.triggered.connect(self.OnOpenMakeNewFrame)
        menu_OpenMatrix.triggered.connect(self.OnOpenD4Matrix)
        menu_RebinMatrix.triggered.connect(self.OnOpenRebinFrame)
        # menu_SaveAsText.triggered.connect()
        menu_Exit.triggered.connect(self.OnClose)

        self.FileListBox = self.findChild(QtWidgets.QTreeWidget, u"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].setText("-2.0")
            self.D4MatRangeCtrl[i * 3 + 1].setText("2.0")
            self.D4MatRangeCtrl[i * 3 + 2].setText("0.05")
            if i != 3:
                self.D4MatTitle[i].setText(("Q%d" % (i + 1)))
                self.D4MatUnit[i].setText("1/A")
            else:
                self.D4MatTitle[i].setText("hw")
                self.D4MatUnit[i].setText("meV")

            self.SliceRange[i * 3].setText("0.0")
            self.SliceRange[i * 3 + 1].setText("0.0")
            self.SliceRange[i * 3 + 2].setText("0.0")
            self.SliceAxis[i].setCurrentIndex(i)
            self.SliceFoldCB[i].setText("-1")
        # p1 = self.findChild(QtWidgets.QGroupBox,u"panel1")
        # p1.setStyleSheet("QGroupBox { border: 1px solid #AAAAAA; border-radius: 4px; margin-top: 0.5em; } QGroupBox::title { subcontrol-origin: margin; left: 5px; padding: 0 3px 0 3px;}")
        # Justify the alignment of controls on OSX
        if sys.platform == "darwin":
            self.resize(QtCore.QSize(540, 740))
        if sys.platform == "win32":
            self.resize(QtCore.QSize(550, 720))

        self.show()

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

        work_path = mu.UtsusemiEnvGetWorkDir()
        if work_path != "":
            os.chdir(work_path)

    #################################
    def OnOpenD4Matrix(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnOpenD4Matrix")
        # [inamura 160621]-->
        # isVirtual?
        if self.D4Mat.D4Mat.isVirtualMode():
            msg = u"Now You use Virtual Matrix. Are you sure to delete it ?"
            ret = QtWidgets.QMessageBox().information(self, u"Question", msg,
                                                      QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Cancel)
            if ret == QtWidgets.QMessageBox.Cancel:
                return
        try:
            if self.MakeVirtualFrame is not None:
                self.MakeVirtualFrame.OnClose(None)
        except:
            pass
        self.VirtualD4MatTextCtrl.setText("No Info")
        # <--[inamura 160621]
        # open dialog
        fullpath, filt = QtWidgets.QFileDialog().getOpenFileName(
            self, u'Open D4Matrix Param file ...', os.getcwd(), filter="XML (*.xml)")

        # cancel?
        if fullpath == "":
            return

        # get file path
        self.ParamFilePath = str(fullpath)
        # dir = os.path.dirname(filepath)
        flag, msg = self._OpenD4Matrix()
        if not flag:
            but = QtWidgets.QMessageBox().warning(
                self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return

    ################################
    def _OpenD4Matrix(self, filepath=""):
        if filepath == "":
            if self.ParamFilePath == "":
                msg = "Not set param file path.."
                mu.UtsusemiError(self.CommentHead + msg)
                return (False, msg)
        else:
            if os.path.exists(filepath):
                self.ParamFilePath = filepath
            else:
                msg = "Not found such file=" + filepath
                mu.UtsusemiError(self.CommentHead + msg)
                return (False, msg)

        ret = self.D4Mat.open(self.ParamFilePath)
        if (ret != -1):
            self.D4MatrixFilePathCtrl.setText(self.ParamFilePath)
        else:
            msg = " File is invalid. (" + self.ParamFilePath + ")"
            mu.UtsusemiError(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].setText("{0:g}".format(vv[0]))
            self.D4MatRangeCtrl[i * 3 + 1].setText("{0:g}".format(vv[1]))
            self.D4MatRangeCtrl[i * 3 + 2].setText("{0:g}".format(vv[2]))
            sv = self.D4Mat.D4Mat.PutAxTitle(i)
            self.D4MatTitle[i].setText(sv)
            uv = self.D4Mat.D4Mat.PutAxUnit(i)
            self.D4MatUnit[i].setText(uv)

        # self.FileListBox.Clear()
        self.FileListBox.clear()
        FileCompsVec = self.D4Mat.D4Mat.PutFileComponents()
        for i in range(FileCompsVec.size()):
            new_line = QtWidgets.QTreeWidgetItem()
            new_line.setText(0, FileCompsVec[i])
            self.FileListBox.addTopLevelItem(new_line)
            # self.FileListBox.Append( FileCompsVec[i] )

        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.setEnabled(True)
        self.isEnableSlice = True  # [inamura 170228]
        self.CheckEnableSliceButton()  # [inamura 170228]

        self.OnAutoFill()
        return (True, "")

    #################################
    def OnCloseD4Matrix(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnCloseMatrix")

        self._CloseD4Matrix()

    # [inamrua 160621]-->
    #################################
    def OnMakeVirtualMat(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnMakeVirtualMat")
        if self.D4Mat.D4Mat.isMatOpened():
            msg = u"Now You open D4Matrix. Are you sure to close it ?"
            ret = QtWidgets.QMessageBox().information(self, u"Question", msg,
                                                      QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Cancel)
            if ret == QtWidgets.QMessageBox.Cancel:
                return
        try:
            self.OnCloseD4Matrix(None)
        except:
            pass

        self.StatusTextCtrl.setText(
            "Opening window for Making Virtual or New D4Matrix.")
        self.MakeVirtualFrame = MakeVirtualD4MatrixFrame(self)

    # <--[inamura 160621]
    #################################
    def OnClearColumn(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnClearColumn")
        if not self.D4Mat.D4Mat.isMatOpened():
            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].setText("{0:g}".format(vv[0]))
            self.D4MatRangeCtrl[i * 3 + 1].setText("{0:g}".format(vv[1]))
            self.D4MatRangeCtrl[i * 3 + 2].setText("{0:g}".format(vv[2]))
            sv = self.D4Mat.D4Mat.PutAxTitle(i)
            self.D4MatTitle[i].setText(sv)
            uv = self.D4Mat.D4Mat.PutAxUnit(i)
            self.D4MatUnit[i].setText(uv)

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

    #################################
    def OnAddSingleFile(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnAddSingleFile")

        # open dialog
        fullpath, filt = QtWidgets.QFileDialog().getOpenFileName(self, u"Choose VisualCont2 output file ...",
                                                                 os.getcwd(), filter="Binary or Text (*.vbin, *.txt)")

        # cancel?
        if fullpath == "":
            return

        filepath = str(fullpath)
        self.StatusTextCtrl.setText("Loading file %s" % (filepath))
        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.setEnabled(False)
        self.isEnableSlice = False  # [inamura 170228]
        self.CheckEnableSliceButton()  # [inamura 170228]

        # self.frame.Refresh()
        # self.frame.Update()

        self.D4Mat.addFromFile(filepath)
        self.StatusTextCtrl.setText("Done.")

        new_line = QtWidgets.QTreeWidgetItem()
        new_line.setText(0, filepath)
        self.FileListBox.addTopLevelItem(new_line)
        # self.FileListBox.Append( filepath )

        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.setEnabled(True)
        self.isEnableSlice = True  # [inamura 170228]
        self.CheckEnableSliceButton()  # [inamura 170228]

    #################################
    def OnAddFilesInDir(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnAddFilesInDir")
        fullpath = QtWidgets.QFileDialog().getExistingDirectory(
            self, u"Select Directory including VisualContQ output files ...", os.getcwd())
        if fullpath == "":
            return

        mu.UtsusemiMessage(self.CommentHead + "DIR=" + fullpath)

        # check selected dir
        filedir = str(fullpath)
        if not os.path.exists(filedir):
            print(self.CommnetHead + "Cannot find such directory, " + filedir)
            raise

        # show progress bar
        self.D4Mat.progress = 0  # [inamura 180412]
        self.pdg = QtWidgets.QProgressDialog(
            "Loading VisualContQ output files (vbin) ...", "Abort", 0, len(os.listdir(filedir)), self)
        self.pdg.setWindowModality(QtCore.Qt.WindowModal)
        # 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(fullpath), ))
        # th.setDaemon(True)
        th.start()
        # progress
        self.pdg.setValue(int(self.D4Mat.progress))
        # pdg.Update(self.D4Mat.progress)
        # self.timer = QtCore.QTimer(self)
        # self.timer.timeout.connect(self.OnTimer)
        # self.timer.start(500)
        """
        while(True):                           ##[inamura 170116]-->
            wx.Sleep(0.5)
            if (self.D4Mat.progress > self.D4Mat.progress_max):
                break                          ##<--[inamura 170116]
            if pdg.wasCanceled():
                break
            pdg.Update(self.D4Mat.progress)
        pdg.Destroy()
        """
        while(True):
            time.sleep(0.1)
            if (self.D4Mat.progress > self.D4Mat.progress_max):
                break
            if self.pdg.wasCanceled():
                break
            self.pdg.setValue(int(self.D4Mat.progress))
        self.pdg.close()
        # 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 a_file in self.D4Mat.AddedFileList:
            new_line = QtWidgets.QTreeWidgetItem()
            new_line.setText(0, a_file)
            self.FileListBox.addTopLevelItem(new_line)
            # self.FileListBox.Append( file )

        # [inamura 170116]-->
        msg = "Finished: Load vbin files in " + filedir
        dial = QtWidgets.QMessageBox().information(
            self, u"Message", msg, QtWidgets.QMessageBox.Ok)
        return
        # <--[inamura 170116]

    #################################
    def OnTimer(self):
        if (self.D4Mat.progress > self.D4Mat.progress_max):
            self.timer.stop()
        if self.pdg.wasCanceled():
            self.timer.stop()
        self.pdg.setValue(int(self.D4Mat.progress))

    #################################
    def OnRemoveFile(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnRemoveFile")
        # selected_list = self.FileListBox.GetSelections()
        selected_list = self.FileListBox.selectedItems()

        if len(selected_list) == 0:
            return
        else:
            for a_selected in selected_list:
                mu.UtsusemiMessage(
                    self.CommentHead + "selected " + a_selected.text())
            # print self.CommentHead,"selected ",selected_list
            mu.UtsusemiMessage(
                self.CommentHead + "len={}".format(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)
                filepath = selected_list[last_index - i].text()
                mu.UtsusemiMessage(
                    self.CommentHead + "Removing File = " + filepath)
                ret = self.D4Mat.subtractText(filepath)
                if ret == 0:
                    # self.FileListBox.Delete(ind)
                    ind = self.FileListBox.indexOfTopLevelItem(
                        selected_list[last_index - i])
                    self.FileListBox.takeTopLevelItem(ind)

    #################################
    def OnAutoFill(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnAutoFill")
        # [inamura 160621]-->
        if evt is None:
            bt_name = "btAutoFill"
        else:
            bt_name = evt
        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].setText("{0:g}".format(vv[j]))

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

    #########################################
    def CheckEnableSliceButton(self):
        """
        """
        if self.isEnableSlice:
            flags = [0, 0, 0, 0]
            for i in range(4):
                curNo = self.SliceAxis[i].currentIndex()
                flags[curNo] += 1
            if flags == [1, 1, 0, 2]:
                self.SliceButtonCtrlList[0].setEnabled(True)
                self.SliceButtonCtrlList[1].setEnabled(False)
                self.findChild(QtWidgets.QPushButton,
                               u"btSlice").setText('Slice2D')
            elif flags == [1, 0, 0, 3]:
                self.SliceButtonCtrlList[0].setEnabled(True)
                self.SliceButtonCtrlList[1].setEnabled(False)
                self.findChild(QtWidgets.QPushButton,
                               u"btSlice").setText('Slice1D')
            elif flags == [1, 1, 1, 1]:
                self.SliceButtonCtrlList[0].setEnabled(False)
                self.SliceButtonCtrlList[1].setEnabled(True)
            else:
                self.SliceButtonCtrlList[0].setEnabled(False)
                self.SliceButtonCtrlList[1].setEnabled(False)
        else:
            self.SliceButtonCtrlList[0].setEnabled(False)
            self.SliceButtonCtrlList[1].setEnabled(False)

        if self.D4Mat.D4Mat.isVirtualMode():
            self.SliceButtonCtrlList[1].setEnabled(False)
    # <--[inamura 170228]
    #########################################

    def OnComboDiagFold(self, evt=None):
        """
        """
        index = self.cbdiagfold.currentIndex()
        if index == 0:
            for obj in self.SliceFoldDiag:
                obj.setCheckState(QtCore.Qt.Unchecked)
                obj.setEnabled(False)
        else:
            for obj in self.SliceFoldDiag:
                obj.setEnabled(True)

    #################################
    def OnSlice(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnSlice")
        # [inamura 160630]--> #check X,Y and Z
        flags = [0, 0, 0, 0]
        for i in range(4):
            ax = self.SliceAxis[i].currentIndex()
            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] and flags != [1, 0, 0, 3]:
            msg = "Axis type selections are invalid."
            dial = QtWidgets.QMessageBox().warning(
                self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return
        # <--[inamrua 160630]

        Axr = []
        type_axes = []
        foldings = []
        ax_flags = [0, 0, 0, 0]
        for i in range(4):
            # ax = self.SliceAxis[i].GetSelection() #[inamura 160616]
            ax = self.SliceAxis[i].currentIndex()
            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
            ax_flags[ax] += 1

            # [inamura 160616]-->
            # if self.SliceFoldCB[i].GetValue():
            #    foldings.append(1)
            # else:
            #    foldings.append(0)
            folnum_s = self.SliceFoldCB[i].text()
            fnum = -1
            try:
                fnum = float(folnum_s)
            except:
                pass
            foldings.append(fnum)
            # <--[inamura 160616]

            ar = []
            ar.append(float(self.SliceRange[i * 3].text()))
            ar.append(float(self.SliceRange[i * 3 + 1].text()))
            Axr.append(ar)

        DiagCond = self.cbdiagfold.currentIndex()
        # print("### DiagCond = %d "%DiagCond)
        if DiagCond == 0:
            pass
        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].checkState() == QtCore.Qt.Checked:
                    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"

        str_fld = ""
        cnt_fld = 0
        for i, c in enumerate(type_axes):
            title = self.D4MatTitle[i].text()
            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].text(), self.SliceRange[i * 3 + 1].text())

            if float(self.SliceFoldCB[i].text()) >= 0.0:
                if cnt_fld > 0:
                    str_fld += ",Ax%d[%g]" % ((i + 1),
                                              float(self.SliceFoldCB[i].text()))
                else:
                    str_fld += "Fold: Ax%d[%g]" % ((i + 1),
                                                   float(self.SliceFoldCB[i].text()))
                cnt_fld += 1

        if str_fld != "":
            titles[1] += str_fld

        titles[4] = "Intensity"

        if ax_flags == [1, 1, 0, 2]:
            if self.M2Plot is None:
                self.M2Plot = Plot2DMap(0, "D4MatSlicer", self)
            self.M2Plot.PlotMap(titles, self.D4Mat.SlicedECM, type_axes)
        else:
            if self.MPlot is None or (not self.MPlot.plot.IsAliveComm()):
                self.MPlot = mp.MPlot()
            self.MPlot.AddData(self.D4Mat.SlicedECM(0))

    # [inamura 170227]-->
    #################################
    def OnSlice3d(self, evt=None):
        """
        """
        # print self.CommentHead + "OnSlice3d"
        flags = [0, 0, 0, 0]
        for i in range(4):
            ax = self.SliceAxis[i].currentIndex()
            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 = QtWidgets.QMessageBox().warning(
                self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return

        Axr = []
        type_axes = []
        foldings = []
        name_axes = ["-", "-", "-"]
        for i in range(4):
            ax = self.SliceAxis[i].currentIndex()
            if ax == 0:
                type_axes.append("X")
                name_axes[0] = self.D4MatTitle[i].text()
            elif ax == 1:
                type_axes.append("Y")
                name_axes[1] = self.D4MatTitle[i].text()
            elif ax == 2:
                type_axes.append("Z")
                name_axes[2] = self.D4MatTitle[i].text()
            elif ax == 3:
                type_axes.append("T")
            else:
                raise

            foldings.append(float(self.SliceFoldCB[i].text()))

            ar = []
            ar.append(float(self.SliceRange[i * 3].text()))
            ar.append(float(self.SliceRange[i * 3 + 1].text()))
            Axr.append(ar)

        keys_axes = ["Vx", "Vy", "Vz"]
        print("Keys={}, {}, {}".format(
            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 uGao.SliceViewer3D as SV
        if self.SliceViewer3d is None:
            self.SliceViewer3d = SV.SliceViewer()

        # if self.SliceViewer3d.setData( 0, self.D4Mat.SlicedECM, "Sliced data in D4MatSlicer" ):
        if self.SliceViewer3d.setData(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" )
            self.SliceViewer3d.setData(
                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=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnOut3DText")
        # [inamura 160630]--> #check X,Y and Z
        flags = [0, 0, 0, 0]
        for i in range(4):
            ax = self.SliceAxis[i].currentIndex()
            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 = QtWidgets.QMessageBox().warning(
                self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return
        # <--[inamrua 160630]

        # [<Ignore Points with MaskVal>, <Use Given MasVal>, <MaskVal>]
        self.MaskValInfo = [True, False, 0.0]
        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 = Manyo.ListToDoubleVector( Axr[0] )
        a2v = Manyo.ListToDoubleVector( Axr[1] )
        a3v = Manyo.ListToDoubleVector( Axr[2] )
        a4v = Manyo.ListToDoubleVector( Axr[3] )
        def_axes = Manyo.MakeStringVector()
        fld = Manyo.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=None):
        """
        """
        self.DumpToFile(True)
    #################################

    def OnDumpToBin(self, env=None):
        """
        """
        self.DumpToFile(False)
    #################################

    def DumpToFile(self, isText):
        """
        """
        mu.UtsusemiMessage(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].currentIndex()
            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].text()))
            # <--[inamura 160616]

            ar = []
            ar.append(float(self.SliceRange[i * 3].text()))
            ar.append(float(self.SliceRange[i * 3 + 1].text()))
            Axr.append(ar)

        if flag_axes != [1, 1, 1, 1]:
            msg = "Invalid axes types. You must choose X,Y,Z and T for each."
            QtWidgets.QMessageBox().warning(self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return

        a1v = Manyo.ListToDoubleVector(Axr[0])
        a2v = Manyo.ListToDoubleVector(Axr[1])
        a3v = Manyo.ListToDoubleVector(Axr[2])
        a4v = Manyo.ListToDoubleVector(Axr[3])
        def_axes = Manyo.MakeStringVector()
        # fld = Manyo.ListToInt4Vector( foldings ) #[inamura 160616]
        fld = Manyo.ListToDoubleVector(foldings)  # [inamura 160616]
        for Axtype in type_axes:
            def_axes.append(Axtype)

        # open dialog
        dlg = None
        if (isText):
            fullpath, filt = QtWidgets.QFileDialog.getSaveFileName(
                self, "Choose Dump Text output file ...", os.getcwd(), filter='TEXT (*.txt)')
        else:
            fullpath, filt = QtWidgets.QFileDialog.getSaveFileName(
                self, "Choose Dump Binary output file ...", os.getcwd(), filter='BIN (*.bin)')

        # cancel?
        if fullpath == "":
            return

        btn_status = []
        for abtn in self.ButtonCtrlList:
            btn_status.append(abtn.isEnabled())
            abtn.setEnabled(False)
        self.SliceButtonCtrlList[0].setEnabled(False)  # [inamura 170228]
        self.SliceButtonCtrlList[1].setEnabled(False)  # [inamura 170228]

        # filepath = str( dlg.GetPath() )
        filepath = str(fullpath)
        self.StatusTextCtrl.setText("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.setText("Ready")

        for astatus, abtn in zip(btn_status, self.ButtonCtrlList):
            abtn.setEnabled(astatus)
        self.CheckEnableSliceButton()  # [inamura 170228]

        # self.frame.Update()
        msg = "Finished Save 4D data to file file : " + filepath
        dial = QtWidgets.QMessageBox().information(
            self, u"Message", msg, QtWidgets.QMessageBox.Ok)

    #################################

    def OnOpenMakeNewFrame(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnOpenMakeNewFrame")
        self.StatusTextCtrl.setText("Opening window for Making New D4Matrix.")
        dlg = MakeNewMatrixFrame(self)
        # self.StatusTextCtrl.SetLabel( "Done." )

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

    #################################
    def OnSaveDataAsText(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnSaveDataAsText")

    #################################
    def OnClose(self, evt=None):
        """
        """
        mu.UtsusemiMessage(self.CommentHead + "OnClose")
        self._CloseD4Matrix()
        if self.M2Plot is not None:
            self.M2Plot.Request2DClose()
        self.close()

    ################################

    def _CloseD4Matrix(self):
        """
        """
        self.D4Mat.close()

        self.ParamFilePath = ""
        self.D4MatrixFilePathCtrl.setText("Not selected.")
        for i in range(2, len(self.ButtonCtrlList)):
            self.ButtonCtrlList[i].setEnabled(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 = UtilQt.IFEvtProp(0)
            self.pno = 0
        else:
            self.pno = (num + 1) * 10
            self.ifi = UtilQt.IFEvtProp(self.pno)

    #########################################
    def PlotMap(self, labels, map_obj, type_axes):
        """
        2D マップ表示
        @param panel タブのインスタンス
        @param map　2D データ
        @retval 無し
        """
        # D2 プロッタが表示されているか
        if self.d2 is None:
            self.ifi.AddListner('u2dclosed', self.OnNotify2DClose)
            self.d2 = D2Vis.M2PlotPlus(self.frame, None, self.pno)

        self.ifi.NotifyEvent(self, "changedata", map_obj)

        while(True):
            time.sleep(0.1)
            if self.ifi.GetProperty("isready"):
                break
        self.ifi.NotifyEvent(self, "showdata", ("Xaxis", "Y", "-", 0.0, 0.0))
        self.ifi.NotifyEvent(self, "turnmodeplotonly", True)
        """
        else:
            if self.d2.plot.plot.poll() is not None: # if M2Plot is closed.
                self.OnNotify2DClose(None)
                self.d2 = M2P.M2Plot( map_obj )
            else:
                self.d2.ChangeMap( map_obj )


        if self.d2 is 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 is 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, "settitles", (labels[0], labels[1], True))
        self.ifi.NotifyEvent(self, "setlabels", (labels[2], labels[3]))
        self.ifi.NotifyEvent(self, "showdata", ("Xaxis", "Y", "-", 0.0, 0.0))
        """
        self.d2.SetMainTitle( labels[0] )
        self.d2.SetSubTitle( labels[0] )
        #self.ifi.NotifyEvent(self, "scalelabel", (labels[2], labels[3], labels[4]))
        self.d2.SetXLabel( labels[0] )
        self.d2.SetYLabel( labels[1] )
        self.d2.SetZLabel( "Neutrons" )
        """
        self.plotNow = (map, labels[0], labels[1])

    #########################################

    def OnNotify2DClose(self, *args):
        """
        2Dプロッタクローズイベント受信処理
        @param evt　　イベント
        @retval 無し
        """
        self.plotNow = None
        if self.d2 is not None:
            del self.d2
            self.d2 = None
        self.ifi.InitIF()

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


#######################################
#  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__':
    Ef = 0.0
    if mu.UtsusemiEnvGetInstCode() == "DNA":
        if len(sys.argv) > 1:
            arg_1 = sys.argv[1]
            arg_1 = arg_1.replace(" ", "")
            AnalyzerDNA = {"SI111": 2.08497, "SI311": 7.64}
            if arg_1.upper() in AnalyzerDNA:
                Ef = AnalyzerDNA[arg_1.upper()]
            else:
                mu.UtsusemiError(
                    "This argument is invalid {} [Si111 / Si311]".format(arg_1))
                sys.exit(-1)
    # Hi-resolution Display for windows
    if PYSIDEVER != 6:
        if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
            QtWidgets.QApplication.setAttribute(
                QtCore.Qt.AA_EnableHighDpiScaling, True)
    # app = wx.App(False)
    app = QtWidgets.QApplication(sys.argv)
    # Set Default Font Size to (default 14)
    deffont = app.font()
    if "UTSUSEMI_DEFAULT_FONTSIZE" in os.environ:
        deffontsize = int(os.environ["UTSUSEMI_DEFAULT_FONTSIZE"])
        deffont.setPointSize(deffontsize)
    else:
        deffont.setPointSize(10)
    app.setFont(deffont)
    app.setWindowIcon(QtGui.QIcon(os.path.join(
        os.environ["UTSUSEMI_BASE_DIR"], "ana", "Reduction", "ICON_Utsusemi4.png")))

    splash_path = os.path.join(
        os.environ["UTSUSEMI_BASE_DIR"], "ana", "Reduction", "LOGO_utsusemi4_c_box.png")
    splash = None

    if os.path.exists(splash_path):
        # splash = UtsusemiSplashScreen(splash_path)
        # splash.Show()
        pixmap = QtGui.QPixmap(splash_path)
        splash = QtWidgets.QSplashScreen(
            pixmap, QtCore.Qt.WindowStaysOnTopHint)
        splash.setMask(pixmap.mask())
        splash.show()
        splash.showMessage("Now Launching")

        app.processEvents()
        import time
        time.sleep(1)

    frame = D4MatSlicer(None, Ef=Ef)
    if splash is not None:

        splash.finish(frame)

    if PYSIDEVER == 6:
        sys.exit(app.exec())
    else:
        sys.exit(app.exec_())
    # app.MainLoop()
        # \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
        #     BOOKMARK                 BOOKMARK                 BOOKMARK                 BOOKMARK              \\
        #                 BOOKMARK                 BOOKMARK                 BOOKMARK                 BOOKMARK  \\
        # \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
