#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
"""
import time
import sys
import os

import Manyo
import Manyo.MLF as mm
import Manyo.Utsusemi as mu
import Manyo.SAS as ms
import utsusemi.ana.Reduction.BaseCommands as BC

import uGao.uGaoUtil as UtilPlot
import uGao.M2PlotPlus as D2Vis

PYSIDEVER = 6
try:
    from PySide6 import QtCore, QtGui, QtWidgets
    from PySide6.QtGui import QAction
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
if QtCore.__version__ < '5.0.0':
    from utsusemi.SAS.vis.ui_SAS_UBSlicer import Ui_MainWindow
else:
    if PYSIDEVER == 2:
        from utsusemi.SAS.vis.ui2_SAS_UBSlicer import Ui_MainWindow
    elif PYSIDEVER == 6:
        from utsusemi.SAS.vis.ui6_SAS_UBSlicer import Ui_MainWindow

###############################################
class UBSlicerFrame(QtWidgets.QMainWindow):
    def __init__(self, dat=None,parent=None):
        """
        """
        self.isDebug = mu.UtsusemiEnvGetDebugMode()
        if self.isDebug: print("#[inamura 220214] UBSlicerFrame start")
        super(UBSlicerFrame, self).__init__(parent)
        self.frame = Ui_MainWindow()
        # リソースからフレームが取得できなかった
        if self.frame is None:
            return
        self.frame.setupUi( self )

        ## Handles menus
        menu_Load = self.findChild( QAction, u"actionLoad")
        menu_Load.triggered.connect( self.OnLoadDataFile )
        menu_LoadParam = self.findChild( QAction, u"actionLoad_Param")
        menu_LoadParam.triggered.connect( self.OnLoadParamFile )
        menu_SaveParam = self.findChild( QAction, u"actionSave_Param")
        menu_SaveParam.triggered.connect( self.OnSaveParamFile )
        menu_exit = self.findChild( QAction, u"actionExit")
        menu_exit.triggered.connect( self.OnClose )

        ## Handles Run
        self.txtRunNo = self.findChild ( QtWidgets.QLabel, u"label_runno" )

        ## Handles for UB matrix panel
        self.txtUBmat = []
        for i in range(3):
            for j in range(3):
                self.txtUBmat.append( self.findChild( QtWidgets.QLineEdit,u'txt{:1d}{:1d}_ub'.format(i+1,j+1)) )
        self.chIsOriginSym = self.findChild ( QtWidgets.QCheckBox, u'checkBox' )

        ## Handles for Projection panel
        self.txtProjAx = []
        self.txtProjTitles = []
        self.txtProjUnits = []
        for i in range(3):
            for j in range(3):
                self.txtProjAx.append( self.findChild( QtWidgets.QLineEdit,u'txt_proj_ax{:1d}{:1d}'.format(i+1,j+1)) )
            self.txtProjTitles.append( self.findChild( QtWidgets.QLineEdit,u'txt_proj_t{:1d}'.format(i+1)) )
            self.txtProjUnits.append( self.findChild( QtWidgets.QLineEdit,u'txt_proj_u{:1d}'.format(i+1)) )
        self.btProjClr = self.findChild( QtWidgets.QPushButton,u'btClr_proj' )
        self.btProject = self.findChild( QtWidgets.QPushButton,u'btProj' )

        ## Handles for Slicing panel
        self.PanelSlice = self.findChild( QtWidgets.QGroupBox, u"PanelSlice")
        self.SliceAxisType = []
        self.SliceRange = []
        self.SliceAutoFill = []
        for i in range(3):
            self.SliceAxisType.append( self.findChild( QtWidgets.QComboBox,u'cb_sl_ax{:1d}'.format(i+1)) )
            for j in range(3):
                self.SliceRange.append( self.findChild( QtWidgets.QLineEdit,u'txt_sl_ax{:1d}{:1d}'.format(i+1,j+1)) )
            self.SliceAutoFill.append( self.findChild(QtWidgets.QPushButton,u'btAutoFillAx{:1d}'.format(i+1)) )
        self.btAutoFill = self.findChild(QtWidgets.QPushButton,u'btAutoFill')
        self.btSlice = self.findChild(QtWidgets.QPushButton,u'btSlice')

        ## Bind
        self.btProjClr.clicked.connect(self.OnProjClear)
        self.btProject.clicked.connect(self.OnProjection)
        for i in range(3):
            #self.SliceAxisType[i].activated[str].connect(self.OnChangeSliceAxisType)
            self.SliceAxisType[i].activated.connect(self.OnChangeSliceAxisType)
            self.SliceAutoFill[i].clicked.connect(self.OnAutoFillAxes)
        self.btAutoFill.clicked.connect(self.OnAutoFillAll)
        self.btSlice.clicked.connect(self.OnSlice)

        ## Initialize
        self.UBmat = []
        for i in range(9):
            self.txtUBmat[i].setText("0.0")
            self.txtProjAx[i].setText("0.0")
            self.SliceRange[i].setText("0.0")
        self.txtUBmat[0].setText("1.0")
        self.txtUBmat[4].setText("1.0")
        self.txtUBmat[8].setText("1.0")
        self.txtProjAx[0].setText("1.0")
        self.txtProjAx[4].setText("1.0")
        self.txtProjAx[8].setText("1.0")
        self.txtProjTitles[0].setText("H")
        self.txtProjTitles[1].setText("K")
        self.txtProjTitles[2].setText("L")
        self.txtProjUnits[0].setText("rlu")
        self.txtProjUnits[1].setText("rlu")
        self.txtProjUnits[2].setText("rlu")
        
        if self.isDebug:
            ubmat = [ 0.306,0.164,-0.961,
                      -0.007,0.767, 0.012,
                      0.836,0.420, 0.352 ]
            for i,x in enumerate(ubmat):
                self.txtUBmat[i].setText(str(x))
        
        self.btProject.setEnabled(False)
        self.btAutoFill.setEnabled(False)
        for i in range(3):
            self.SliceAutoFill[i].setEnabled(False)
        self.btSlice.setEnabled(False)

        self.isDataLoaded=False
        self.runNo= "None"
        if dat is None:
            self.TQ = ms.TreatQhklWithUB()
        else:
            self.TQ = ms.TreatQhklWithUB(dat)
            hh=dat.PutHeader()
            if hh.CheckKey(mu.UTSUSEMI_KEY_HEAD_INSTRUMENT)==1:
                self.runNo = hh.PutString(mu.UTSUSEMI_KEY_HEAD_INSTRUMENT)
            else:
                self.runNo = ""
            if hh.CheckKey(mu.UTSUSEMI_KEY_HEAD_RUNNUMBER)==1:
                self.runNo += hh.PutString(mu.UTSUSEMI_KEY_HEAD_RUNNUMBER)
            else:
                self.runNo += "Loaded"
            self.isDataLoaded=True
        self.btProject.setEnabled(self.isDataLoaded)
        self.M2Plot=None
        self.CommentHead="UBSlicer"
        self.setWindowTitle(u"UB Slicer ({})".format(self.runNo))
        self.txtRunNo.setText("{}".format(self.runNo))
        self.PanelSlice.setEnabled(False)  ## Slice panel
        self.show()

    ##############################################
    def OnClose(self):
        """
        """
        self.close()


    ##############################################
    def closeEvent(self, evt):
        """
        Close Event (virtual)
        """
        self.OnClose()
        evt.accept()

    ##############################################
    def OnLoadDataFile(self):
        """
        """
        if self.isDebug: print("Menu_Load")
        preEnabled = self.btProject.isEnabled()
        self.btProject.setEnabled(False)
        
        # open dialog
        fullpath, filt = QtWidgets.QFileDialog().getOpenFileName( self, u'Open data file ...', os.getcwd(), filter="ManyoDataBinary (*.mdb)" )
        # canceled ?
        if fullpath=="":
            self.btProject.setEnabled(preEnabled)
            return
        filepath=str(fullpath)
        if not os.path.exists(filepath):
            msg = " Cannot find msb file(%s)" % (filepath)
            mu.UtsusemiWarning(self.CommentHead+"::OnLoadDataFile >>"+msg)
            but = QtWidgets.QMessageBox().warning(self,u"Warning", msg, QtWidgets.QMessageBox.Ok )
            self.btProject.setEnabled(preEnabled)
            return


        self.btAutoFill.setEnabled(False)
        self.PanelSlice.setEnabled(False)
        time.sleep(0.5)
        dname=os.path.dirname(filepath)
        bname=os.path.basename(filepath)

        dat = BC.LoadDataFromManyoBinary(dname,bname)
        self.TQ.SetTarget(dat)
        self.isDataLoaded=True
        self.btProject.setEnabled(self.isDataLoaded)

        hh=dat.PutHeader()
        if hh.CheckKey(mu.UTSUSEMI_KEY_HEAD_INSTRUMENT)==1:
            self.runNo = hh.PutString(mu.UTSUSEMI_KEY_HEAD_INSTRUMENT)
        else:
            self.runNo = ""
        if hh.CheckKey(mu.UTSUSEMI_KEY_HEAD_RUNNUMBER)==1:
            self.runNo += hh.PutString(mu.UTSUSEMI_KEY_HEAD_RUNNUMBER)
        else:
            self.runNo += "Loaded"
        self.setWindowTitle(u"UB Slicer ({})".format(self.runNo))
        self.txtRunNo.setText("{}".format(self.runNo))

        return

    ##############################################
    def OnLoadParamFile(self):
        """
        """
        if self.isDebug: print("Menu_LoadParam")
        # open dialog
        fullpath, filt = QtWidgets.QFileDialog().getOpenFileName( self, u'Open data file ...', os.getcwd(), filter="(*.xml)" )
        # canceled ?
        if fullpath=="":
            return
        filepath=str(fullpath)
        if not os.path.exists(filepath):
            msg = " Cannot find xml file({})".format(filepath)
            mu.UtsusemiWarning(self.CommentHead+"::OnLoadUBmatrixFile >>"+msg)
            but = QtWidgets.QMessageBox().warning(self,u"Warning", msg, QtWidgets.QMessageBox.Ok )
            return
        vcp=mu.UtsusemiSqeCalcXtalParams()
        flags = vcp.TOXML_UBMATRIX + vcp.TOXML_SLICINGINFO + vcp.TOXML_PROJECTION
        if vcp.LoadFile(filepath,flags):
            ubmat_v = vcp.PutUBMatrix()
            qaxes_v = vcp.PutViewAxes()
            qaxes_labels_v=vcp.PutViewAxesLabels()
            qaxes_units_v=vcp.PutViewAxesUnits()
            
            if ubmat_v.size()==9:
                for i in range(9):
                    self.txtUBmat[i].setText("{}".format(ubmat_v[i]))
            else:
                msg = " ubMatrix data is invalid.({})".format(ubm_path)
                mu.UtsusemiWarning(self.CommentHead+"::OnLoadParamFile >>"+msg)
                but = QtWidgets.QMessageBox().warning(self,u"Warning", msg, QtWidgets.QMessageBox.Ok )
                return
            
            for i in range(3):
                for j in range(3):
                    self.txtProjAx[i*3+j].setText("{}".format(qaxes_v[ i*4 + j ]))
                self.txtProjTitles[i].setText(qaxes_labels_v[i])
                self.txtProjUnits[i].setText(qaxes_units_v[i])

            slice_type_v=vcp.PutAxType()
            for i in range(3):
                slice_v = vcp.PutAxRange(i)
                for j in range(3):
                    self.SliceRange[i*3+j].setText("{}".format(slice_v[j]))
                stype_dic={"X":0,"Y":1,"T":2}
                stype = slice_type_v[i].upper()
                if stype in stype_dic:
                    self.SliceAxisType[i].setCurrentIndex(stype_dic[stype])
                
        else:
            msg = " Not found such XtalParam file.({})".format(filepath)
            mu.UtsusemiWarning(self.CommentHead+"::OnLoadParamFile >>"+msg)
            but = QtWidgets.QMessageBox().warning(self,u"Warning", msg, QtWidgets.QMessageBox.Ok )
            return
        return

    ##############################################
    def OnSaveParamFile(self):
        """
        """
        if self.isDebug: print("Menu_SaveParam")
        filepath,filt =QtWidgets.QFileDialog.getSaveFileName(self, u"Save Params File ...", os.path.join(os.getcwd(),"XtalParam.xml"), filter=u"(*.xml)")
        filepath=str(filepath)
        if filepath=="":
            return

        vcp=mu.UtsusemiSqeCalcXtalParams()
        ubmat=[]
        for i in range(9):
            ubmat.append( float(self.txtUBmat[i].text()) )
        
        paxes=[]
        for i in range(3):
            pq=[float(self.txtProjAx[i*3+0].text()),
                float(self.txtProjAx[i*3+1].text()),
                float(self.txtProjAx[i*3+2].text()),
                0.0,
                self.txtProjTitles[i].text().strip(),
                self.txtProjUnits[i].text().strip()
            ]
            paxes.append(pq)
        paxes.append( [0.0,0.0,0.0,0.0,"Energy","meV"] )

        sAType=[str("X"),str("Y"),str("T")]
        for i in range(3):
            vcp.SetSliceAxis("{:1d}".format(i),
                             sAType[self.SliceAxisType[i].currentIndex()],
                             float(self.SliceRange[i*3].text()),
                             float(self.SliceRange[i*3+1].text()),
                             float(self.SliceRange[i*3+2].text()),
                             -1.0
            )
        vcp.SetSliceAxis("3","T",0.0,0.0,0.0,0.0)
        
        vcp.SetUBMatrix(ubmat,True)
        vcp.SetProjectionAxes( paxes[0], paxes[1], paxes[2], paxes[3] )
        flags = vcp.TOXML_UBMATRIX + vcp.TOXML_SLICINGINFO + vcp.TOXML_PROJECTION
        vcp.SaveFile(filepath,flags)
        del vcp
        return

    ##############################################
    def OnProjClear(self):
        """
        """
        if self.isDebug: print(".OnProjClear")
        for i in range(9):
            self.txtProjAx[i].setText("0.0")
        self.txtProjAx[0].setText("1.0")
        self.txtProjAx[4].setText("1.0")
        self.txtProjAx[8].setText("1.0")
        self.txtProjTitles[0].setText("H")
        self.txtProjTitles[1].setText("K")
        self.txtProjTitles[2].setText("L")

    ##############################################
    def OnProjection(self):
        """
        """
        if self.isDebug: print("OnProjection")
        self.UBmat=[]
        for i in range(9):
            try:
               self.UBmat.append( float(self.txtUBmat[i].text()) )
            except:
                raise UserWarning( "UB matrix includes invalid values.")
                return

        if self.TQ.SetUBmatrix( self.UBmat ):
            pass
        else:
            raise UserWarning( "UB matrix includes invalid values.")
            return

        vaxes = []
        vtitles = []
        vunits = []
        for i in range(3):
            ax=[]
            for j in range(3):
                try:
                    val=float(self.txtProjAx[i*3 + j].text())
                except:
                    raise UserWarning( "View Axes includes invalid values at {},{}".format(i,j))
                    return
                ax.append(val)
            vaxes.append(ax[:])
            vtitles.append(self.txtProjTitles[i].text())
            vunits.append(self.txtProjUnits[i].text())

        if self.isDebug:
            print("vaxes[0]",vaxes[0])
            print("vaxes[1]",vaxes[1])
            print("vaxes[2]",vaxes[2])
            print("vtitles=",vtitles)
        self.TQ.SetViewAxes( vaxes[0], vaxes[1], vaxes[2] )
        self.TQ.SetViewAxesLabels( vtitles[0],vtitles[1],vtitles[2],vunits[0],vunits[1],vunits[2])
        if self.TQ.Projection():
            ## Change Buttons Enabled
            self.btAutoFill.setEnabled(True)
            for i in range(3):
                self.SliceAutoFill[i].setEnabled(True)
            self.CheckSliceEnabled()
            self.PanelSlice.setEnabled(True)
        else:
            mu.UtsusemiError("Error Projection")

    ##############################################
    def OnChangeSliceAxisType(self):
        """
        """
        sender = self.sender()
        for i in range(3):
            if sender==self.SliceAxisType[i]:
                if self.isDebug: print("OnChangeSliceAxisType sender={}".format(i))
                cind=self.SliceAxisType[i].currentIndex()
                if cind==0 or cind==1: # X-axis or Y-axis
                    self.SliceRange[i*3 +2].setEnabled(True)
                else:
                    self.SliceRange[i*3 +2].setEnabled(False)
        self.CheckSliceEnabled()

    ##############################################
    def OnAutoFillAll(self):
        """
        """
        if self.isDebug: print("OnAUtoFillAll")
        mrange=self.TQ.PutSliceMaxRangeList()
        self.SliceRange[0].setText("{:g}".format(mrange[0]))
        self.SliceRange[1].setText("{:g}".format(mrange[1]))
        self.SliceRange[3].setText("{:g}".format(mrange[2]))
        self.SliceRange[4].setText("{:g}".format(mrange[3]))
        self.SliceRange[6].setText("{:g}".format(mrange[4]))
        self.SliceRange[7].setText("{:g}".format(mrange[5]))

    ##############################################
    def OnAutoFillAxes(self):
        """
        """
        sender = self.sender()
        for i in range(3):
            if self.SliceAutoFill[i]==sender:
                if self.isDebug: print("OnAutoFillAxes sender={}".format(i))
                mrange=self.TQ.PutSliceMaxRangeList()
                self.SliceRange[i*3].setText("{:g}".format(mrange[i*2]))
                self.SliceRange[i*3+1].setText("{:g}".format(mrange[i*2+1]))

    ##############################################
    def CheckSliceEnabled(self):
        """
        """
        axesFlag = [False,False,False]
        for i in range(3):
            axesFlag[self.SliceAxisType[i].currentIndex()]=True
        self.btSlice.setEnabled( (axesFlag[0] and axesFlag[1] and axesFlag[2]) )

    ##############################################
    def OnSlice(self):
        """
        """
        if self.isDebug: print("OnSlice")
        
        sliceAxesType=[]
        indSliceX=-1
        indSliceY=-1
        indSliceT=-1
        for i in range(3):
            k=self.SliceAxisType[i].currentIndex()
            if k==0:
                sliceAxesType.append("X")
                indSliceX=i
            elif k==1:
                sliceAxesType.append("Y")
                indSliceY=i
            else:
                sliceAxesType.append("T")
                indSliceT=i
        if indSliceX==-1 or indSliceY==-1 or indSliceT==-1:
            raise UserWarning( "Error OnSlice" )
        self.TQ.SetSliceAxes(sliceAxesType[0],sliceAxesType[1],sliceAxesType[2])
        xrange = [ float(self.SliceRange[indSliceX*3].text()), float(self.SliceRange[indSliceX*3+1].text()), float(self.SliceRange[indSliceX*3+2].text()) ]
        yrange = [ float(self.SliceRange[indSliceY*3].text()), float(self.SliceRange[indSliceY*3+1].text()), float(self.SliceRange[indSliceY*3+2].text()) ]
        trange = [ float(self.SliceRange[indSliceT*3].text()), float(self.SliceRange[indSliceT*3+1].text()) ]

        if self.isDebug: print(xrange,yrange,trange)
        if xrange[2]==0.0 or yrange[2]==0.0:
            msg="Slice : bin width is invalid ( more than 0 available )"
            ret = QtWidgets.QMessageBox().critical(self,u"Error", msg, QtWidgets.QMessageBox.Ok )
            return
        
        dat=Manyo.ElementContainerArray()
        self.TQ.Slice( dat, xrange, yrange, trange )
        
        labels = ["","",""]
        labels[self.SliceAxisType[0].currentIndex()]=self.txtProjTitles[0].text()
        labels[self.SliceAxisType[1].currentIndex()]=self.txtProjTitles[1].text()
        labels[self.SliceAxisType[2].currentIndex()]=self.txtProjTitles[2].text()
        
        titles = ["","","","","",""]
        qKey = self.TQ.PutQKeysList()
        titles[2]=self.txtProjTitles[indSliceX].text()
        titles[3]=self.txtProjTitles[indSliceY].text()
        titles[4]=qKey[indSliceX]
        titles[5]=qKey[indSliceY]
        # メインタイトル作成
        ecm_h = dat.PutHeader()
        sample = self.runNo
        if ecm_h.CheckKey("SampleName")==1:
            sample += " Sample: %s " % ecm_h.PutString("SampleName")
        """
        else:
            sample = ""
            if ecm_h.CheckKey("INSTRUMENT")==1:
                sample += "%s" % ecm_h.PutString("INSTRUMENT")
            if ecm_h.CheckKey("RUNNUMBER")==1:
                sample += "%s" % ( ecm_h.PutString("RUNNUMBER") )
            #else:
            #    sample = "---"
        """
        titles[0]=sample

        # サブタイトル作成
        str1 = "UB=\n"
        str1+= "|{:7.4f} {:7.4f} {:7.4f}|\n".format(self.UBmat[0],self.UBmat[1],self.UBmat[2])
        str1+= "|{:7.4f} {:7.4f} {:7.4f}|\n".format(self.UBmat[3],self.UBmat[4],self.UBmat[5])
        str1+= "|{:7.4f} {:7.4f} {:7.4f}|\n".format(self.UBmat[6],self.UBmat[7],self.UBmat[8])

        ii = -1
        for i in range(3):
            if self.SliceAxisType[i].currentIndex() == 2:
                ii=i
                break
        if (ii==-1):
            raise UserWarning("Error on Slice Axis Type")
            return

        # Thickness 取得
        nn=self.txtProjTitles[ii].text()
        thick1= self.SliceRange[ii*3 +0].text()
        thick2= self.SliceRange[ii*3 +1].text()
        str1 += "Thick=[{:s}:{:s} - {:s}]\n".format(nn,thick1,thick2)
        titles[1]=str1
        
        if self.M2Plot is None:
            self.M2Plot = Plot2DMap(0, "UBSlicer", self)
        self.M2Plot.PlotMap( titles, dat, isRefresh=True )
        

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

    #########################################
    def PlotMap(self, labels, eca, isRefresh=True):
        """
        2D マップ表示
        @param labels (list) [<main title>,<sub title>,<xlabel>,<ylabel>,<x axis>,<y axis>]
        @param eca (ElementContainerArray)
        @param isRefresh (bool)
        @retval 無し
        """
        # D2 プロッタが表示されているか
        if self.d2 is None:
            # 2Dプロッタフレームクローズイベントのリスナー登録
            self.ifi.AddListner('u2dclosed',  self.OnNotify2DClose)
            self.d2 = D2Vis.M2PlotPlus(self.frame ,None, self.pno)
        self.ifi.NotifyEvent(self, "changedata", eca)
        self.ifi.NotifyEvent(self, "showdata", (labels[4],labels[5],"-",0.0,0.0) )
        self.ifi.NotifyEvent(self, "settitles",(labels[0],labels[1],True))
        self.ifi.NotifyEvent(self, "setlabels",(labels[2],labels[3]))

        self.plotNow = (eca, labels[0], labels[1])  
 
                
    #########################################
    def OnNotify2DClose(self, *args):
        """
        2Dプロッタクローズイベント受信処理
        @param args
        @retval 無し
        """
        #self.d2 = None
        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")


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


#######################################
#  UBSlicer
#######################################  
class UBSlicer(object):
    """
    Application Class 
    """
    #########################################
    def __init__(self, matrix=None):
        """
        アプリケーションスタート
        @param  matrix  エレメントコンテナマトリックス
        @retval 無し
        """
        # Hi-resolution Display for windows
        if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
            QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling,True)
        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.setPixelSize(deffontsize)
        else:
            deffont.setPixelSize(14)
        app.setFont(deffont)

        frame = UBSlicerFrame(matrix, None)
        if PYSIDEVER == 6:
            sys.exit(app.exec())
        else:
            sys.exit(app.exec_())


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

if __name__=='__main__':
    if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
        QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling,True)
    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.setPixelSize(deffontsize)
    else:
        deffont.setPixelSize(14)
    app.setFont(deffont)
    app.setWindowIcon(QtGui.QIcon(os.path.join( os.environ["UTSUSEMI_BASE_DIR"],"ana","Reduction","ICON_Utsusemi4.png" )))

    frame = UBSlicerFrame(None,None)
    if PYSIDEVER == 6:
        sys.exit(app.exec())
    else:
        sys.exit(app.exec_())
