# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name:        SliceViewerMain
# Purpose:
#
# Author:
#
# Created:     22/01/2016
# Copyright:   (c)
# Licence:
#-------------------------------------------------------------------------------
import sys, os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/View')
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/Tool')

from pyqtgraph.Qt import QtCore, QtGui, uic
from PyQt4.QtCore import pyqtSignal, QSize, Qt
from PyQt4.QtGui import QSizePolicy
import pyqtgraph as pg
import pyqtgraph.opengl as gl
import numpy as np
import threading
import time
import Queue
import socket
import math
import inspect
import threading

import GLAxisItem2
import ViewSubData
import ViewMainData
import ExtMath


from OpenGL.GLU import *
from OpenGL.GLUT import *

#[inamura 160920]-->
#########################################
from vis.UtilPlot import AcqPath 
def SearchPath(fname,isFile=True):
    """
    フルパスの探索
    @param  fname  　ファイル名
    @retval ファイルのフルパス
    """ 
    # カレントディレクトリを取得
    fpath = os.path.join(os.getcwd(), fname)
    # カレントディレクトリに目的ファイルがあるか
    if isFile:
        if os.path.isfile(fpath):
            # フルパスを返す
            return (os.getcwd(),fpath)
    else:
        if os.path.isdir(fpath):
            return fpath

    # 環境変数に指定されたディレクトリを取得
    ap = AcqPath()
    paths = [ap.GetSysExp(), ap.GetSysAnal(), ap.GetSysVis()]
    p_path = os.environ.get('PYTHONPATH')
    if p_path!=None:
        p_path_list = p_path.split(os.pathsep)
        for pp in p_path_list:
            paths.append(pp)
            paths.append( os.path.join(pp,"vis","SliceViewer3D") )

    # 全PYTHONPATHディレクトリを探索
    for path in paths:
        fpath = os.path.normpath(os.path.join(path,fname))
        # ディレクトリに目的ファイルがあるか
        if isFile:
            if os.path.isfile(fpath):
                # フルパスを返す
                return (path,fpath)
        else:
            if os.path.isdir(fpath):
                return fpath

    # 目的ファイルが見つからなかった
    return None
#########################################
view_path = SearchPath( "View", isFile=False )
if view_path!=None:
    sys.path.append(view_path)
#<--[inamura 160920]

if sys.platform!="darwin": #[inamura 171017 temporal measure]
    glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)

class SliceViewerMain(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        #[inamura 160920]-->
        ui_path = SearchPath( "SliceViewerMain.ui" )
        if ui_path==None:
            raise UserWarning,"Not found SliceViewerMain.ui"
        #self.ui = uic.loadUi("SliceViewerMain.ui",self)
        self.ui = uic.loadUi(ui_path[1],self)
        #<--[inamura 160920]

        self.viewSubData  = ViewSubData.ViewSubData()
        self.viewMainData = ViewMainData.ViewMainData()
        self.viewSubData.viewMainData = self.viewMainData
        self.viewMainData.viewSubData = self.viewSubData
        self.extMath = ExtMath.ExtMath()

        # widget size
        #-----------
        baseW = 440
#        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
#        self.setMinimumSize(100, 100) 
#        self.setMaximumSize(1500, 1000)

        # window
        self.windowW = 1250
        self.windowH = 720
        if sys.platform=="darwin":
            self.windowH = 760
        # glView  
        self.glViewW = 700
        self.glViewH = 700
        # dataInfo
        self.dataInfoWmin = baseW
        self.dataInfoWmax = baseW
        self.dataInfoHmin = 100
        self.dataInfoHmax = 700
        # basic slice
        self.basicSliceWmin = baseW
        self.basicSliceWmax = baseW
        self.basicSliceHmin = 650
        self.basicSliceHmax = 650
        if sys.platform=="darwin":
            self.basicSliceHmin = 750
            self.basicSliceHmax = 750
        # free slice
        self.freeSliceWmin = baseW
        self.freeSliceWmax = baseW
        self.freeSliceHmin = 550
        self.freeSliceHmax = 550
        # colorBar
        self.colorBarWmin = 100
        self.colorBarWmax = 100
        self.colorBarHmin = 200
        self.colorBarHmax = 1000
        # axis
        self.axisGridWmin = baseW
        self.axisGridWmax = baseW
        self.axisGridHmin = 300
        self.axisGridHmax = 300
        # label
        self.labelWmin = baseW
        self.labelWmax = baseW
        self.labelHmin = 130
        self.labelHmax = 130


#        self.extMath.rotateAroundVector(np.array([1, 1, 1]), 2, np.array([2, 3,4]))
#        self.extMath.rotateAroundVector(np.array([1, 0, 0]), 30.0/180.0*math.pi, np.array([2, 3,4]))
#        print self.extMath.getAngle(np.array([1, 0, 0]), np.array([1, math.sqrt(3), 0]))*180.0/math.pi

        self.viewSubData.updateGrid()
        self.viewSubData.updateAxis()
        self.viewSubData.updateAxisTick()
        self.viewSubData.updateAxisLabelFont(self.viewSubData.axisFont)

        self.outputDirectory = ""
        self.xScrollPressed = False
        self.yScrollPressed = False
        self.zScrollPressed = False
        self.xScrollTriggered = False
        self.yScrollTriggered = False
        self.zScrollTriggered = False

        self.widgets = []

        #[inamura 160920]-->
        icon_dir = SearchPath( "Icon",isFile=False )
        if icon_dir==None:
            raise UserWarning,"Not Found Icon folder"
        self.IconDir=icon_dir
        #<--[inamura 160920]
        #[inamura 180516]-->
        import matplotlib
        import numpy
        # Original ColorMap of Utsusemi
        cdict = {'blue': ((0.0, 0.0, 0.0),
                          (0.16, 1, 1),
                          (0.377, 1, 1),
                          (0.67, 0, 0),
                          (1, 0,0)),
                 'green': ((0.0, 0, 0),
                           (0.174, 0, 0),
                           (0.410, 1, 1),
                           (0.66, 1, 1),
                           (0.915, 0, 0),
                           (1, 0, 0)),
                 'red': ((0.0, 0, 0),
                         (0.387, 0, 0),
                         (0.680, 1, 1),
                         (0.896, 1, 1),
                         (1, 0.5, 0.5))
                 }
        _GMT_haxby_data =  {'blue': [(0.0, 0.474509805441, 0.474509805441), (0.0322580635548, 0.588235318661, 0.588235318661), (0.0645161271095, 0.686274528503, 0.686274528503), (0.0967741906643, 0.784313738346, 0.784313738346), (0.129032254219, 0.831372559071, 0.831372559071), (0.161290317774, 0.878431379795, 0.878431379795), (0.193548381329, 0.941176474094, 0.941176474094), (0.225806444883, 0.972549021244, 0.972549021244), (0.258064508438, 1.0, 1.0), (0.290322571993, 1.0, 1.0), (0.322580635548, 1.0, 1.0), (0.354838699102, 0.941176474094, 0.941176474094), (0.387096762657, 0.882352948189, 0.882352948189), (0.419354826212, 0.784313738346, 0.784313738346), (0.451612889767, 0.68235296011, 0.68235296011), (0.483870953321, 0.658823549747, 0.658823549747), (0.516129016876, 0.635294139385, 0.635294139385), (0.548387110233, 0.552941203117, 0.552941203117), (0.580645143986, 0.474509805441, 0.474509805441), (0.612903237343, 0.407843142748, 0.407843142748), (0.645161271095, 0.341176480055, 0.341176480055), (0.677419364452, 0.270588248968, 0.270588248968), (0.709677398205, 0.29411765933, 0.29411765933), (0.741935491562, 0.305882364511, 0.305882364511), (0.774193525314, 0.352941185236, 0.352941185236), (0.806451618671, 0.486274510622, 0.486274510622), (0.838709652424, 0.61960786581, 0.61960786581), (0.870967745781, 0.68235296011, 0.68235296011), (0.903225779533, 0.768627464771, 0.768627464771), (0.93548387289, 0.843137264252, 0.843137264252), (0.967741906643, 0.921568632126, 0.921568632126), (1.0, 1.0, 1.0)], 'green': [(0.0, 0.0, 0.0), (0.0322580635548, 0.0, 0.0), (0.0645161271095, 0.0196078438312, 0.0196078438312), (0.0967741906643, 0.0392156876624, 0.0392156876624), (0.129032254219, 0.0980392172933, 0.0980392172933), (0.161290317774, 0.156862750649, 0.156862750649), (0.193548381329, 0.40000000596, 0.40000000596), (0.225806444883, 0.505882382393, 0.505882382393), (0.258064508438, 0.686274528503, 0.686274528503), (0.290322571993, 0.745098054409, 0.745098054409), (0.322580635548, 0.792156875134, 0.792156875134), (0.354838699102, 0.882352948189, 0.882352948189), (0.387096762657, 0.921568632126, 0.921568632126), (0.419354826212, 0.921568632126, 0.921568632126), (0.451612889767, 0.92549020052, 0.92549020052), (0.483870953321, 0.960784316063, 0.960784316063), (0.516129016876, 1.0, 1.0), (0.548387110233, 0.960784316063, 0.960784316063), (0.580645143986, 0.92549020052, 0.92549020052), (0.612903237343, 0.843137264252, 0.843137264252), (0.645161271095, 0.741176486015, 0.741176486015), (0.677419364452, 0.627451002598, 0.627451002598), (0.709677398205, 0.458823531866, 0.458823531866), (0.741935491562, 0.313725501299, 0.313725501299), (0.774193525314, 0.352941185236, 0.352941185236), (0.806451618671, 0.486274510622, 0.486274510622), (0.838709652424, 0.61960786581, 0.61960786581), (0.870967745781, 0.701960802078, 0.701960802078), (0.903225779533, 0.768627464771, 0.768627464771), (0.93548387289, 0.843137264252, 0.843137264252), (0.967741906643, 0.921568632126, 0.921568632126), (1.0, 1.0, 1.0)], 'red': [(0.0, 0.0392156876624, 0.0392156876624), (0.0322580635548, 0.156862750649, 0.156862750649), (0.0645161271095, 0.0784313753247, 0.0784313753247), (0.0967741906643, 0.0, 0.0), (0.129032254219, 0.0, 0.0), (0.161290317774, 0.0, 0.0), (0.193548381329, 0.101960785687, 0.101960785687), (0.225806444883, 0.0509803928435, 0.0509803928435), (0.258064508438, 0.0980392172933, 0.0980392172933), (0.290322571993, 0.196078434587, 0.196078434587), (0.322580635548, 0.266666680574, 0.266666680574), (0.354838699102, 0.380392163992, 0.380392163992), (0.387096762657, 0.415686279535, 0.415686279535), (0.419354826212, 0.486274510622, 0.486274510622), (0.451612889767, 0.541176497936, 0.541176497936), (0.483870953321, 0.674509823322, 0.674509823322), (0.516129016876, 0.803921580315, 0.803921580315), (0.548387110233, 0.874509811401, 0.874509811401), (0.580645143986, 0.941176474094, 0.941176474094), (0.612903237343, 0.96862745285, 0.96862745285), (0.645161271095, 1.0, 1.0), (0.677419364452, 1.0, 1.0), (0.709677398205, 0.956862747669, 0.956862747669), (0.741935491562, 0.933333337307, 0.933333337307), (0.774193525314, 1.0, 1.0), (0.806451618671, 1.0, 1.0), (0.838709652424, 1.0, 1.0), (0.870967745781, 0.960784316063, 0.960784316063), (0.903225779533, 1.0, 1.0), (0.93548387289, 1.0, 1.0), (0.967741906643, 1.0, 1.0), (1.0, 1.0, 1.0)]}
        colormap_default = matplotlib.colors.LinearSegmentedColormap('default_utsusemi',cdict,200)
        colormap_haxby = matplotlib.colors.LinearSegmentedColormap('GMT_haxby',_GMT_haxby_data,256)
        self.colorMap_utsusemi = {}
        # Make Default ColorMap
        pos=numpy.linspace(0.0,1.0,200)
        self.colorBarPreset_default = "default"
        color = colormap_default( pos, bytes=True)
        cmap = pg.ColorMap(pos,color)
        lut = pg.ColorMap(pos,color).getLookupTable(0.0,1.0,200)
        self.colorMap_utsusemi[self.colorBarPreset_default] = ( cmap, lut )
        # Make GMT-haxby ColorMap
        self.colorBarPreset_haxby = "haxby"
        color = colormap_haxby( pos, bytes=True)
        cmap = pg.ColorMap(pos,color)
        lut = pg.ColorMap(pos,color).getLookupTable(0.0,1.0,200)
        self.colorMap_utsusemi[self.colorBarPreset_haxby] = ( cmap, lut )
        # Preset is Default
        self.viewSubData.colorBarPreset=self.colorBarPreset_default
        self.preColorBarName = None
        #<--[inamura 180516]

#================================================================================
# 画面の構築
#================================================================================
        # Title
        self.setWindowTitle("Slice Viewer")
        self.resize( QSize(self.windowW, self.windowH) );

        #**** 描画用 ****
        # 3D表示画面の追加
        self.addGLViewWidget()
        
        # スクロールバーを追加
        self.addSliceScrollBar()

        #**** パラメータ用 *****
        # データ読み込み用パラメータウィジェットの作成
        self.createDataLoadWidget()
        
        # Create data Information Widget
        self.createDataInfoWidget()
        self.updateDataInformation()

        # 3面スライス用パラメータウィジェットの作成
        self.createBasicSliceWidget()        
       
        # 任意面スライス用パラメータウィジェットの作成
        self.createFreeSliceWidget()

        # Axis/Grid Widget
        self.createAxisGridWidget()

        # 強度分布設定用（カラーバー）ウィジェットの作成
        self.createColorBarSettingWidget()

        # 表示設定用パラメータウィジェットの作成
        self.createViewSettingWidget()

        # その他ラベル等表示設定用ウィジェットの作成
        self.createLabelSettingWidget()

        # パラメータ用レイアウトにスペーサーを挿入 (一番下に追加)
        self.addSpacerToParameterLayout()

        # カラーバーウィジェット
        self.addColorBarWidget()

        # Status bar
        self.addStatusBar()
       
#================================================================================
# メニュー等のスロット/シグナルの定義
#================================================================================
        # メニューアクションにSLOTを接続
        #-----------------------------
        # データ読み込みメニュー
        #self.data_load_view_action.toggled.connect(self.viewWidget)
        self.data_load_view_action.triggered.connect(self.openFileDialog)
        # Data Info
        self.data_info_view_action.toggled.connect(self.viewWidget)
        # 基本3面表示メニュー
        self.basic_slice_view_action.toggled.connect(self.viewWidget)
        # 基本3面用スライダ表示メニュー
        self.basic_slice_slider_view_action.toggled.connect(self.viewWidget)
        # 任意面表示メニュー
        self.free_slice_view_action.toggled.connect(self.viewWidget)
        # Axis/Gridメニュー
        self.axis_grid_view_action.toggled.connect(self.viewWidget)
        # カラーバー設定用メニュー
        self.color_bar_setting_view_action.toggled.connect(self.viewWidget)
        # カラーバー
        self.color_bar_view_action.toggled.connect(self.viewWidget)
        # 表示設定用メニュー
        self.view_setting_view_action.toggled.connect(self.viewWidget)
        # ラベル
        self.label_setting_view_action.toggled.connect(self.viewWidget)
        # screenshot
        self.view_screenshot_action.triggered.connect(self.doBasicSliceView)
        # transparency
        self.translucent_action.triggered.connect(self.onChangeGLOption)
        # zoom best fit    
        self.zoom_best_fit_action.triggered.connect(self.zoomBestFit)
        # set view direction to +X
        self.view_direction_to_plus_x_action.triggered.connect(self.viewDirectionToPlusX)
        # set view direction to -X
        self.view_direction_to_minus_x_action.triggered.connect(self.viewDirectionToMinusX)
        # set view direction to +Y
        self.view_direction_to_plus_y_action.triggered.connect(self.viewDirectionToPlusY)
        # set view direction to -Y
        self.view_direction_to_minus_y_action.triggered.connect(self.viewDirectionToMinusY)
        # set view direction to +Z
        self.view_direction_to_plus_z_action.triggered.connect(self.viewDirectionToPlusZ)
        # set view direction to -Z
        self.view_direction_to_minus_z_action.triggered.connect(self.viewDirectionToMinusZ)
        # increase vertical size of main window
        self.increase_vertical_size_action.triggered.connect(self.IncreaseWindowVerticalSize)
        # decrease vertical size of main window
        self.decrease_vertical_size_action.triggered.connect(self.DecreaseWindowVerticalSize)
        # increase horizontal size of main window
        self.increase_horizontal_size_action.triggered.connect(self.IncreaseWindowHorizontalSize)
        # decrease horizontal size of main window
        self.decrease_horizontal_size_action.triggered.connect(self.DecreaseWindowHorizontalSize)


        # スライス関連操作中に照射させるシグナルに対するスロット
        #-------------------------------------------------------------
        # Reset Scroll Bar
        self.connect(self.viewMainData, self.viewMainData.update_scrollbar_signal, self.updateScrollbar)
        # Update Scroll Bar range
        self.connect(self.viewMainData, self.viewMainData.update_scrollbar_range_signal, self.updateScrollbarRange)
        # ステータスバー
        self.connect(self.viewMainData, self.viewMainData.status_bar_signal, self.updateStatusBar)
        # Data Information
        self.connect(self.viewMainData, self.viewMainData.update_data_info_signal, self.updateDataInformation)
        # Update Basic Slice Data
        self.connect(self.viewMainData, self.viewMainData.update_basic_slice_signal, self.updateBasicSlice)
        # Update Axis and grid
        self.connect(self.viewMainData, self.viewMainData.update_axis_grid_signal, self.updateAxisGridOrigin)
        # 3面表示のItem (メインビューに表示）を作成
        self.connect(self.viewMainData, self.viewMainData.create_slice_signal, self.createBasicSliceItem)
        # Free Slice Item (メインビューに表示）を作成
        self.connect(self.viewMainData, self.viewMainData.create_free_slice_signal, self.createFreeSliceItem)
        # Update view
        self.connect(self.viewMainData, self.viewMainData.update_slice_view_signal, self.updateSliceView)
        # メインビューの更新
        self.connect(self.viewMainData, self.viewMainData.update_glview_signal, self.dataToGLViewItemVisibility)
        # データからカラーバーウィジェットへ反映（auto scaleで取得した値を反映）
        self.connect(self.viewMainData, self.viewMainData.update_autoscale_signal, self.dataToColorBarWidget)
        # 画像として保存
        self.connect(self.viewMainData, self.viewMainData.save_glview_signal, self.saveAsImage)
        # update grid size
        self.connect(self.viewMainData, self.viewMainData.update_grid_size_signal, self.updateGridSize)
        # update grid
        self.connect(self.viewMainData, self.viewMainData.update_grid_signal, self.updateGrid)

#================================================================================
# 初期値の設定
#================================================================================
#  設定用ウィジェット等の表示/非表示の切り替え (***.uiでの設定を反映させる)
        self.initializeWidgetsVisible()
        
# データクラスの情報をウィジェットに反映
        self.viewMethod1Radio.setChecked(True)
        self.dataToWidget()        
        
# データクラスの情報からView Itemを作成/表示・非表示の切り替え
        self.dataToGLViewItemVisibility()
        
# Update Axis Label
        self.updateAxisLabel()
        
# ウィジェットの活性制御
        self.enableControl() 

# zoom best fit
        self.zoomBestFit()

#================================================================================
# コマンド関連
#================================================================================
        # インターフェイスクラスのインスタンスを取得
        self.ifi = IFEvtProp(1)

        # フローティングボックスクローズのリスナー登録
        self.ifi.AddListner('setFocalPoint', self.setFocalPoint)
        self.ifi.AddListner('setViewPoint', self.setViewPoint)
        self.ifi.AddListner('setDistance', self.setDistance)
        self.ifi.AddListner('setAzimuth', self.setAzimuth)
        self.ifi.AddListner('setElevation', self.setElevation)
        self.ifi.AddListner('setScalarRange', self.setScalarRange)
        self.ifi.AddListner('setAxisLength', self.setAxisLength)
        self.ifi.AddListner('setGridSpace', self.setGridSpace)
        self.ifi.AddListner('setOutputDirectory', self.setOutputDirectory)
        self.ifi.AddListner('doSliceAx1', self.doSliceAx1)
        self.ifi.AddListner('doSliceAx2', self.doSliceAx2)
        self.ifi.AddListner('doSliceAx3', self.doSliceAx3)
        self.ifi.AddListner('doFreeSlice', self.doFreeSlice)
        self.ifi.AddListner('setData', self.setData) ##[inamura 170227]
        self.ifi.AddListner('setAxesTitles', self.setAxesTitles) ##[inamura 170227]

#********************************************************************************************* 
# END of __init__(self)
#********************************************************************************************* 
#================================================================================
#
# ユーザコマンド
#
#================================================================================
# [inamura 170227]-->
    def setData(self, *args):
        ## decode data
        import Manyo
        try:
            #print "params=",args[2]
            filepath = args[2][0]
            title = args[2][1]
            xkey = args[2][2]
            ykey = args[2][3]
            zkey = args[2][4]
            #print "filepath=",filepath
            crr = Manyo.ReadSerializationFileBinary(filepath)
            data = Manyo.ElementContainerMatrix()
            crr.Load(data)
            del crr
        except:
            print "Failed to read temporal file"
            return
        
        self.viewMainData.SetData(data,xkey,ykey,zkey)
        title = "D4MatSlicer : %s"%title
        self.initializeViewer(title)

        fp_x ="%g"%((self.viewMainData.basicSliceAx1From + self.viewMainData.basicSliceAx1To)/3.0 )
        fp_y ="%g"%((self.viewMainData.basicSliceAx2From + self.viewMainData.basicSliceAx2To)/3.0 )
        fp_z ="%g"%((self.viewMainData.basicSliceAx3From + self.viewMainData.basicSliceAx3To)/3.0 )

        self.setFocalPoint("","",[fp_x,fp_y,fp_z])

    def setAxesTitles(self, *args):
        self.viewMainData.ax1Slice.axisTitle = str(args[2][0])
        self.viewMainData.ax2Slice.axisTitle = str(args[2][1])
        self.viewMainData.ax3Slice.axisTitle = str(args[2][2])
        self.ax1Title.setText(self.viewMainData.ax1Slice.axisTitle)
        self.ax2Title.setText(self.viewMainData.ax2Slice.axisTitle)
        self.ax3Title.setText(self.viewMainData.ax3Slice.axisTitle)
        self.updateAxisGrid()
        
#<--[inamura 170227]

# 注視点を指定
#---------------------------------------
    def setFocalPoint(self, *args):
        try:
            x = float(args[2][0]) * self.viewMainData.basicSliceAx1Scale
            y = float(args[2][1]) * self.viewMainData.basicSliceAx2Scale
            z = float(args[2][2]) * self.viewMainData.basicSliceAx3Scale
            self.glView.opts['center'] = QtGui.QVector3D(x, y, z)
            self.glView.update()
        except:
            print "error! input argument needs numeric string."

# View Pointを指定
#---------------------------------------
    def setViewPoint(self, *args):
        try:
            print "setViewPoint args=",args
            vx = float(args[2][0]) * self.viewMainData.basicSliceAx1Scale
            vy = float(args[2][1]) * self.viewMainData.basicSliceAx2Scale
            vz = float(args[2][2]) * self.viewMainData.basicSliceAx3Scale
            print "vx,vy,vz=",vx,vy,vz
            center = self.glView.opts['center']
            fx = 0
            fy = 0
            fz = 0
            if isinstance(center, pg.Vector):
               fx = center[0]
               fy = center[1]
               fz = center[2]
            elif isinstance(center, QtGui.QVector3D):
               fx = center.x()
               fy = center.y()
               fz = center.z()

            vecX = vx-fx
            vecY = vy-fy
            vecZ = vz-fz
            dist = math.sqrt(vecX*vecX + vecY*vecY + vecZ*vecZ)
            tmp  = math.sqrt(vecX*vecX + vecY*vecY)
            ele  = math.atan2(vecZ, tmp) * 180.0 / math.pi
            az   = math.atan2(vecY, vecX) * 180.0 / math.pi
       
            self.glView.opts['distance'] = dist
            self.glView.opts['azimuth'] = az
            self.glView.opts['elevation'] = ele

            self.glView.update()
        except:
            print "error! input argument needs numeric string."
            
# 視点の距離を指定
#---------------------------------------
    def setDistance(self, *args):
        try:
            dist = float(args[2][0])
            self.glView.opts['distance'] = dist
            self.glView.update()
        except:
            print "error! input argument needs numeric string."
            

# 方位角を指定
#---------------------------------------
    def setAzimuth(self, *args):
        try:
            az = float(args[2][0])
            self.glView.opts['azimuth'] = az
            self.glView.update()
        except:
            print "error! input argument needs numeric string."                        

# カメラの仰角を指定
#---------------------------------------
    def setElevation(self, *args):
        try:
            ele = float(args[2][0])
            self.glView.opts['elevation'] = ele
            self.glView.update()
        except:
            print "error! input argument needs numeric string."

# set scalar range
#--------------------------------------
    def setScalarRange(self, *args):
        try:
            min = float(args[2][0])
            max = float(args[2][1])
            self.viewSubData.scalarRangeMin = min
            self.viewSubData.scalarRangeMax = max
            self.dataToColorBarWidget()        
            self.udpateColorbar()

        except:
            print "error! input argument needs numeric string."

# set axis length
#--------------------------------------
    def setAxisLength(self, *args):
        try:
            lenX = float(args[2][0])
            lenY = float(args[2][1])
            lenZ = float(args[2][2])

            self.viewSubData.lenXaxis = lenX
            self.viewSubData.lenYaxis = lenY
            self.viewSubData.lenZaxis = lenZ
            self.dataToAxisGridWidget()
            self.viewSubData.updateAxis()
            self.glView.update()
        except:
            print "error! input argument needs numeric string."
  
# set grid scale
#--------------------------------------
    def setGridSpace(self, *args):
        try:
            spaceX = float(args[2][0])
            spaceY = float(args[2][1])
            spaceZ = float(args[2][2])

            self.viewSubData.gridSpaceX = spaceX
            self.viewSubData.gridSpaceY = spaceY
            self.viewSubData.gridSpaceZ = spaceZ
            self.dataToAxisGridWidget()
            self.viewSubData.updateGrid()
            self.glView.update()
        except:
            print "error! input argument needs numeric string."

# set output directory
#--------------------------------------
    def setOutputDirectory(self, *args):
        try:
            self.outputDirectory = args[2][0]
        except:
            print "error! input argument needs numeric string."

# Ax1 slice
#--------------------------------------
    def doSliceAx1(self, *args):
        try:
             proc   = int(args[2][0])
             pos    = args[2][1]
             delta  = float(args[2][2])
             ax2bin = float(args[2][3])
             ax3bin = float(args[2][4])

             self.ax1.setText(pos)
             self.ax1Thickness.setText(str(delta))
             self.ax2Bin.setText(str(ax2bin))
             self.ax3Bin.setText(str(ax3bin))
             self.viewMainData.basicSliceAx2bin   = ax2bin
             self.viewMainData.basicSliceAx3bin   = ax3bin

             self.doBasicSliceView2(proc)

        except:
            print "error! input argument needs numeric string."

# Ax2 slice
#--------------------------------------
    def doSliceAx2(self, *args):
        try:
             proc   = int(args[2][0])
             pos    = args[2][1]
             delta  = float(args[2][2])
             ax3bin = float(args[2][3])
             ax1bin = float(args[2][4])

             self.ax2.setText(pos)
             self.ax2Thickness.setText(str(delta))
             self.ax1Bin.setText(str(ax1bin))
             self.ax3Bin.setText(str(ax3bin))
             self.viewMainData.basicSliceAx1bin   = ax1bin
             self.viewMainData.basicSliceAx3bin   = ax3bin

             self.doBasicSliceView2(proc)

        except:
            print "error! input argument needs numeric string."

# Ax3 slice
#--------------------------------------
    def doSliceAx3(self, *args):
        try:
             proc   = int(args[2][0])
             pos    = args[2][1]
             delta  = float(args[2][2])
             ax1bin = float(args[2][3])
             ax2bin = float(args[2][4])

             self.ax3.setText(pos)
             self.ax3Thickness.setText(str(delta))
             self.ax1Bin.setText(str(ax1bin))
             self.ax2Bin.setText(str(ax2bin))
             self.viewMainData.basicSliceAx1bin   = ax1bin
             self.viewMainData.basicSliceAx2bin   = ax2bin

             self.doBasicSliceView2(proc)

        except:
            print "error! input argument needs numeric string."

# Free Slice
#--------------------------------------
    def doFreeSlice(self, *args):
        try:
             process   = int(args[2][0])
             org       = [float(args[2][1]), float(args[2][2]), float(args[2][3])]
             x         = [float(args[2][4]), float(args[2][5]), float(args[2][6])]
             y         = [float(args[2][7]), float(args[2][8]), float(args[2][9])]
             xbin      = float(args[2][10])
             ybin      = float(args[2][11])
             rangex    = [float(args[2][12]), float(args[2][13])]
             rangey    = [float(args[2][14]), float(args[2][15])]
             thickness = float(args[2][16])

             self.freeOriginX.setText(str(org[0]))
             self.freeOriginY.setText(str(org[1]))
             self.freeOriginZ.setText(str(org[2]))

             self.freeX1.setText(str(x[0]))
             self.freeX2.setText(str(x[1]))
             self.freeX3.setText(str(x[2]))

             self.freeY1.setText(str(y[0]))
             self.freeY2.setText(str(y[1]))
             self.freeY3.setText(str(y[2]))

             self.freeXbin.setText(str(xbin))
             self.freeYbin.setText(str(ybin))

             self.freeXrangeMin.setText(str(rangex[0]))
             self.freeXrangeMax.setText(str(rangex[1]))
             self.freeYrangeMin.setText(str(rangey[0]))
             self.freeYrangeMax.setText(str(rangey[1]))
             self.freeThickness.setText(str(thickness))

             self.doFreeSliceView(process)

        except:
            print "error! input argument needs numeric string."



#======================================================================================
#
# 画面構築
#
#======================================================================================    
# Horizontal and Vertical Line
#------------------------------
    def getHorizontalLine(self):
        hline = QtGui.QFrame()
        hline.setFrameShape(QtGui.QFrame.HLine)
        hline.setFrameShadow(QtGui.QFrame.Sunken)
        return hline
        
    def getVerticalLine(self):
        vline = QtGui.QFrame()
        vline.setFrameShape(QtGui.QFrame.VLine)
        vline.setFrameShadow(QtGui.QFrame.Sunken)
        return vline
        
# 3D表示画面の追加                
#-----------------
    def addGLViewWidget(self):
        self.glView = gl.GLViewWidget()
        #self.glView.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.glView.setMinimumSize(self.glViewW, self.glViewH)
        self.glView.setMaximumSize(self.glViewW, self.glViewH)
        self.glView.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.ui.mainViewLayout.addWidget(self.glView)

        spacerItem = QtGui.QSpacerItem(20, 100, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.ui.mainViewLayout.addItem(spacerItem)


        #self.glView.setBackgroundColor(255, 255, 255)
        self.glView.setBackgroundColor('k') #[inamura 180516]
        #self.glView.opts['fov'] = 1.0

# 基本3面表示スライダーウィジェットの作成
#-----------------------------------------
    def addSliceScrollBar(self):
        pass
        #self.sliceScrollWidget = QtGui.QWidget(self)
        #self.scrollL = QtGui.QVBoxLayout()

        # xscroll
        # xscrollLayout = QtGui.QHBoxLayout()        
        # self.scrollL.addLayout(xscrollLayout)
        # xscrollLabel = QtGui.QLabel("ax1")    
        # xscrollLabel.setMaximumSize(25, 30) 
        # xscrollLayout.addWidget(xscrollLabel) 

        # self.xscroll = QtGui.QScrollBar(QtCore.Qt.Horizontal, self)
        # xscrollLayout.addWidget(self.xscroll)
        # self.xscroll.setMaximum(self.viewSubData.xscrollMax)
        # self.xscroll.setPageStep(self.viewSubData.xscrollStep)
        # self.xscroll.sliderPressed.connect(self.onXSliderPressed)
        # self.xscroll.sliderReleased.connect(self.onXSliderReleased)
        # self.xscroll.actionTriggered.connect(self.onXScrollbarActionTriggered)
        # self.xscroll.valueChanged.connect(self.onXScrollbarChanged)
        
        # yscroll
        # yscrollLayout = QtGui.QHBoxLayout()        
        # self.scrollL.addLayout(yscrollLayout)
        # yscrollLabel = QtGui.QLabel("ax2")    
        # yscrollLabel.setMaximumSize(25, 30) 
        # yscrollLayout.addWidget(yscrollLabel) 

        # self.yscroll = QtGui.QScrollBar(QtCore.Qt.Horizontal, self)
        # yscrollLayout.addWidget(self.yscroll)
        # self.yscroll.setMaximum(self.viewSubData.yscrollMax)
        # self.yscroll.setPageStep(self.viewSubData.yscrollStep)
        # self.yscroll.sliderPressed.connect(self.onYSliderPressed)
        # self.yscroll.sliderReleased.connect(self.onYSliderReleased)
        # self.yscroll.actionTriggered.connect(self.onYScrollbarActionTriggered)
        # self.yscroll.valueChanged.connect(self.onYScrollbarChanged)

        # # zscroll
        # zscrollLayout = QtGui.QHBoxLayout()        
        # self.scrollL.addLayout(zscrollLayout)
        # zscrollLabel = QtGui.QLabel("ax3")    
        # zscrollLabel.setMaximumSize(25, 30) 
        # zscrollLayout.addWidget(zscrollLabel) 

        # self.zscroll = QtGui.QScrollBar(QtCore.Qt.Horizontal, self)
        # zscrollLayout.addWidget(self.zscroll)
        # self.zscroll.setMaximum(self.viewSubData.zscrollMax)
        # self.zscroll.setPageStep(self.viewSubData.zscrollStep)
        # self.zscroll.sliderPressed.connect(self.onZSliderPressed)
        # self.zscroll.sliderReleased.connect(self.onZSliderReleased)
        # self.zscroll.actionTriggered.connect(self.onZScrollbarActionTriggered)
        # self.zscroll.valueChanged.connect(self.onZScrollbarChanged)
        
        #self.sliceScrollWidget.setLayout(self.scrollL)
        #self.ui.scrollLayout.addWidget(self.sliceScrollWidget) 

### パラメータレイアウト ----------------------------------

# データ読み込み用ウィジェットの作成
#------------------------------------
    def createDataLoadWidget(self):
        self.dataLoadWidget = QtGui.QWidget(self)
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Background, QtCore.Qt.lightGray)
        self.dataLoadWidget.setAutoFillBackground(True)
        self.dataLoadWidget.setPalette(palette)

        dataGroup = QtGui.QGroupBox(self)
        dataGroup.setTitle(QtCore.QString.fromUtf8("Data"))
        groupLayout = QtGui.QVBoxLayout()
        
        #-- file path line
        groupChildLayout1 = QtGui.QHBoxLayout()
        groupLayout.addLayout(groupChildLayout1)
        fileLabel = QtGui.QLabel("File Path")
        groupChildLayout1.addWidget(fileLabel)

        self.filePath = QtGui.QLineEdit()
        self.filePath.setMinimumSize(175, 15)
        self.filePath.setMaximumSize(225, 30)
        self.filePath.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        groupChildLayout1.addWidget(self.filePath)

        fileButton = QtGui.QPushButton("...")
        fileButton.clicked.connect(self.openFileDialog)
        fileButton.setMaximumSize(30, 30)
        #fileButton.setGeometry(QtCore.QRect(0, 0, 20, 20))
        fileButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        groupChildLayout1.addWidget(fileButton)
        #fileButton.setIcon(QtGui.QStyle.standardIcon(QtGui.QStyle.SP_FileDialogStart))

        
        #-- load button line
        groupChildLayout2 = QtGui.QHBoxLayout()
        groupLayout.addLayout(groupChildLayout2)
        loadButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Load"))
        loadButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        loadButton.setMaximumSize(200, 30)        
        loadButton.clicked.connect(self.loadFile)
        loadButton.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        groupChildLayout2.addWidget(loadButton)
        
        #--
        dataGroup.setLayout(groupLayout)
        dataLoadTopLayout = QtGui.QVBoxLayout()
        dataLoadTopLayout.addWidget(dataGroup)
        self.dataLoadWidget.setLayout(dataLoadTopLayout)
        self.ui.parameterLayout.addWidget(self.dataLoadWidget) 

# Create Data Info Widget
#-----------------------------------
    def createDataInfoWidget(self):
        self.dataInfoWidget = QtGui.QWidget(self)
        self.dataInfoWidget.setMinimumSize(self.dataInfoWmin, self.dataInfoHmin)
        self.dataInfoWidget.setMaximumSize(self.dataInfoWmax, self.dataInfoHmax)
        self.dataInfoWidget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)

        self.widgets.append(self.dataInfoWidget)
#        self.dataInfoWidget.setMaximumSize(500, 800)
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Background, QtCore.Qt.lightGray)
        self.dataInfoWidget.setAutoFillBackground(True)
        self.dataInfoWidget.setPalette(palette)

        dataInfoGroup = QtGui.QGroupBox(self)
        dataInfoGroup.setTitle(QtCore.QString.fromUtf8("Data Information"))
        groupLayout = QtGui.QVBoxLayout()

        dataInfoGroup.setLayout(groupLayout)

        #
        self.dataInfo = QtGui.QTextEdit(self)
        self.dataInfo.setReadOnly(True)
        self.dataInfo.setMaximumSize(500, 500)
        self.dataInfo.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        groupLayout.addWidget(self.dataInfo)

        #--
        dataInfoTopLayout = QtGui.QVBoxLayout()
        dataInfoTopLayout.addWidget(dataInfoGroup)
        self.dataInfoWidget.setLayout(dataInfoTopLayout)
        self.ui.parameterLayout.addWidget(self.dataInfoWidget)

# 基本3面スライス用ウィジェットの作成
#-------------------------------------
    def createBasicSliceWidget(self):
        self.basicSliceWidget = QtGui.QWidget(self)
        self.basicSliceWidget.setMinimumSize(self.basicSliceWmin, self.basicSliceHmin)
        self.basicSliceWidget.setMaximumSize(self.basicSliceWmax, self.basicSliceHmax)
        self.basicSliceWidget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)

        self.widgets.append(self.basicSliceWidget)

        self.ui.parameterLayout.addWidget(self.basicSliceWidget) 
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Background, QtCore.Qt.lightGray)
        self.basicSliceWidget.setAutoFillBackground(True)
        self.basicSliceWidget.setPalette(palette)
        basicSliceTopLayout = QtGui.QVBoxLayout()
        self.basicSliceWidget.setLayout(basicSliceTopLayout)

        topGroup = QtGui.QGroupBox(self)
        topGroup.setTitle(QtCore.QString.fromUtf8("Visualize"))
        topLayout = QtGui.QVBoxLayout()
        topGroup.setLayout(topLayout)
        basicSliceTopLayout.addWidget(topGroup)

        #---- 
        editBoxW  = 60
        editBoxW2 = 100
        editBoxH = 30
        autoW = 50
        autoH = 30
        sliderW = 300
        sliderH = 30

        #---- 

        # Visualization Group
        #--------------------------------------------
        visGroup = QtGui.QGroupBox(self)
#        visGroup.setTitle(QtCore.QString.fromUtf8("View Range"))
        visGroup.setStyleSheet("QGroupBox { border: 2px solid rgb(0, 0, 0);}") 
        visTopLayout = QtGui.QVBoxLayout()
        visGroup.setLayout(visTopLayout)
        topLayout.addWidget(visGroup)

        label = QtGui.QLabel("View Range")
        label.setStyleSheet("font-weight: bold;") 
        visTopLayout.addWidget(label)

        visLayout = QtGui.QGridLayout()
        visTopLayout.addLayout(visLayout)
        rowID = 0
        label = QtGui.QLabel("From")
        label.setAlignment(QtCore.Qt.AlignCenter)
        visLayout.addWidget(label, rowID, 1) 
        label = QtGui.QLabel("To")
        label.setAlignment(QtCore.Qt.AlignCenter)
        visLayout.addWidget(label, rowID, 3) 
        label = QtGui.QLabel("Bin")
        label.setAlignment(QtCore.Qt.AlignCenter)
        visLayout.addWidget(label, rowID, 4) 
        label = QtGui.QLabel("View Scale")
        label.setAlignment(QtCore.Qt.AlignCenter)
        visLayout.addWidget(label, rowID, 6) 

        rowID += 1
        label = QtGui.QLabel("Ax1")
        label.setMaximumSize(30, editBoxH)
        label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        label.setAlignment(QtCore.Qt.AlignCenter)
        visLayout.addWidget(label, rowID, 0) 
        self.ax1From = QtGui.QLineEdit()        
        self.ax1From.setMaximumSize(editBoxW, editBoxH)
        self.ax1From.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax1From, rowID, 1)
        label = QtGui.QLabel("-")
        label.setMaximumSize(5, editBoxH)
        label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        label.setAlignment(QtCore.Qt.AlignCenter)
        visLayout.addWidget(label, rowID, 2) 
        self.ax1To = QtGui.QLineEdit()        
        self.ax1To.setMaximumSize(editBoxW, editBoxH)
        self.ax1To.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax1To, rowID, 3)
        self.ax1Bin = QtGui.QLineEdit()        
        self.ax1Bin.setMaximumSize(editBoxW, editBoxH)
        self.ax1Bin.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax1Bin, rowID, 4)
        self.ax1AutoButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Auto"))
        self.ax1AutoButton.clicked.connect(self.basicSliceAutoRangeX)
        self.ax1AutoButton.setMaximumSize(autoW, autoH)
        self.ax1AutoButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax1AutoButton, rowID, 5)
        self.ax1ViewScale = QtGui.QLineEdit()        
        self.ax1ViewScale.setMaximumSize(editBoxW, editBoxH)
        self.ax1ViewScale.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax1ViewScale, rowID, 6)

        rowID += 1
        visLayout.addWidget(QtGui.QLabel("Ax2"), rowID, 0) 
        self.ax2From = QtGui.QLineEdit()        
        self.ax2From.setMaximumSize(editBoxW, editBoxH)
        self.ax2From.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax2From, rowID, 1)
        label = QtGui.QLabel("-")
        label.setAlignment(QtCore.Qt.AlignCenter)
        visLayout.addWidget(label, rowID, 2) 
        self.ax2To = QtGui.QLineEdit()        
        self.ax2To.setMaximumSize(editBoxW, editBoxH)
        self.ax2To.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax2To, rowID, 3)
        self.ax2Bin = QtGui.QLineEdit()        
        self.ax2Bin.setMaximumSize(editBoxW, editBoxH)
        self.ax2Bin.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax2Bin, rowID, 4)
        self.ax2AutoButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Auto"))
        self.ax2AutoButton.clicked.connect(self.basicSliceAutoRangeY)
        self.ax2AutoButton.setMaximumSize(autoW, autoH)
        self.ax2AutoButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax2AutoButton, rowID, 5)
        self.ax2ViewScale = QtGui.QLineEdit()        
        self.ax2ViewScale.setMaximumSize(editBoxW, editBoxH)
        self.ax2ViewScale.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax2ViewScale, rowID, 6)

        rowID += 1
        visLayout.addWidget(QtGui.QLabel("Ax3"), rowID, 0) 
        self.ax3From = QtGui.QLineEdit()        
        self.ax3From.setMaximumSize(editBoxW, editBoxH)
        self.ax3From.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax3From, rowID, 1)
        label = QtGui.QLabel("-")
        label.setAlignment(QtCore.Qt.AlignCenter)
        visLayout.addWidget(label, rowID, 2) 
        self.ax3To = QtGui.QLineEdit()        
        self.ax3To.setMaximumSize(editBoxW, editBoxH)
        self.ax3To.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax3To, rowID, 3)
        self.ax3Bin = QtGui.QLineEdit()        
        self.ax3Bin.setMaximumSize(editBoxW, editBoxH)
        self.ax3Bin.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax3Bin, rowID, 4)
        self.ax3AutoButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Auto"))
        self.ax3AutoButton.clicked.connect(self.basicSliceAutoRangeZ)
        self.ax3AutoButton.setMaximumSize(autoW, autoH)
        self.ax3AutoButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax3AutoButton, rowID, 5)
        self.ax3ViewScale = QtGui.QLineEdit()        
        self.ax3ViewScale.setMaximumSize(editBoxW, editBoxH)
        self.ax3ViewScale.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout.addWidget(self.ax3ViewScale, rowID, 6)

        visLayout2 = QtGui.QHBoxLayout()
        visTopLayout.addLayout(visLayout2)
        visLayout2.addWidget(QtGui.QLabel("Intensity"))
        self.intensityMin = QtGui.QLineEdit()        
        self.intensityMin.setMaximumSize(70, editBoxH)
        self.intensityMin.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout2.addWidget(self.intensityMin)
        label = QtGui.QLabel("-")
        label.setMaximumSize(5, editBoxH)
        label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        label.setAlignment(QtCore.Qt.AlignCenter)
        visLayout2.addWidget(label)
        self.intensityMax = QtGui.QLineEdit()        
        self.intensityMax.setMaximumSize(70, editBoxH)
        self.intensityMax.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout2.addWidget(self.intensityMax)
        self.intensityAutoButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Auto"))
        self.intensityAutoButton.clicked.connect(self.basicSliceAutoIntensity)
        self.intensityAutoButton.setMaximumSize(autoW, autoH)
        self.intensityAutoButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        visLayout2.addWidget(self.intensityAutoButton)
        spacerItem = QtGui.QSpacerItem(165, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
        visLayout2.addItem(spacerItem)

        visLayout3 = QtGui.QHBoxLayout()  
        visTopLayout.addLayout(visLayout3)      
        self.logscaleCheck = QtGui.QCheckBox("Log-scale")
        visLayout3.addWidget(self.logscaleCheck)
        spacerItem = QtGui.QSpacerItem(75, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
        visLayout3.addItem(spacerItem)
        
        # Color Map

        #colorMapLabel = QtGui.QLabel(QtCore.QString.fromUtf8("Color Map"))
        #visLayout4.addWidget(colorMapLabel)
        visLayout3.addWidget(QtGui.QLabel("Color map"))
        self.colorMapCombo2 = QtGui.QComboBox(self)
        self.colorMapCombo2.setMaximumSize(80, editBoxH)
        self.colorMapCombo2.addItem(self.colorBarPreset_default) #[inamura 180516]self.colorBarPreset_haxby
        self.colorMapCombo2.addItem(self.colorBarPreset_haxby) #[inamura 180516]
        self.colorMapCombo2.addItem("cyclic")
        self.colorMapCombo2.addItem("spectrum")
        self.colorMapCombo2.addItem("thermal")
        self.colorMapCombo2.addItem("flame")
        self.colorMapCombo2.addItem("yellowy")
        self.colorMapCombo2.addItem("bipolar")
        self.colorMapCombo2.addItem("greyclip")
        self.colorMapCombo2.addItem("grey")
        visLayout3.addWidget(self.colorMapCombo2)
 #       spacerItem = QtGui.QSpacerItem(75, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
#        visLayout3.addItem(spacerItem)
        self.basicSliceVisApplyButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Apply"))

        self.basicSliceVisApplyButton.clicked.connect(self.onClickViewRangeApplyButton)

        # self.basicSliceVisApplyButton.clicked.connect(self.widgetToDataForBasicSliceViewRange)
        # self.basicSliceVisApplyButton.clicked.connect(self.updateColorBar)
        # self.basicSliceVisApplyButton.clicked.connect(self.updateAxisSize)
        # self.basicSliceVisApplyButton.clicked.connect(self.updateGridSize)
        # self.basicSliceVisApplyButton.clicked.connect(self.updateAxisGrid)
        self.basicSliceVisApplyButton.setMaximumSize(80, editBoxH * 2)
        visLayout3.addWidget(self.basicSliceVisApplyButton)
       
        # Slice Plane Group
        #--------------------------------------------
        sliceTopLayout = QtGui.QGridLayout()
        topLayout.addLayout(sliceTopLayout)

        ### Ax1-Ax2
        rowID = 0
        slice12Group = QtGui.QGroupBox(self)
#        slice12Group.setStyleSheet("QGroupBox {background-color: rgb(255, 255, 0); border: 2px solid rgb(0, 0, 0);}") 
        slice12Group.setStyleSheet("QGroupBox { border: 2px solid rgb(0, 0, 0);}") 
#        slice12Group.setTitle(QtCore.QString.fromUtf8("Ax1-Ax2 plane"))
        slice12Group.setTitle(QtCore.QString.fromUtf8(""))
        slice12TopLayout = QtGui.QVBoxLayout()
        slice12Group.setLayout(slice12TopLayout)
        sliceTopLayout.addWidget(slice12Group, rowID, 0)

        slice12Layout0 = QtGui.QHBoxLayout()
        slice12TopLayout.addLayout(slice12Layout0) 
        self.ax1ax2PlaneViewCheck = QtGui.QCheckBox("Ax1-Ax2 plane")
        self.ax1ax2PlaneViewCheck.clicked.connect(self.enableControl)
        self.ax1ax2PlaneViewCheck.clicked.connect(self.dataToGLViewItemVisibility)
        self.ax1ax2PlaneViewCheck.clicked.connect(self.basicSlicePlaneTodata)

        slice12Layout0.addWidget(self.ax1ax2PlaneViewCheck)

        slice12Layout1 = QtGui.QHBoxLayout()
        slice12TopLayout.addLayout(slice12Layout1) 
        slice12Layout1.addWidget(QtGui.QLabel("Ax3"))
        self.ax3 = QtGui.QLineEdit()
        self.ax3.setMaximumSize(editBoxW2, editBoxH)
        self.ax3.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        slice12Layout1.addWidget(self.ax3)
        slice12Layout1.addWidget(QtGui.QLabel(QtCore.QString.fromUtf8("Δ Ax3")))
        self.ax3Thickness = QtGui.QLineEdit()
        self.ax3Thickness.setMaximumSize(editBoxW, editBoxH)
        self.ax3Thickness.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        slice12Layout1.addWidget(self.ax3Thickness)
        spacerItem = QtGui.QSpacerItem(125, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
        slice12Layout1.addItem(spacerItem)

        # zscroll
        slice12Layout2 = QtGui.QHBoxLayout()
        slice12TopLayout.addLayout(slice12Layout2) 
        self.zscroll = QtGui.QScrollBar(QtCore.Qt.Horizontal, self)
        slice12Layout2.addWidget(self.zscroll)
        self.zscroll.setMaximumSize(sliderW, sliderH)
#        self.zscroll.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.zscroll.setMaximum(self.viewSubData.xscrollMax)
        self.zscroll.setPageStep(self.viewSubData.xscrollStep)
        self.zscroll.sliderPressed.connect(self.onZSliderPressed)
        self.zscroll.sliderReleased.connect(self.onZSliderReleased)
        self.zscroll.actionTriggered.connect(self.onZScrollbarActionTriggered)
        self.zscroll.valueChanged.connect(self.onZScrollbarChanged)

        ### Ax2-Ax3
        rowID += 1
        slice23Group = QtGui.QGroupBox(self)
        slice23Group.setStyleSheet("QGroupBox { border: 2px solid rgb(0, 0, 0);}") 
#        slice23Group.setTitle(QtCore.QString.fromUtf8("Ax2-Ax3 plane"))
        slice23Group.setTitle(QtCore.QString.fromUtf8(""))
        slice23TopLayout = QtGui.QVBoxLayout()
        slice23Group.setLayout(slice23TopLayout)
        sliceTopLayout.addWidget(slice23Group, rowID, 0)

        slice23Layout0 = QtGui.QHBoxLayout()
        slice23TopLayout.addLayout(slice23Layout0) 
        self.ax2ax3PlaneViewCheck = QtGui.QCheckBox("Ax2-Ax3 plane")
        self.ax2ax3PlaneViewCheck.clicked.connect(self.enableControl)
        self.ax2ax3PlaneViewCheck.clicked.connect(self.dataToGLViewItemVisibility)
        self.ax2ax3PlaneViewCheck.clicked.connect(self.basicSlicePlaneTodata)

        slice23Layout0.addWidget(self.ax2ax3PlaneViewCheck)

        slice23Layout1 = QtGui.QHBoxLayout()
        slice23TopLayout.addLayout(slice23Layout1) 
        slice23Layout1.addWidget(QtGui.QLabel("Ax1"))
        self.ax1 = QtGui.QLineEdit()
        self.ax1.setMaximumSize(editBoxW2, editBoxH)
        self.ax1.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        slice23Layout1.addWidget(self.ax1)
        slice23Layout1.addWidget(QtGui.QLabel(QtCore.QString.fromUtf8("Δ Ax1")))
        self.ax1Thickness = QtGui.QLineEdit()
        self.ax1Thickness.setMaximumSize(editBoxW, editBoxH)
        self.ax1Thickness.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        slice23Layout1.addWidget(self.ax1Thickness)
        spacerItem = QtGui.QSpacerItem(125, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
        slice23Layout1.addItem(spacerItem)

        # xscroll
        slice23Layout2 = QtGui.QHBoxLayout()
        slice23TopLayout.addLayout(slice23Layout2) 
        self.xscroll = QtGui.QScrollBar(QtCore.Qt.Horizontal, self)
        slice23Layout2.addWidget(self.xscroll)
        self.xscroll.setMaximumSize(sliderW, sliderH)
#        self.xscroll.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.xscroll.setMaximum(self.viewSubData.xscrollMax)
        self.xscroll.setPageStep(self.viewSubData.xscrollStep)
        self.xscroll.sliderPressed.connect(self.onXSliderPressed)
        self.xscroll.sliderReleased.connect(self.onXSliderReleased)
        self.xscroll.actionTriggered.connect(self.onXScrollbarActionTriggered)
        self.xscroll.valueChanged.connect(self.onXScrollbarChanged)

        self.basicSliceApplyButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Apply"))
        self.basicSliceApplyButton.clicked.connect(self.doBasicSliceView)
        self.basicSliceApplyButton.clicked.connect(self.updateAxisLabel)
        self.basicSliceApplyButton.setMaximumSize(60, editBoxH)
        self.basicSliceApplyButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sliceTopLayout.addWidget(self.basicSliceApplyButton, rowID, 1)

        ### Ax3-Ax1
        rowID += 1
        slice31Group = QtGui.QGroupBox(self)
        slice31Group.setStyleSheet("QGroupBox { border: 2px solid rgb(0, 0, 0);}") 
        #slice31Group.setTitle(QtCore.QString.fromUtf8("Ax3-Ax1 plane"))
        slice31Group.setTitle(QtCore.QString.fromUtf8(""))
        slice31TopLayout = QtGui.QVBoxLayout()
        slice31Group.setLayout(slice31TopLayout)
        sliceTopLayout.addWidget(slice31Group, rowID, 0)

        slice31Layout0 = QtGui.QHBoxLayout()
        slice31TopLayout.addLayout(slice31Layout0) 
        self.ax3ax1PlaneViewCheck = QtGui.QCheckBox("Ax3-Ax1 plane")
        self.ax3ax1PlaneViewCheck.clicked.connect(self.enableControl)
        self.ax3ax1PlaneViewCheck.clicked.connect(self.dataToGLViewItemVisibility)
        self.ax3ax1PlaneViewCheck.clicked.connect(self.basicSlicePlaneTodata)

        slice31Layout0.addWidget(self.ax3ax1PlaneViewCheck)

        slice31Layout1 = QtGui.QHBoxLayout()
        slice31TopLayout.addLayout(slice31Layout1) 
        slice31Layout1.addWidget(QtGui.QLabel("Ax2"))
        self.ax2 = QtGui.QLineEdit()
        self.ax2.setMaximumSize(editBoxW2, editBoxH)
        self.ax2.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        slice31Layout1.addWidget(self.ax2)
        slice31Layout1.addWidget(QtGui.QLabel(QtCore.QString.fromUtf8("Δ Ax2")))
        self.ax2Thickness = QtGui.QLineEdit()
        self.ax2Thickness.setMaximumSize(editBoxW, editBoxH)
        self.ax2Thickness.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        slice31Layout1.addWidget(self.ax2Thickness)
        spacerItem = QtGui.QSpacerItem(125, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
        slice31Layout1.addItem(spacerItem)

        # yscroll
        slice31Layout2 = QtGui.QHBoxLayout()
        slice31TopLayout.addLayout(slice31Layout2) 
        self.yscroll = QtGui.QScrollBar(QtCore.Qt.Horizontal, self)
        slice31Layout2.addWidget(self.yscroll)
        self.yscroll.setMaximumSize(sliderW, sliderH)
 #       self.yscroll.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.yscroll.setMaximum(self.viewSubData.xscrollMax)
        self.yscroll.setPageStep(self.viewSubData.xscrollStep)
        self.yscroll.sliderPressed.connect(self.onYSliderPressed)
        self.yscroll.sliderReleased.connect(self.onYSliderReleased)
        self.yscroll.actionTriggered.connect(self.onYScrollbarActionTriggered)
        self.yscroll.valueChanged.connect(self.onYScrollbarChanged)


        self.basicSliceStopButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Stop"))
        self.basicSliceStopButton.clicked.connect(self.cancelBasicSliceView)
        self.basicSliceStopButton.setMaximumSize(60, editBoxH)
        self.basicSliceStopButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sliceTopLayout.addWidget(self.basicSliceStopButton, rowID, 1)

        # Output
        #-----------------------------
        outputGroup = QtGui.QGroupBox(self)
#        outputGroup.setTitle(QtCore.QString.fromUtf8("Slice"))
        outputGroup.setStyleSheet("QGroupBox { border: 2px solid rgb(0, 0, 0);}") 
        outputTopLayout = QtGui.QVBoxLayout()
        outputGroup.setLayout(outputTopLayout)
        topLayout.addWidget(outputGroup)

        label = QtGui.QLabel("Slice")
        label.setStyleSheet("font-weight: bold;") 
        outputTopLayout.addWidget(label)
        outputLayout = QtGui.QVBoxLayout()
        outputTopLayout.addLayout(outputLayout)

        outputLayout1 = QtGui.QHBoxLayout()
        outputTopLayout.addLayout(outputLayout1)

        self.slicePlane = QtGui.QComboBox(self)
        self.slicePlane.setMaximumSize(90, editBoxH)
        self.slicePlane.addItem("Ax1-Ax2")
        self.slicePlane.addItem("Ax2-Ax3")
        self.slicePlane.addItem("Ax3-Ax1")
        outputLayout1.addWidget(self.slicePlane)
 
        self.M2plotButton = QtGui.QPushButton(QtCore.QString.fromUtf8("M2Plot"))
        self.M2plotButton.clicked.connect(self.doBasicSliceView)
        outputLayout1.addWidget(self.M2plotButton)

        outputLayout1b = QtGui.QVBoxLayout()
        outputLayout1.addLayout(outputLayout1b)

#        self.saveImageButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Save As Image"))
#        self.saveImageButton.clicked.connect(self.doBasicSliceView)
#        outputLayout1b.addWidget(self.saveImageButton)
        self.saveECAButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Save As ECA"))
        self.saveECAButton.clicked.connect(self.doBasicSliceView)
        outputLayout1b.addWidget(self.saveECAButton)

    def createBasicSliceWidget_Old(self):
        self.basicSliceWidget = QtGui.QWidget(self)
        self.widgets.append(self.basicSliceWidget)
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Background, QtCore.Qt.lightGray)
        self.basicSliceWidget.setAutoFillBackground(True)
        self.basicSliceWidget.setPalette(palette)

        sliceGroup = QtGui.QGroupBox(self)
        sliceGroup.setTitle(QtCore.QString.fromUtf8("Visualize"))
        groupLayout = QtGui.QVBoxLayout()
        sliceGroup.setLayout(groupLayout)

        #-- ax1 -------------------------
        ax1Group = QtGui.QGroupBox(self)
        ax1Group.setTitle(QtCore.QString.fromUtf8("Ax2-Ax3"))
        groupLayout.addWidget(ax1Group)
        ax1Layout = QtGui.QVBoxLayout()
        ax1Group.setLayout(ax1Layout)

        #*  表示, 軸名
        ax1ChildLayout1 = QtGui.QHBoxLayout()
        ax1Layout.addLayout(ax1ChildLayout1)
        self.ax1ViewCheck = QtGui.QCheckBox("Visible")
        self.ax1ViewCheck.clicked.connect(self.widgetToData)
        self.ax1ViewCheck.clicked.connect(self.enableControl)
        self.ax1ViewCheck.clicked.connect(self.dataToGLViewItemVisibility)
        ax1ChildLayout1.addWidget(self.ax1ViewCheck)

        # ax1 label
        ax1TitleLabel = QtGui.QLabel("ax1 Title")
        ax1ChildLayout1.addWidget(ax1TitleLabel)
        self.ax1Title = QtGui.QLineEdit()
        self.ax1Title.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        ax1ChildLayout1.addWidget(self.ax1Title)

        #*  ax1 bin
        ax1ChildLayout2 = QtGui.QHBoxLayout()
        ax1Layout.addLayout(ax1ChildLayout2)
        
        ax1Label = QtGui.QLabel("ax1")
        ax1ChildLayout2.addWidget(ax1Label)
        self.ax1 = QtGui.QLineEdit()
        self.ax1.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        ax1ChildLayout2.addWidget(self.ax1)

        ax1ThicknessLabel = QtGui.QLabel(QtCore.QString.fromUtf8("Δ ax1"))
        ax1ChildLayout2.addWidget(ax1ThicknessLabel)
        self.ax1Thickness = QtGui.QLineEdit()
        self.ax1Thickness.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        ax1ChildLayout2.addWidget(self.ax1Thickness)            

        #-- Apply M2Plot, Save as EC, text, Save as Image
        ax1ButtonLayout = QtGui.QHBoxLayout()        
        ax1Layout.addLayout(ax1ButtonLayout)
        
        ax1ButtonChildLayout = QtGui.QGridLayout()
        ax1ButtonLayout.addLayout(ax1ButtonChildLayout)
        rowID = 0
        colID = 0
        #-- Applyボタン
        self.ax1ExeButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Apply"))
        #self.ax1ExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/3d_effect.png")))          
        self.ax1ExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"3d_effect.png")))) #[inamura 160920]
        #self.ax1ExeButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax1ExeButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax1ExeButton.setMaximumSize(200, 30)
        self.ax1ExeButton.clicked.connect(self.widgetToData)
        self.ax1ExeButton.clicked.connect(self.doBasicSliceView)
        self.ax1ExeButton.clicked.connect(self.updateAxisLabel)
        ax1ButtonChildLayout.addWidget(self.ax1ExeButton, rowID, colID)        

        colID += 1
        # M2Plot
        self.ax1M2plotButton = QtGui.QPushButton(QtCore.QString.fromUtf8("M2Plot"))
        #self.ax1M2plotButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/plotchart.png")))        
        self.ax1M2plotButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"plotchart.png")))) #[inamura 160920]
        #self.ax1M2plotButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax1M2plotButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax1M2plotButton.setMaximumSize(200, 30)
        self.ax1M2plotButton.clicked.connect(self.widgetToData)
        self.ax1M2plotButton.clicked.connect(self.doBasicSliceView)
        self.ax1M2plotButton.clicked.connect(self.updateAxisLabel)
        ax1ButtonChildLayout.addWidget(self.ax1M2plotButton, rowID, colID)

        rowID = 1
        colID = 0
        # Save as ECA
        self.ax1SaveECAButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Save as ECA"))
        #self.ax1SaveECAButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/1_030.png")))
        self.ax1SaveECAButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"1_030.png")))) #[inamura 160920]
        #self.ax1SaveECAButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax1SaveECAButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax1SaveECAButton.setMaximumSize(200, 30)
        self.ax1SaveECAButton.clicked.connect(self.widgetToData)
        self.ax1SaveECAButton.clicked.connect(self.doBasicSliceView)
        self.ax1SaveECAButton.clicked.connect(self.updateAxisLabel)
        ax1ButtonChildLayout.addWidget(self.ax1SaveECAButton, rowID, colID)          

        colID += 1
        # Save as Image
        self.ax1SaveButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Save as Image"))
        #self.ax1SaveButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/childish_Image.png")))
        self.ax1SaveButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"childish_Image.png")))) #[inamura 160920]
        #self.ax1SaveButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax1SaveButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax1SaveButton.setMaximumSize(200, 30)
        self.ax1SaveButton.clicked.connect(self.widgetToData)
        self.ax1SaveButton.clicked.connect(self.doBasicSliceView)
        self.ax1SaveButton.clicked.connect(self.updateAxisLabel)
        ax1ButtonChildLayout.addWidget(self.ax1SaveButton, rowID, colID)         
       
        # Cancel
        self.ax1CancelButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Stop"))
        #self.ax1CancelButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/stop.png")))
        self.ax1CancelButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"stop.png")))) #[inamura 160920]
        #self.ax1CancelButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax1CancelButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax1CancelButton.setMaximumSize(200, 30)
        self.ax1CancelButton.clicked.connect(self.cancelBasicSliceView)
        ax1ButtonLayout.addWidget(self.ax1CancelButton)
        
        #-- ax2 -------------------------
        ax2Group = QtGui.QGroupBox(self)
        ax2Group.setTitle(QtCore.QString.fromUtf8("ax2"))
        groupLayout.addWidget(ax2Group)
        ax2Layout = QtGui.QVBoxLayout()
        ax2Group.setLayout(ax2Layout)
        
        #*  表示, 軸名
        ax2ChildLayout1 = QtGui.QHBoxLayout()
        ax2Layout.addLayout(ax2ChildLayout1)
        self.ax2ViewCheck = QtGui.QCheckBox("Visible")
        self.ax2ViewCheck.clicked.connect(self.widgetToData)
        self.ax2ViewCheck.clicked.connect(self.enableControl)
        self.ax2ViewCheck.clicked.connect(self.dataToGLViewItemVisibility)
        ax2ChildLayout1.addWidget(self.ax2ViewCheck)

        # ax2 label
        ax2TitleLabel = QtGui.QLabel("ax2 Title")
        ax2ChildLayout1.addWidget(ax2TitleLabel)
        self.ax2Title = QtGui.QLineEdit()
        self.ax2Title.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        ax2ChildLayout1.addWidget(self.ax2Title)
        
        #*  ax2 bin
        ax2ChildLayout2 = QtGui.QHBoxLayout()
        ax2Layout.addLayout(ax2ChildLayout2)
        
        ax2Label = QtGui.QLabel("ax2")
        ax2ChildLayout2.addWidget(ax2Label)
        self.ax2 = QtGui.QLineEdit()
        self.ax2.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        ax2ChildLayout2.addWidget(self.ax2)

        ax2ThicknessLabel = QtGui.QLabel(QtCore.QString.fromUtf8("Δ ax2"))
        ax2ChildLayout2.addWidget(ax2ThicknessLabel)
        self.ax2Thickness = QtGui.QLineEdit()
        self.ax2Thickness.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        ax2ChildLayout2.addWidget(self.ax2Thickness)            
        
        
        #-- M2Plot, Save as EC, text, Save as Image
        ax2ButtonLayout = QtGui.QHBoxLayout()        
        ax2Layout.addLayout(ax2ButtonLayout)
        
        ax2ButtonChildLayout = QtGui.QGridLayout()
        ax2ButtonLayout.addLayout(ax2ButtonChildLayout)
        rowID = 0
        colID = 0
        #-- Applyボタン
        self.ax2ExeButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Apply"))
        #self.ax2ExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/3d_effect.png")))          
        self.ax2ExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"3d_effect.png")))) #[inamura 160920]
        #self.ax2ExeButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax2ExeButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax2ExeButton.setMaximumSize(200, 30)
        self.ax2ExeButton.clicked.connect(self.widgetToData)
        self.ax2ExeButton.clicked.connect(self.doBasicSliceView)
        self.ax2ExeButton.clicked.connect(self.updateAxisLabel)
        ax2ButtonChildLayout.addWidget(self.ax2ExeButton, rowID, colID)        

        colID += 1
        # M2Plot
        self.ax2M2plotButton = QtGui.QPushButton(QtCore.QString.fromUtf8("M2Plot"))
        #self.ax2M2plotButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/plotchart.png")))        
        self.ax2M2plotButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"plotchart.png")))) #[inamura 160920]
        #self.ax2M2plotButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax2M2plotButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax2M2plotButton.setMaximumSize(200, 30)
        self.ax2M2plotButton.clicked.connect(self.widgetToData)
        self.ax2M2plotButton.clicked.connect(self.doBasicSliceView)
        self.ax2M2plotButton.clicked.connect(self.updateAxisLabel)
        ax2ButtonChildLayout.addWidget(self.ax2M2plotButton, rowID, colID)

        rowID = 1
        colID = 0
        # Save as ECA
        self.ax2SaveECAButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Save as ECA"))
        #self.ax2SaveECAButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/1_030.png")))
        self.ax2SaveECAButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"1_030.png")))) #[inamura 160920]
        #self.ax2SaveECAButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax2SaveECAButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax2SaveECAButton.setMaximumSize(200, 30)
        self.ax2SaveECAButton.clicked.connect(self.widgetToData)
        self.ax2SaveECAButton.clicked.connect(self.doBasicSliceView)
        self.ax2SaveECAButton.clicked.connect(self.updateAxisLabel)
        ax2ButtonChildLayout.addWidget(self.ax2SaveECAButton, rowID, colID)          

        colID += 1
        # Save as Image
        self.ax2SaveButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Save as Image"))
        #self.ax2SaveButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/childish_Image.png")))
        self.ax2SaveButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"childish_Image.png")))) #[inamura 160920]
        #self.ax2SaveButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax2SaveButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax2SaveButton.setMaximumSize(200, 30)
        self.ax2SaveButton.clicked.connect(self.widgetToData)
        self.ax2SaveButton.clicked.connect(self.doBasicSliceView)
        self.ax2SaveButton.clicked.connect(self.updateAxisLabel)
        ax2ButtonChildLayout.addWidget(self.ax2SaveButton, rowID, colID)         
        
        
        # Cancel
        self.ax2CancelButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Stop"))
        #self.ax2CancelButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/stop.png")))
        self.ax2CancelButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"stop.png")))) #[inamura 160920]
        #self.ax2CancelButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax2CancelButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax2CancelButton.setMaximumSize(200, 30)
        self.ax2CancelButton.clicked.connect(self.cancelBasicSliceView)
        ax2ButtonLayout.addWidget(self.ax2CancelButton)
        
        #-- ax3 -------------------------
        ax3Group = QtGui.QGroupBox(self)
        ax3Group.setTitle(QtCore.QString.fromUtf8("ax3"))
        groupLayout.addWidget(ax3Group)
        ax3Layout = QtGui.QVBoxLayout()
        ax3Group.setLayout(ax3Layout)
        
        #*  表示, 軸名
        ax3ChildLayout1 = QtGui.QHBoxLayout()
        ax3Layout.addLayout(ax3ChildLayout1)
        self.ax3ViewCheck = QtGui.QCheckBox("Visible")
        self.ax3ViewCheck.clicked.connect(self.widgetToData)
        self.ax3ViewCheck.clicked.connect(self.enableControl)
        self.ax3ViewCheck.clicked.connect(self.dataToGLViewItemVisibility)
        ax3ChildLayout1.addWidget(self.ax3ViewCheck)

        # ax3 label
        ax3TitleLabel = QtGui.QLabel("ax3 Title")
        ax3ChildLayout1.addWidget(ax3TitleLabel)
        self.ax3Title = QtGui.QLineEdit()
        self.ax3Title.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        ax3ChildLayout1.addWidget(self.ax3Title)
        
        #*  ax3 bin
        ax3ChildLayout2 = QtGui.QHBoxLayout()
        ax3Layout.addLayout(ax3ChildLayout2)
        
        ax3Label = QtGui.QLabel("ax3")
        ax3ChildLayout2.addWidget(ax3Label)
        self.ax3 = QtGui.QLineEdit()
        self.ax3.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        ax3ChildLayout2.addWidget(self.ax3)

        ax3ThicknessLabel = QtGui.QLabel(QtCore.QString.fromUtf8("Δ ax3"))
        ax3ChildLayout2.addWidget(ax3ThicknessLabel)
        self.ax3Thickness = QtGui.QLineEdit()
        self.ax3Thickness.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        ax3ChildLayout2.addWidget(self.ax3Thickness)            
        
        
        #-- M2Plot, Save as EC, text, Save as Image
        ax3ButtonLayout = QtGui.QHBoxLayout()        
        ax3Layout.addLayout(ax3ButtonLayout)
        
        ax3ButtonChildLayout = QtGui.QGridLayout()
        ax3ButtonLayout.addLayout(ax3ButtonChildLayout)
        rowID = 0
        colID = 0
        #-- Applyボタン
        self.ax3ExeButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Apply"))
        #self.ax3ExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/3d_effect.png")))
        self.ax3ExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"3d_effect.png")))) #[inamura 160920]
        #self.ax3ExeButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax3ExeButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax3ExeButton.setMaximumSize(200, 30)
        self.ax3ExeButton.clicked.connect(self.widgetToData)
        self.ax3ExeButton.clicked.connect(self.doBasicSliceView)
        self.ax3ExeButton.clicked.connect(self.updateAxisLabel)
        ax3ButtonChildLayout.addWidget(self.ax3ExeButton, rowID, colID)        

        colID += 1
        # M2Plot
        self.ax3M2plotButton = QtGui.QPushButton(QtCore.QString.fromUtf8("M2Plot"))
        #self.ax3M2plotButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/plotchart.png")))        
        self.ax3M2plotButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"plotchart.png")))) #[inamura 160920]
        #self.ax3M2plotButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax3M2plotButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax3M2plotButton.setMaximumSize(200, 30)
        self.ax3M2plotButton.clicked.connect(self.widgetToData)
        self.ax3M2plotButton.clicked.connect(self.doBasicSliceView)
        self.ax3M2plotButton.clicked.connect(self.updateAxisLabel)
        ax3ButtonChildLayout.addWidget(self.ax3M2plotButton, rowID, colID)

        rowID = 1
        colID = 0
        # Save as ECA
        self.ax3SaveECAButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Save as ECA"))
        #self.ax3SaveECAButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/1_030.png")))
        self.ax3SaveECAButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"1_030.png")))) #[inamura 160920]
        #self.ax3SaveECAButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax3SaveECAButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax3SaveECAButton.setMaximumSize(200, 30)
        self.ax3SaveECAButton.clicked.connect(self.widgetToData)
        self.ax3SaveECAButton.clicked.connect(self.doBasicSliceView)
        self.ax3SaveECAButton.clicked.connect(self.updateAxisLabel)
        ax3ButtonChildLayout.addWidget(self.ax3SaveECAButton, rowID, colID)          

        colID += 1
        # Save as Image
        self.ax3SaveButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Save as Image"))
        #self.ax3SaveButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/childish_Image.png")))
        self.ax3SaveButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"childish_Image.png")))) #[inamura 160920]
        #self.ax3SaveButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax3SaveButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax3SaveButton.setMaximumSize(200, 30)
        self.ax3SaveButton.clicked.connect(self.widgetToData)
        self.ax3SaveButton.clicked.connect(self.doBasicSliceView)
        self.ax3SaveButton.clicked.connect(self.updateAxisLabel)
        ax3ButtonChildLayout.addWidget(self.ax3SaveButton, rowID, colID)         
        
        # Cancel
        self.ax3CancelButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Stop"))
        #self.ax3CancelButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/stop.png")))
        self.ax3CancelButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"stop.png")))) #[inamura 160920]          
        #self.ax3CancelButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.ax3CancelButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax3CancelButton.setMaximumSize(200, 30)
        self.ax3CancelButton.clicked.connect(self.cancelBasicSliceView)
        ax3ButtonLayout.addWidget(self.ax3CancelButton)     
        
        #---
        # ax3 bin
        binLayout = QtGui.QHBoxLayout()
        groupLayout.addLayout(binLayout)
        
        ax1BinLabel = QtGui.QLabel("ax1 bin")
        binLayout.addWidget(ax1BinLabel)
        self.ax1Bin = QtGui.QLineEdit()
        self.ax1Bin.setMaximumSize(75, 30)
        self.ax1Bin.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        binLayout.addWidget(self.ax1Bin)
  
        ax2BinLabel = QtGui.QLabel("ax2 bin")
        binLayout.addWidget(ax2BinLabel)
        self.ax2Bin = QtGui.QLineEdit()
        self.ax2Bin.setMaximumSize(75, 30)
        self.ax2Bin.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        binLayout.addWidget(self.ax2Bin)
        
        ax3BinLabel = QtGui.QLabel("ax3 bin")
        binLayout.addWidget(ax3BinLabel)
        self.ax3Bin = QtGui.QLineEdit()
        self.ax3Bin.setMaximumSize(75, 30)
        self.ax3Bin.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        binLayout.addWidget(self.ax3Bin)
        
        #-----
        sliceGroup.setLayout(groupLayout)
        
        basicSliceTopLayout = QtGui.QVBoxLayout()
        basicSliceTopLayout.addWidget(sliceGroup)
        self.basicSliceWidget.setLayout(basicSliceTopLayout)
        self.ui.parameterLayout.addWidget(self.basicSliceWidget) 

# 任意面スライス用ウィジェットの作成
#-----------------------------------
    def createFreeSliceWidget(self):
        self.freeSliceWidget = QtGui.QWidget(self)
        self.freeSliceWidget.setMinimumSize(self.freeSliceWmin, self.freeSliceHmin)
        self.freeSliceWidget.setMaximumSize(self.freeSliceWmax, self.freeSliceHmax)
        self.freeSliceWidget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)

        self.widgets.append(self.freeSliceWidget)
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Background, QtCore.Qt.lightGray)
        self.freeSliceWidget.setAutoFillBackground(True)
        self.freeSliceWidget.setPalette(palette)

        freeSliceGroup      = QtGui.QGroupBox(self)
        freeSliceGroup.setTitle(QtCore.QString.fromUtf8("Free Slice"))
        #freeSliceGroup.setStyleSheet("QGroupBox { color: blue}");        
        groupLayout = QtGui.QVBoxLayout()
        freeSliceGroup.setLayout(groupLayout)
        
        sliceGroup = QtGui.QGroupBox(self)
#        visGroup.setTitle(QtCore.QString.fromUtf8("View Range"))
        sliceGroup.setStyleSheet("QGroupBox { border: 2px solid rgb(0, 0, 0);}") 
        sliceTopLayout = QtGui.QVBoxLayout()
        sliceGroup.setLayout(sliceTopLayout)
        groupLayout.addWidget(sliceGroup)

        label = QtGui.QLabel("Slice")
        label.setStyleSheet("font-weight: bold;") 
        sliceTopLayout.addWidget(label)

        #*  表示, 軸名
        self.freeSliceViewCheck = QtGui.QCheckBox("Visible")
        self.freeSliceViewCheck.clicked.connect(self.enableControl)
        self.freeSliceViewCheck.clicked.connect(self.dataToGLViewItemVisibility)
        self.ax1ax2PlaneViewCheck.clicked.connect(self.freeSlicePlaneTodata)


        sliceTopLayout.addWidget(self.freeSliceViewCheck)

        # select method
        #planeGroup = QtGui.QGroupBox(self)
        #palette = QtGui.QPalette()
        #palette.setColor(QtGui.QPalette.Disabled , Qt.red)
        #palette.setColor(planeGroup.backgroundRole(), QtGui.QColor(0,255,255))
        #planeGroup.setPalette(palette)
        #planeGroup.setStyleSheet("QGroupBox {border: 1px solid gray}");

        # planeGroup.setTitle(QtCore.QString.fromUtf8("Plane Setting"))
        # groupLayout.addWidget(planeGroup)
        # planeRadioLayout = QtGui.QHBoxLayout()
        # planeGroup.setLayout(planeRadioLayout)

        # self.normalVecRadio = QtGui.QRadioButton("Normal Vector + Origin")
        # planeRadioLayout.addWidget(self.normalVecRadio)
        # self.normalVecRadio.toggled.connect(self.enableControl)
        # self.vecVecRadio = QtGui.QRadioButton("Vector + Vector")
        # planeRadioLayout.addWidget(self.vecVecRadio)
        # self.vecVecRadio.toggled.connect(self.enableControl)
        
        # methodGroup = QtGui.QButtonGroup(self.freeSliceWidget)
        # methodGroup.addButton(self.normalVecRadio)
        # methodGroup.addButton(self.vecVecRadio)

        ### Normal Vector + Origin ###
        # Normal Vector
        # normalVecLayout = QtGui.QHBoxLayout()
        # groupLayout.addLayout(normalVecLayout)        
        # normVecLabel = QtGui.QLabel("Normal Vector")
        # normalVecLayout.addWidget(normVecLabel)

        # self.normVecX = QtGui.QLineEdit()
        # self.normVecX.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        # self.normVecX.setMaximumSize(QtCore.QSize(75, 20))
        # normalVecLayout.addWidget(self.normVecX)

        # self.normVecY = QtGui.QLineEdit()
        # self.normVecY.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        # self.normVecY.setMaximumSize(QtCore.QSize(75, 20))        
        # normalVecLayout.addWidget(self.normVecY)

        # self.normVecZ = QtGui.QLineEdit()
        # self.normVecZ.setMaximumSize(QtCore.QSize(75, 20))        
        # self.normVecZ.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        # normalVecLayout.addWidget(self.normVecZ)
        
        # Origin
        originLayout = QtGui.QHBoxLayout()
        sliceTopLayout.addLayout(originLayout)             
        originLabel = QtGui.QLabel("Origin")
        originLayout.addWidget(originLabel)

        self.freeOriginX = QtGui.QLineEdit()
        self.freeOriginX.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeOriginX.setMaximumSize(QtCore.QSize(75, 20))
        originLayout.addWidget(self.freeOriginX)

        self.freeOriginY = QtGui.QLineEdit()
        self.freeOriginY.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeOriginY.setMaximumSize(QtCore.QSize(75, 20))        
        originLayout.addWidget(self.freeOriginY)

        self.freeOriginZ = QtGui.QLineEdit()
        self.freeOriginZ.setMaximumSize(QtCore.QSize(75, 20))        
        self.freeOriginZ.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        originLayout.addWidget(self.freeOriginZ)

        ### x 
        vector1Layout = QtGui.QHBoxLayout()
        sliceTopLayout.addLayout(vector1Layout)        
        vector1Lavel = QtGui.QLabel("X")
        vector1Layout.addWidget(vector1Lavel)

        self.freeX1 = QtGui.QLineEdit()
        self.freeX1.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeX1.setMaximumSize(QtCore.QSize(75, 20))
        vector1Layout.addWidget(self.freeX1)

        self.freeX2 = QtGui.QLineEdit()
        self.freeX2.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeX2.setMaximumSize(QtCore.QSize(75, 20))        
        vector1Layout.addWidget(self.freeX2)

        self.freeX3 = QtGui.QLineEdit()
        self.freeX3.setMaximumSize(QtCore.QSize(75, 20))        
        self.freeX3.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        vector1Layout.addWidget(self.freeX3)

        ### y
        vector2Layout = QtGui.QHBoxLayout()
        sliceTopLayout.addLayout(vector2Layout)        
        vector2Lavel = QtGui.QLabel("Y")
        vector2Layout.addWidget(vector2Lavel)

        self.freeY1 = QtGui.QLineEdit()
        self.freeY1.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeY1.setMaximumSize(QtCore.QSize(75, 20))
        vector2Layout.addWidget(self.freeY1)

        self.freeY2 = QtGui.QLineEdit()
        self.freeY2.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeY2.setMaximumSize(QtCore.QSize(75, 20))        
        vector2Layout.addWidget(self.freeY2)

        self.freeY3 = QtGui.QLineEdit()
        self.freeY3.setMaximumSize(QtCore.QSize(75, 20))        
        self.freeY3.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        vector2Layout.addWidget(self.freeY3)
        


        # separator
        #separator = QtGui.QFrame()
        #separator.setFrameShape(QtGui.QFrame.HLine)
        #separator.setFrameShadow(QtGui.QFrame.Sunken)
        #sliceTopLayout.addWidget(separator)
        
        # X bin
        groupChildLayout2 = QtGui.QHBoxLayout()
        sliceTopLayout.addLayout(groupChildLayout2)
        qxbinLabel = QtGui.QLabel("X bin")
        groupChildLayout2.addWidget(qxbinLabel)
        self.freeXbin = QtGui.QLineEdit()
        self.freeXbin.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        groupChildLayout2.addWidget(self.freeXbin)
        
      
        # Y bin
        groupChildLayout3 = QtGui.QHBoxLayout()
        sliceTopLayout.addLayout(groupChildLayout3)
        qybinLabel = QtGui.QLabel("Y bin")
        groupChildLayout3.addWidget(qybinLabel)
        self.freeYbin = QtGui.QLineEdit()
        self.freeYbin.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        groupChildLayout3.addWidget(self.freeYbin)
        
        # X range
        xRangeLayout = QtGui.QHBoxLayout()
        sliceTopLayout.addLayout(xRangeLayout)
        xRangeLabel = QtGui.QLabel("X range")
        xRangeLayout.addWidget(xRangeLabel)

        self.freeXrangeMin = QtGui.QLineEdit()
        self.freeXrangeMin.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeXrangeMin.setMaximumSize(QtCore.QSize(105, 20))
        xRangeLayout.addWidget(self.freeXrangeMin)

        self.freeXrangeMax = QtGui.QLineEdit()
        self.freeXrangeMax.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeXrangeMax.setMaximumSize(QtCore.QSize(105, 20))
        xRangeLayout.addWidget(self.freeXrangeMax)   
        
        # Y range
        yRangeLayout = QtGui.QHBoxLayout()
        sliceTopLayout.addLayout(yRangeLayout)
        yRangeLabel = QtGui.QLabel("Y range")
        yRangeLayout.addWidget(yRangeLabel)

        self.freeYrangeMin = QtGui.QLineEdit()
        self.freeYrangeMin.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeYrangeMin.setMaximumSize(QtCore.QSize(105, 20))
        yRangeLayout.addWidget(self.freeYrangeMin)

        self.freeYrangeMax = QtGui.QLineEdit()
        self.freeYrangeMax.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeYrangeMax.setMaximumSize(QtCore.QSize(105, 20))
        yRangeLayout.addWidget(self.freeYrangeMax)                   
        
        # thickness
        groupChildLayout4 = QtGui.QHBoxLayout()
        sliceTopLayout.addLayout(groupChildLayout4)
        thickLabel = QtGui.QLabel("Thickness")
        groupChildLayout4.addWidget(thickLabel)
        self.freeThickness = QtGui.QLineEdit()
        self.freeThickness.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        groupChildLayout4.addWidget(self.freeThickness)

        # exe
        exeFreeSliceLayout = QtGui.QHBoxLayout()        
        sliceTopLayout.addLayout(exeFreeSliceLayout)

        #-- Applyボタン
        self.freeSliceExeButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Apply"))
        #self.freeSliceExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/3d_free.png")))          
        self.freeSliceExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"3d_free.png")))) #[inamura 160920]          
        self.freeSliceExeButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeSliceExeButton.setMaximumSize(200, 30)
        self.freeSliceExeButton.clicked.connect(self.widgetToData)
        self.freeSliceExeButton.clicked.connect(self.doFreeSliceViewSlot)
        exeFreeSliceLayout.addWidget(self.freeSliceExeButton)

        # M2Plot
        self.freeSliceM2plotButton = QtGui.QPushButton(QtCore.QString.fromUtf8("M2Plot"))
        #self.freeSliceM2plotButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/plotchart.png")))
        self.freeSliceM2plotButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"plotchart.png")))) #[inamura 160920]
        #self.freeSliceM2plotButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.freeSliceM2plotButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeSliceM2plotButton.setMaximumSize(200, 30)
        self.freeSliceM2plotButton.clicked.connect(self.widgetToData)
        self.freeSliceM2plotButton.clicked.connect(self.doFreeSliceViewSlot)
        exeFreeSliceLayout.addWidget(self.freeSliceM2plotButton)


        # Save as ECA
        self.freeSliceSaveECAButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Save as ECA"))
        #self.freeSliceSaveECAButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/1_030.png")))
        self.freeSliceSaveECAButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"1_030.png")))) #[inamura 160920]
        #self.freeSliceSaveECAButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        self.freeSliceSaveECAButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeSliceSaveECAButton.setMaximumSize(200, 30)
        self.freeSliceSaveECAButton.clicked.connect(self.widgetToData)
        self.freeSliceSaveECAButton.clicked.connect(self.doFreeSliceViewSlot)
        exeFreeSliceLayout.addWidget(self.freeSliceSaveECAButton)

        #----
        # shift plane
        #------- 
        shiftGroup = QtGui.QGroupBox(self)
#        visGroup.setTitle(QtCore.QString.fromUtf8("View Range"))
        shiftGroup.setStyleSheet("QGroupBox { border: 2px solid rgb(0, 0, 0);}") 
        shiftTopLayout = QtGui.QVBoxLayout()
        shiftGroup.setLayout(shiftTopLayout)
        groupLayout.addWidget(shiftGroup)

        label = QtGui.QLabel("Shift Plane")
        label.setStyleSheet("font-weight: bold;") 
        shiftTopLayout.addWidget(label)


        # xdiff
        xdiffLayout = QtGui.QHBoxLayout()        
        shiftTopLayout.addLayout(xdiffLayout)
        xdiffLabel = QtGui.QLabel("Xdiff")
        xdiffLayout.addWidget(xdiffLabel)
        self.freeSliceXdiff = QtGui.QLineEdit()
        self.freeSliceXdiff.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeSliceXdiff.setMaximumSize(QtCore.QSize(105, 20))
        xdiffLayout.addWidget(self.freeSliceXdiff)

        # ydiff
        ydiffLayout = QtGui.QHBoxLayout()        
        shiftTopLayout.addLayout(ydiffLayout)
        ydiffLabel = QtGui.QLabel("Ydiff")
        ydiffLayout.addWidget(ydiffLabel)
        self.freeSliceYdiff = QtGui.QLineEdit()
        self.freeSliceYdiff.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeSliceYdiff.setMaximumSize(QtCore.QSize(105, 20))
        ydiffLayout.addWidget(self.freeSliceYdiff)

        # zdiff
        zdiffLayout = QtGui.QHBoxLayout()        
        shiftTopLayout.addLayout(zdiffLayout)
        zdiffLabel = QtGui.QLabel("Zdiff")
        zdiffLayout.addWidget(zdiffLabel)
        self.freeSliceZdiff = QtGui.QLineEdit()
        self.freeSliceZdiff.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeSliceZdiff.setMaximumSize(QtCore.QSize(105, 20))
        zdiffLayout.addWidget(self.freeSliceZdiff)

        shiftFreeSliceLayout = QtGui.QHBoxLayout()        
        shiftTopLayout.addLayout(shiftFreeSliceLayout)

        #-- Backボタン
        self.freeSliceBackButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Back"))
#        self.freeSliceBackButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/3d_free.png")))          
        self.freeSliceBackButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeSliceBackButton.setMaximumSize(200, 30)
        self.freeSliceBackButton.clicked.connect(self.shiftFreeSlicePlane)
        shiftFreeSliceLayout.addWidget(self.freeSliceBackButton)

        #-- Goボタン
        self.freeSliceGoButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Go"))
#        self.freeSliceGoButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/3d_free.png")))          
        self.freeSliceGoButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.freeSliceGoButton.setMaximumSize(200, 30)
        self.freeSliceGoButton.clicked.connect(self.shiftFreeSlicePlane)
        shiftFreeSliceLayout.addWidget(self.freeSliceGoButton)




        # Cancel
        # self.freeSliceCancelButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Stop"))
        # self.freeSliceCancelButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/stop.png")))
        # #self.freeSliceCancelButton.setGeometry(QtCore.QRect(0, 0, 20, 0))
        # self.freeSliceCancelButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        # self.freeSliceCancelButton.setMaximumSize(200, 30)
        # self.freeSliceCancelButton.clicked.connect(self.cancelFreeSliceView)
        # exeFreeSliceLayout.addWidget(self.freeSliceCancelButton)
              

        freeSliceTopLayout = QtGui.QVBoxLayout()
        freeSliceTopLayout.addWidget(freeSliceGroup)
        self.freeSliceWidget.setLayout(freeSliceTopLayout)
        self.ui.parameterLayout.addWidget(self.freeSliceWidget) 

# Axis/Grid Widget
#-----------------------------------
    def createAxisGridWidget(self):
        self.axisGridWidget = QtGui.QWidget(self)
        self.axisGridWidget.setMinimumSize(self.axisGridWmin, self.axisGridHmin)
        self.axisGridWidget.setMaximumSize(self.axisGridWmax, self.axisGridHmax)
        self.axisGridWidget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)

        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Background, QtCore.Qt.lightGray)
        self.axisGridWidget.setAutoFillBackground(True)
        self.axisGridWidget.setPalette(palette)

        axisGridGroup = QtGui.QGroupBox(self)
        axisGridGroup.setTitle(QtCore.QString.fromUtf8("Axis/Grid"))
        groupLayout = QtGui.QVBoxLayout()
        axisGridGroup.setLayout(groupLayout)

        #** Axis 
        axisLayout = QtGui.QHBoxLayout()
        groupLayout.addLayout(axisLayout)
        self.axisViewCheck = QtGui.QCheckBox("Visible")
        self.axisViewCheck.clicked.connect(self.widgetToData)
        self.axisViewCheck.clicked.connect(self.enableControl)
        self.axisViewCheck.clicked.connect(self.dataToGLViewItemVisibility)
        axisLayout.addWidget(self.axisViewCheck)

        self.axisTickCheck = QtGui.QCheckBox("Show Scale Mark")
        self.axisTickCheck.clicked.connect(self.widgetToData)
        self.axisTickCheck.clicked.connect(self.dataToGLViewItemVisibility)
        axisLayout.addWidget(self.axisTickCheck)

        editBoxW = 50
        # 
        axisLayout2 = QtGui.QHBoxLayout()
        groupLayout.addLayout(axisLayout2)
        axisLengthTitle = QtGui.QLabel("Axis Length(Ax1, Ax2, Ax3)")
        axisLayout2.addWidget(axisLengthTitle)
        self.axisLengthX = QtGui.QLineEdit()
        self.axisLengthX.setMaximumSize(editBoxW, 35)
        self.axisLengthX.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        axisLayout2.addWidget(self.axisLengthX)
        self.axisLengthY = QtGui.QLineEdit()
        self.axisLengthY.setMaximumSize(editBoxW, 35)
        self.axisLengthY.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        axisLayout2.addWidget(self.axisLengthY)
        self.axisLengthZ = QtGui.QLineEdit()
        self.axisLengthZ.setMaximumSize(editBoxW, 35)
        self.axisLengthZ.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        axisLayout2.addWidget(self.axisLengthZ)
        
        #** Grid
        gridLayout = QtGui.QHBoxLayout()
        groupLayout.addLayout(gridLayout)
        self.gridXYViewCheck = QtGui.QCheckBox("Ax1-Ax2 Visible")
        self.gridXYViewCheck.clicked.connect(self.widgetToData)
        self.gridXYViewCheck.clicked.connect(self.dataToGLViewItemVisibility)
        gridLayout.addWidget(self.gridXYViewCheck)

        self.gridYZViewCheck = QtGui.QCheckBox("Ax2-Ax3 Visible")
        self.gridYZViewCheck.clicked.connect(self.widgetToData)
        self.gridYZViewCheck.clicked.connect(self.dataToGLViewItemVisibility)
        gridLayout.addWidget(self.gridYZViewCheck)

        self.gridZXViewCheck = QtGui.QCheckBox("Ax3-Ax1 Visible")
        self.gridZXViewCheck.clicked.connect(self.widgetToData)
        self.gridZXViewCheck.clicked.connect(self.dataToGLViewItemVisibility)
        gridLayout.addWidget(self.gridZXViewCheck)

        gridLayout2 = QtGui.QHBoxLayout()
        groupLayout.addLayout(gridLayout2)
        gridScaleTitle = QtGui.QLabel("Grid Space(Ax1, Ax2, Ax3)")
        gridLayout2.addWidget(gridScaleTitle)
        self.gridSpaceX = QtGui.QLineEdit()
        self.gridSpaceX.setMaximumSize(editBoxW, 35)
        self.gridSpaceX.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        gridLayout2.addWidget(self.gridSpaceX)
        self.gridSpaceY = QtGui.QLineEdit()
        self.gridSpaceY.setMaximumSize(editBoxW, 35)
        self.gridSpaceY.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        gridLayout2.addWidget(self.gridSpaceY)
        self.gridSpaceZ = QtGui.QLineEdit()
        self.gridSpaceZ.setMaximumSize(editBoxW, 35)
        self.gridSpaceZ.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        gridLayout2.addWidget(self.gridSpaceZ)

        gridLayout3 = QtGui.QHBoxLayout()
        groupLayout.addLayout(gridLayout3)
        gridLayout3.addWidget(QtGui.QLabel("Axis TItle(Ax1, Ax2, Ax3)"))
        self.ax1Title = QtGui.QLineEdit()
        self.ax1Title.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax1Title.setMaximumSize(editBoxW, 35)
        gridLayout3.addWidget(self.ax1Title)
        self.ax2Title = QtGui.QLineEdit()
        self.ax2Title.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax2Title.setMaximumSize(editBoxW, 35)
        gridLayout3.addWidget(self.ax2Title)
        self.ax3Title = QtGui.QLineEdit()
        self.ax3Title.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        self.ax3Title.setMaximumSize(editBoxW, 35)
        gridLayout3.addWidget(self.ax3Title)

        #-- 実行ボタン
        self.axisGridExeButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Apply"))
        #self.axisGridExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/axis.png")))
        self.axisGridExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"axis.png")))) #[inamura 160920]
        self.axisGridExeButton.clicked.connect(self.widgetToData)
        self.axisGridExeButton.clicked.connect(self.updateAxisGrid)
        groupLayout.addWidget(self.axisGridExeButton)

        #--
        axisGridTopLayout = QtGui.QVBoxLayout()
        axisGridTopLayout.addWidget(axisGridGroup)
        self.axisGridWidget.setLayout(axisGridTopLayout)
        self.ui.parameterLayout.addWidget(self.axisGridWidget)

# カラーバー（強度分布）編集設定用ウィジェットの作成
#-----------------------------------
    def createColorBarSettingWidget(self):
        self.colorBarSettingWidget = QtGui.QWidget(self)
        self.colorBarSettingWidget.setMinimumSize(self.colorBarWmin, self.colorBarHmin)
        self.colorBarSettingWidget.setMaximumSize(self.colorBarWmax, self.colorBarHmax)
        self.colorBarSettingWidget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)

        self.widgets.append(self.colorBarSettingWidget)
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Background, QtCore.Qt.lightGray)
        self.colorBarSettingWidget.setAutoFillBackground(True)
        self.colorBarSettingWidget.setPalette(palette)

        colorBarSettingGroup      = QtGui.QGroupBox(self)
        colorBarSettingGroup.setTitle(QtCore.QString.fromUtf8("ColorBar Settings"))
        groupLayout = QtGui.QVBoxLayout()
        colorBarSettingGroup.setLayout(groupLayout)
        
        
        # linear scale or log scale
        scaleGroup = QtGui.QGroupBox(self)
        scaleGroup.setTitle(QtCore.QString.fromUtf8(""))
        groupLayout.addWidget(scaleGroup)
        scaleRadioLayout = QtGui.QHBoxLayout()
        scaleGroup.setLayout(scaleRadioLayout)

        self.linearRadio = QtGui.QRadioButton("Linear scale")
        scaleRadioLayout.addWidget(self.linearRadio)
        #self.linearRadio.toggled.connect(self.enableCotrol)
        self.logRadio = QtGui.QRadioButton("Logarithmic scale")
        scaleRadioLayout.addWidget(self.logRadio)
        #self.logRadio.toggled.connect(self.enableControl)
        
        scaleSelectionGroup = QtGui.QButtonGroup(self.colorBarSettingWidget)
        scaleSelectionGroup.addButton(self.linearRadio)
        scaleSelectionGroup.addButton(self.logRadio)        
             
        # Scalar Range
        autoLayout = QtGui.QHBoxLayout()
        groupLayout.addLayout(autoLayout)
        self.autoScale = QtGui.QCheckBox("Auto Scale")
        self.autoScale.clicked.connect(self.enableControl)
        autoLayout.addWidget(self.autoScale)
        
        # Minimum
        scalarRangeLayout = QtGui.QHBoxLayout()
        groupLayout.addLayout(scalarRangeLayout)
        rangeLabel = QtGui.QLabel("Range:")
        rangeLabel.setMaximumSize(50, 30)
        scalarRangeLayout.addWidget(rangeLabel)
        self.scalarRangeMinimum = QtGui.QLineEdit()
        self.scalarRangeMinimum.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        scalarRangeLayout.addWidget(self.scalarRangeMinimum)
          
        # Maximum
        rangeLabel2 = QtGui.QLabel(QtCore.QString.fromUtf8("to"))
        rangeLabel2.setMaximumSize(20, 30)
        scalarRangeLayout.addWidget(rangeLabel2)
        self.scalarRangeMaximum = QtGui.QLineEdit()
        self.scalarRangeMaximum.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        scalarRangeLayout.addWidget(self.scalarRangeMaximum)
     
        # Color Map
        colorMapLayout = QtGui.QHBoxLayout()
        groupLayout.addLayout(colorMapLayout)
        colorMapLabel = QtGui.QLabel(QtCore.QString.fromUtf8("Color Map"))
        colorMapLayout.addWidget(colorMapLabel)
        self.colorMapCombo = QtGui.QComboBox(self)
        self.colorMapCombo.addItem("cyclic")
        self.colorMapCombo.addItem("spectrum")
        self.colorMapCombo.addItem("thermal")
        self.colorMapCombo.addItem("flame")
        self.colorMapCombo.addItem("yellowy")
        self.colorMapCombo.addItem("bipolar")
        self.colorMapCombo.addItem("greyclip")
        self.colorMapCombo.addItem("grey")
        colorMapLayout.addWidget(self.colorMapCombo)
        
        #-- 実行ボタン
        self.colorBarExeButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Apply"))
        #self.colorBarExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap("Icon/color.png")))
        self.colorBarExeButton.setIcon(QtGui.QIcon(QtGui.QPixmap(os.path.join(self.IconDir,"color.png")))) #[inamura 160920]
        self.colorBarExeButton.clicked.connect(self.widgetToData)
        self.colorBarExeButton.clicked.connect(self.updateColorBar)
        groupLayout.addWidget(self.colorBarExeButton)

        #--
        colorBarSettingTopLayout = QtGui.QVBoxLayout()
        colorBarSettingTopLayout.addWidget(colorBarSettingGroup)
        self.colorBarSettingWidget.setLayout(colorBarSettingTopLayout)
        self.ui.parameterLayout.addWidget(self.colorBarSettingWidget) 
        
# 表示設定用ウィジェットの作成
#-----------------------------------
    def createViewSettingWidget(self):
        self.viewSettingWidget = QtGui.QWidget(self)
        self.widgets.append(self.viewSettingWidget)
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Background, QtCore.Qt.lightGray)
        self.viewSettingWidget.setAutoFillBackground(True)
        self.viewSettingWidget.setPalette(palette)

        viewSettingGroup      = QtGui.QGroupBox(self)
        viewSettingGroup.setTitle(QtCore.QString.fromUtf8("View Settings"))
        groupLayout = QtGui.QVBoxLayout()
        viewSettingGroup.setLayout(groupLayout)
        
        # 注視点、距離、方位角、仰角を与えて視点を変更
        viewMethodLayout = QtGui.QHBoxLayout()
        groupLayout.addLayout(viewMethodLayout)
        self.viewMethod1Radio = QtGui.QRadioButton("point + point")
        self.viewMethod1Radio.toggled.connect(self.enableControl)
        viewMethodLayout.addWidget(self.viewMethod1Radio)
        self.viewMethod2Radio = QtGui.QRadioButton("point + angle")
        self.viewMethod2Radio.toggled.connect(self.enableControl)
        viewMethodLayout.addWidget(self.viewMethod2Radio)
        
        viewChildLayout1 = QtGui.QGridLayout()
        groupLayout.addLayout(viewChildLayout1)        

        # 注視点 X
        rowID = 0
        colID = 0
        fpLabelX = QtGui.QLabel(QtCore.QString.fromUtf8("Focal Point ax1"))
        viewChildLayout1.addWidget(fpLabelX, rowID, colID)

        colID += 1
        self.focalPointX = QtGui.QLineEdit()
        self.focalPointX.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        viewChildLayout1.addWidget(self.focalPointX, rowID, colID)

        # 注視点 Y
        rowID += 1
        colID  = 0
        fpLabelY = QtGui.QLabel(QtCore.QString.fromUtf8("Focal Point ax2"))
        viewChildLayout1.addWidget(fpLabelY, rowID, colID)

        colID += 1
        self.focalPointY = QtGui.QLineEdit()
        self.focalPointY.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        viewChildLayout1.addWidget(self.focalPointY, rowID, colID)

        # 注視点 Z
        rowID += 1
        colID  = 0
        fpLabelZ = QtGui.QLabel(QtCore.QString.fromUtf8("Focal Point ax3"))
        viewChildLayout1.addWidget(fpLabelZ, rowID, colID)

        colID += 1
        self.focalPointZ = QtGui.QLineEdit()
        self.focalPointZ.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        viewChildLayout1.addWidget(self.focalPointZ, rowID, colID) 

        # View Point X
        rowID += 1
        colID  = 0
        vpLabelX = QtGui.QLabel(QtCore.QString.fromUtf8("View Point ax1"))
        viewChildLayout1.addWidget(vpLabelX, rowID, colID)

        colID += 1
        self.viewPointX = QtGui.QLineEdit()
        self.viewPointX.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        viewChildLayout1.addWidget(self.viewPointX, rowID, colID)

        # 注視点 Y
        rowID += 1
        colID  = 0
        vpLabelY = QtGui.QLabel(QtCore.QString.fromUtf8("View Point ax2"))
        viewChildLayout1.addWidget(vpLabelY, rowID, colID)

        colID += 1
        self.viewPointY = QtGui.QLineEdit()
        self.viewPointY.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        viewChildLayout1.addWidget(self.viewPointY, rowID, colID)

        # 注視点 Z
        rowID += 1
        colID  = 0
        vpLabelZ = QtGui.QLabel(QtCore.QString.fromUtf8("View Point ax3"))
        viewChildLayout1.addWidget(vpLabelZ, rowID, colID)

        colID += 1
        self.viewPointZ = QtGui.QLineEdit()
        self.viewPointZ.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        viewChildLayout1.addWidget(self.viewPointZ, rowID, colID) 

        # 距離
        rowID += 1
        colID = 0
        distLabel = QtGui.QLabel(QtCore.QString.fromUtf8("Distance"))
        viewChildLayout1.addWidget(distLabel, rowID, colID)

        colID += 1
        self.distEdit = QtGui.QLineEdit()
        self.distEdit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        viewChildLayout1.addWidget(self.distEdit, rowID, colID)

        # 方位角
        rowID += 1
        colID  = 0
        azLabel = QtGui.QLabel(QtCore.QString.fromUtf8("Azimuth"))
        viewChildLayout1.addWidget(azLabel, rowID, colID)

        colID += 1
        self.azEdit = QtGui.QLineEdit()
        self.azEdit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        viewChildLayout1.addWidget(self.azEdit, rowID, colID)

        # 仰角
        rowID += 1
        colID = 0
        eleLabel = QtGui.QLabel(QtCore.QString.fromUtf8("Elevation"))
        viewChildLayout1.addWidget(eleLabel, rowID, colID)

        colID += 1
        self.eleEdit = QtGui.QLineEdit()
        self.eleEdit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        viewChildLayout1.addWidget(self.eleEdit, rowID, colID)

        #-- 実行ボタン
        exeButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Apply"))
        #fileButton.setGeometry(QtCore.QRect(0, 0, 20, 20))
        exeButton.clicked.connect(self.changeViewPoint)
        groupLayout.addWidget(exeButton)

        #--
        viewSettingTopLayout = QtGui.QVBoxLayout()
        viewSettingTopLayout.addWidget(viewSettingGroup)
        self.viewSettingWidget.setLayout(viewSettingTopLayout)
        self.ui.parameterLayout.addWidget(self.viewSettingWidget) 
 


# その他ラベル等表示設定用
#---------------------------------------
    def createLabelSettingWidget(self):
        self.labelSettingWidget = QtGui.QWidget(self)
        self.labelSettingWidget.setMinimumSize(self.labelWmin, self.labelHmin)
        self.labelSettingWidget.setMaximumSize(self.labelWmax, self.labelHmax)
        self.labelSettingWidget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)

        self.widgets.append(self.labelSettingWidget)
        palette = QtGui.QPalette()
        palette.setColor(QtGui.QPalette.Background, QtCore.Qt.lightGray)
        self.labelSettingWidget.setAutoFillBackground(True)
        self.labelSettingWidget.setPalette(palette)

        labelSettingGroup      = QtGui.QGroupBox(self)
        labelSettingGroup.setTitle(QtCore.QString.fromUtf8("Label Settings"))
        groupLayout = QtGui.QVBoxLayout()
        labelSettingGroup.setLayout(groupLayout)

        # axis font
        axisFontLayout = QtGui.QHBoxLayout()
        groupLayout.addLayout(axisFontLayout)
        
        axisFontLabel = QtGui.QLabel(QtCore.QString.fromUtf8("Axis Font"))
        axisFontLayout.addWidget(axisFontLabel)
        self.axisFontCombo = QtGui.QComboBox(self)
        self.axisFontCombo.addItem("Fixed-Pitch (8x13 px)")
        self.axisFontCombo.addItem("Fixed-Pitch (9x15 px)")
        self.axisFontCombo.addItem("Helvetica (10pt)")
        self.axisFontCombo.addItem("Helvetica (12pt)")
        self.axisFontCombo.addItem("Helvetica (18pt)")
        self.axisFontCombo.addItem("Times Roman (10pt)")
        self.axisFontCombo.addItem("Times Roman (24pt)")
        axisFontLayout.addWidget(self.axisFontCombo)

        #-- 実行ボタン
        exeButton = QtGui.QPushButton(QtCore.QString.fromUtf8("Apply"))
        exeButton.clicked.connect(self.updateLabel)
        groupLayout.addWidget(exeButton)

        #--
        labelSettingTopLayout = QtGui.QVBoxLayout()
        labelSettingTopLayout.addWidget(labelSettingGroup)
        self.labelSettingWidget.setLayout(labelSettingTopLayout)
        self.ui.parameterLayout.addWidget(self.labelSettingWidget)         

    
# パラメータレイアウトにスペーサーを挿入
#---------------------------------------
    def addSpacerToParameterLayout(self):
        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.ui.parameterLayout.addItem(spacerItem)


# カラーバーウィジェットの追加
#----------------------------------
    def addColorBarWidget(self):
        self.colorBarWidget = QtGui.QWidget(self)
        
        self.colorBarWidget.setMaximumSize(120, 999)
        self.colorBarWidget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)        
        
        groupLayout = QtGui.QHBoxLayout()
        self.colorBarWidget.setLayout(groupLayout)    
        self.ui.colorBarLayout.addWidget(self.colorBarWidget)
    
        self.colorBar = pg.GradientWidget(orientation='left')
        self.colorBar.setMaximumSize(30, 999)
        self.colorBar.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)           
        
        #self.colorBar.loadPreset('thermal') # カラーバー色の設定
        #for i in range(len(self.colorBar.item.listTicks())):
        #    wt = self.colorBar.item.getTick(i)
        #    wt.setVisible(False)

        nPts = 200
        lut = self.colorBar.getLookupTable(nPts, alpha=None)
        groupLayout.setSpacing(0)
        self.colorBar.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
        groupLayout.addWidget(self.colorBar)
        
        # カラーバーラベルの設定
        self.colorLabelLayout = QtGui.QVBoxLayout()
        groupLayout.addLayout(self.colorLabelLayout)        
          
        

        #    label.setMaximumSize(50, 20)
        #    #label.setGeometry(QtCore.QRect(0, 0, 70, 20))
        #    label.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
        #    label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        #    self.colorLabelLayout.addWidget(label)  

# ステータスバーの追加
#-----------------------------------
    def addStatusBar(self):
        self.status_bar = QtGui.QStatusBar(self)
        self.status_bar.showMessage("")
        self.setStatusBar(self.status_bar)

#======================================================================================
#
# ***.uiでの設定情報（表示/非表示)をウィジェットへ反映
#
#======================================================================================
    def initializeWidgetsVisible(self):
        #--------------------------------------------------------------------------
        # データ読み込みメニュー        
        if self.data_load_view_action.isChecked():
            self.dataLoadWidget.show()
        else:
            self.dataLoadWidget.hide()    

        # Data Info Menu
        if self.data_info_view_action.isChecked():
            self.dataInfoWidget.show()
        else:
            self.dataInfoWidget.hide()    

        # 基本3面表示メニュー
        if self.basic_slice_view_action.isChecked():
            self.basicSliceWidget.show()
        else:
            self.basicSliceWidget.hide()
            
        # 基本3面スライダ表示メニュー
#        if self.basic_slice_slider_view_action.isChecked():
#            self.sliceScrollWidget.show()
#        else:
#            self.sliceScrollWidget.hide()            

        # Axis/Grid表示メニュー
        if self.axis_grid_view_action.isChecked():
            self.axisGridWidget.show()
        else:
            self.axisGridWidget.hide()

        # 任意面表示メニュー
        if self.free_slice_view_action.isChecked():
            self.freeSliceWidget.show()
        else:
            self.freeSliceWidget.hide()
            
        # カラーバー
        if self.color_bar_setting_view_action.isChecked():
            self.colorBarSettingWidget.show()
        else:
            self.colorBarSettingWidget.hide()    
            
        # カラーバー
        if self.color_bar_view_action.isChecked():
            self.colorBarWidget.show()
        else:
            self.colorBarWidget.hide()   

        # 表示設定用メニュー
        if self.view_setting_view_action.isChecked():
            self.viewSettingWidget.show()
        else:
            self.viewSettingWidget.hide()
            
        # ラベル表示設定用メニュー
        if self.label_setting_view_action.isChecked():
            self.labelSettingWidget.show()
        else:
            self.labelSettingWidget.hide()            

#======================================================================================
#
# データの情報をウィジェットへ反映
#
#======================================================================================
# Data to widget
#------------------------------------------------      
    def dataToWidget(self):
        # 基本3面スライス面表示
        self.dataToBasicSliceWidget()

        # 任意スライス面表示
        self.dataToFreeSliceWidget()
        
        # Axis/Grid
        self.dataToAxisGridWidget()        
           
        # カラーバー
        self.dataToColorBarWidget()        
        
        # 視点
        self.dataToViewWidget()
        
        # 軸フォント
        self.dataToLabelWidget()


# 基本3面スライス面情報の反映 (Data to Control)
#------------------------------------------------ 
    def dataToBasicSliceWidget(self):
        # View Range
        #----------------------------
        # ax1
        self.ax1From.setText(str(self.viewMainData.basicSliceAx1From))
        self.ax1To.setText(str(self.viewMainData.basicSliceAx1To))
        self.ax1Bin.setText(str(self.viewMainData.basicSliceAx1bin))
        self.ax1ViewScale.setText(str(self.viewMainData.basicSliceAx1Scale))
        # ax2
        self.ax2From.setText(str(self.viewMainData.basicSliceAx2From))
        self.ax2To.setText(str(self.viewMainData.basicSliceAx2To))
        self.ax2Bin.setText(str(self.viewMainData.basicSliceAx2bin))
        self.ax2ViewScale.setText(str(self.viewMainData.basicSliceAx2Scale))
        # ax3
        self.ax3From.setText(str(self.viewMainData.basicSliceAx3From))
        self.ax3To.setText(str(self.viewMainData.basicSliceAx3To))
        self.ax3Bin.setText(str(self.viewMainData.basicSliceAx3bin))
        self.ax3ViewScale.setText(str(self.viewMainData.basicSliceAx3Scale))
        # intensity
        self.intensityMin.setText(str(self.viewSubData.scalarRangeMin))
        self.intensityMax.setText(str(self.viewSubData.scalarRangeMax))
        # logscale
        if self.viewSubData.scale == ViewSubData.ViewSubData.LINEAR_SCALE:
            self.logscaleCheck.setChecked(False)
        elif self.viewSubData.scale == ViewSubData.ViewSubData.LOG_SCALE:
            self.logscaleCheck.setChecked(True)
        # color map
        self.colorMapCombo2.setCurrentIndex(self.colorMapCombo2.findText(QtCore.QString(self.viewSubData.colorBarPreset)))

        # Slice Plane
        #--------------------------
        # ax1-ax2
        if self.viewMainData.ax3Slice.visible:
            self.ax1ax2PlaneViewCheck.setChecked(True)
        else:
            self.ax1ax2PlaneViewCheck.setChecked(False)

        self.ax3.setText(self.viewMainData.ax3Slice.position)
        self.ax3Thickness.setText(str(self.viewMainData.ax3Slice.thickness))

        # ax2-ax3
        if self.viewMainData.ax1Slice.visible:
            self.ax2ax3PlaneViewCheck.setChecked(True)
        else:
            self.ax2ax3PlaneViewCheck.setChecked(False)
        
        self.ax1.setText(self.viewMainData.ax1Slice.position)
        self.ax1Thickness.setText(str(self.viewMainData.ax1Slice.thickness))
        
        # ax3-ax1
        if self.viewMainData.ax2Slice.visible:
            self.ax3ax1PlaneViewCheck.setChecked(True)
        else:
            self.ax3ax1PlaneViewCheck.setChecked(False)

        
        self.ax2.setText(self.viewMainData.ax2Slice.position)
        self.ax2Thickness.setText(str(self.viewMainData.ax2Slice.thickness))
        
        # Output
        #--------------------------
        self.slicePlane.setCurrentIndex(self.viewMainData.slicePlane)


# 任意面スライス情報の反映 (Data to Control)
#------------------------------------------------ 
    def dataToFreeSliceWidget(self):
        if self.viewMainData.freeSlice.visible:
            self.freeSliceViewCheck.setChecked(True)
        else:
            self.freeSliceViewCheck.setChecked(False)

        self.freeOriginX.setText(str(self.viewMainData.freeSlice.org[0]))
        self.freeOriginY.setText(str(self.viewMainData.freeSlice.org[1]))
        self.freeOriginZ.setText(str(self.viewMainData.freeSlice.org[2]))

        self.freeX1.setText(str(self.viewMainData.freeSlice.x[0]))
        self.freeX2.setText(str(self.viewMainData.freeSlice.x[1]))
        self.freeX3.setText(str(self.viewMainData.freeSlice.x[2]))

        self.freeY1.setText(str(self.viewMainData.freeSlice.y[0]))
        self.freeY2.setText(str(self.viewMainData.freeSlice.y[1]))
        self.freeY3.setText(str(self.viewMainData.freeSlice.y[2]))

        self.freeXbin.setText(str(self.viewMainData.freeSlice.xbin))
        self.freeYbin.setText(str(self.viewMainData.freeSlice.ybin))

        self.freeXrangeMin.setText(str(self.viewMainData.freeSlice.rangex[0]))
        self.freeXrangeMax.setText(str(self.viewMainData.freeSlice.rangex[1]))
        self.freeYrangeMin.setText(str(self.viewMainData.freeSlice.rangey[0]))
        self.freeYrangeMax.setText(str(self.viewMainData.freeSlice.rangey[1]))

        self.freeThickness.setText(str(self.viewMainData.freeSlice.thickness))

        self.freeSliceXdiff.setText(str(self.viewMainData.freeSlice.xdiff))
        self.freeSliceYdiff.setText(str(self.viewMainData.freeSlice.ydiff))
        self.freeSliceZdiff.setText(str(self.viewMainData.freeSlice.zdiff))
        
# Axis/Grid (Data to Control)
#------------------------------------------------ 
    def dataToAxisGridWidget(self):
        if self.viewSubData.axisVisible:
            self.axisViewCheck.setChecked(True)
        else:
            self.axisViewCheck.setChecked(False)        

        if self.viewSubData.axisTickVisible:
            self.axisTickCheck.setChecked(True)
        else:
            self.axisTickCheck.setChecked(False)        

        self.axisLengthX.setText(str(self.viewSubData.lenXaxis))
        self.axisLengthY.setText(str(self.viewSubData.lenYaxis))
        self.axisLengthZ.setText(str(self.viewSubData.lenZaxis))

        if self.viewSubData.gridXYVisible:
            self.gridXYViewCheck.setChecked(True)
        else:
            self.gridXYViewCheck.setChecked(False)

        if self.viewSubData.gridYZVisible:
            self.gridYZViewCheck.setChecked(True)
        else:
            self.gridYZViewCheck.setChecked(False)

        if self.viewSubData.gridZXVisible:
            self.gridZXViewCheck.setChecked(True)
        else:
            self.gridZXViewCheck.setChecked(False)

        self.gridSpaceX.setText(str(self.viewSubData.gridSpace[0]))
        self.gridSpaceY.setText(str(self.viewSubData.gridSpace[1]))
        self.gridSpaceZ.setText(str(self.viewSubData.gridSpace[2]))

        self.ax1Title.setText(self.viewMainData.ax1Slice.axisTitle)
        self.ax2Title.setText(self.viewMainData.ax2Slice.axisTitle)
        self.ax3Title.setText(self.viewMainData.ax3Slice.axisTitle)

# カラーバー情報の反映 (Data to Control)
#------------------------------------------------ 
    def dataToColorBarWidget(self):
        # スケール
        if self.viewSubData.scale == ViewSubData.ViewSubData.LINEAR_SCALE:
            self.linearRadio.setChecked(True)
        elif self.viewSubData.scale == ViewSubData.ViewSubData.LOG_SCALE:
            self.logRadio.setChecked(True)
        
        # Auto Scale
        if self.viewSubData.autoScale:
            self.autoScale.setChecked(True)
        else:
            self.autoScale.setChecked(False)
        
        self.scalarRangeMinimum.setText(str(self.viewSubData.scalarRangeMin))
        self.scalarRangeMaximum.setText(str(self.viewSubData.scalarRangeMax))
        
        # カラーバー
        self.colorMapCombo2.setCurrentIndex(self.colorMapCombo2.findText(QtCore.QString(self.viewSubData.colorBarPreset)))
        self.updateColorBar()


# 視点情報の反映 (Data to Control)
#------------------------------------------------ 
    def dataToViewWidget(self):
        # 初期値を設定
              
        center = self.glView.opts['center']
        xtmp = 0
        ytmp = 0
        ztmp = 0
        if isinstance(center, pg.Vector):
           xtmp = center[0]
           ytmp = center[1]
           ztmp = center[2]
        elif isinstance(center, QtGui.QVector3D):
           xtmp = center.x()
           ytmp = center.y()
           ztmp = center.z()
        
        x = xtmp/self.viewMainData.basicSliceAx1Scale
        y = ytmp/self.viewMainData.basicSliceAx2Scale
        z = ztmp/self.viewMainData.basicSliceAx3Scale

        dist = self.glView.opts['distance']
        az   = self.glView.opts['azimuth']
        ele  = self.glView.opts['elevation']
        self.focalPointX.setText(QtCore.QString.number(x))
        self.focalPointY.setText(QtCore.QString.number(y))
        self.focalPointZ.setText(QtCore.QString.number(z))
        self.distEdit.setText(QtCore.QString.number(dist))
        self.azEdit.setText(QtCore.QString.number(az))
        self.eleEdit.setText(QtCore.QString.number(ele))

        viewZ = ztmp + dist * math.sin(math.pi*ele/180.0)
        tmp = dist * math.cos(math.pi*ele/180.0)
        viewX = xtmp + tmp * math.cos(math.pi*az/180.0)
        viewY = ytmp + tmp * math.sin(math.pi*az/180.0)

        viewX = viewX/self.viewMainData.basicSliceAx1Scale
        viewY = viewY/self.viewMainData.basicSliceAx2Scale
        viewZ = viewZ/self.viewMainData.basicSliceAx3Scale
        self.viewPointX.setText(QtCore.QString.number(viewX))
        self.viewPointY.setText(QtCore.QString.number(viewY))
        self.viewPointZ.setText(QtCore.QString.number(viewZ))
 

# 軸フォント情報の反映 (Data to Control)
#------------------------------------------------ 
    def dataToLabelWidget(self):
        # フォント
        if self.viewSubData.axisFont == GLUT_BITMAP_8_BY_13:
            self.axisFontCombo.setCurrentIndex(0)
        elif self.viewSubData.axisFont == GLUT_BITMAP_9_BY_15:
            self.axisFontCombo.setCurrentIndex(1)            
        elif self.viewSubData.axisFont == GLUT_BITMAP_HELVETICA_10:
            self.axisFontCombo.setCurrentIndex(2)            
        elif self.viewSubData.axisFont == GLUT_BITMAP_HELVETICA_12:
            self.axisFontCombo.setCurrentIndex(3)            
        elif self.viewSubData.axisFont == GLUT_BITMAP_HELVETICA_18:
            self.axisFontCombo.setCurrentIndex(4)            
        elif self.viewSubData.axisFont == GLUT_BITMAP_TIMES_ROMAN_10:
            self.axisFontCombo.setCurrentIndex(5)            
        elif self.viewSubData.axisFont == GLUT_BITMAP_TIMES_ROMAN_24:
            self.axisFontCombo.setCurrentIndex(6)           

#======================================================================================
#
# メインビューの再描画
# データの表示/非表示情報をView ItemのVisibilityへ反映
#
#======================================================================================
    def dataToGLViewItemVisibility(self):
        # 一度すべてのitemを消去.
        self.glView.items=[]
          
        # axis, axis label
        if hasattr(self.viewSubData, "axis") and self.viewSubData.axisVisible:                
            self.glView.addItem(self.viewSubData.axis)
            self.glView.addItem(self.viewSubData.xAxisLabel)
            self.glView.addItem(self.viewSubData.yAxisLabel)
            self.glView.addItem(self.viewSubData.zAxisLabel)

        tickSize = 0
        if hasattr(self.viewSubData, "xAxisTick") and self.viewSubData.axisVisible and self.viewSubData.axisTickVisible:
            tickSize = len(self.viewSubData.xAxisTick)
            for id in range(tickSize):
                self.glView.addItem(self.viewSubData.xAxisTick[id])
            tickSize = len(self.viewSubData.yAxisTick)
            for id in range(tickSize):
                self.glView.addItem(self.viewSubData.yAxisTick[id])
            tickSize = len(self.viewSubData.zAxisTick)
            for id in range(tickSize):
                self.glView.addItem(self.viewSubData.zAxisTick[id])

        # grid
        if hasattr(self.viewSubData, "gridXY") and self.viewSubData.gridXYVisible:
            self.glView.addItem(self.viewSubData.gridXY)
        if hasattr(self.viewSubData, "gridYZ") and self.viewSubData.gridYZVisible:
            self.glView.addItem(self.viewSubData.gridYZ)
        if hasattr(self.viewSubData, "gridZX") and self.viewSubData.gridZXVisible:
            self.glView.addItem(self.viewSubData.gridZX)

        # slice plane
        if hasattr(self, "basicSliceItemXY") and self.ax1ax2PlaneViewCheck.isChecked():
            self.glView.addItem(self.basicSliceItemXY)
        if hasattr(self, "basicSliceItemYZ") and self.ax2ax3PlaneViewCheck.isChecked():
            self.glView.addItem(self.basicSliceItemYZ)
        if hasattr(self, "basicSliceItemZX") and self.ax3ax1PlaneViewCheck.isChecked():
            self.glView.addItem(self.basicSliceItemZX)

        if hasattr(self, "freeSliceItem") and self.freeSliceViewCheck.isChecked():
            self.glView.addItem(self.freeSliceItem)

        self.glView.update()

#======================================================================================
#
# データの情報をView Itemへ反映
#
#======================================================================================
# データクラスの初期値からView Item情報を修正する
#--------------------------------------------------
    def updateAxisLabel(self):
        self.viewSubData.updateAxisLabel()
        self.glView.update()


#///////////////////////////////////////////////////////////////////////////////////////
#
# ウィジェットの情報をデータクラスへ反映
#
#///////////////////////////////////////////////////////////////////////////////////////
    def widgetToData(self):
       # Axis/Grid
       if self.sender() == self.axisViewCheck or self.sender() == self.gridXYViewCheck or \
          self.sender() == self.gridYZViewCheck or self.sender() == self.gridZXViewCheck or \
          self.sender() == self.axisGridExeButton or self.sender() == self.axisTickCheck:
           self.axisGridWidgetToData()

       # Color map
       if self.sender() == self.colorBarExeButton:
           self.colorBarWidgetToData()
 

    def widgetToDataForBasicSliceViewRange(self):
        # View Range
        #----------------------------
        # ax1
        self.viewMainData.basicSliceAx1From  = float(str(self.ax1From.text()))
        self.viewMainData.basicSliceAx1To    = float(str(self.ax1To.text()))
        self.viewMainData.basicSliceAx1bin   = float(str(self.ax1Bin.text()))
        self.viewMainData.basicSliceAx1Scale = float(str(self.ax1ViewScale.text()))
        # ax2
        self.viewMainData.basicSliceAx2From  = float(str(self.ax2From.text()))
        self.viewMainData.basicSliceAx2To    = float(str(self.ax2To.text()))
        self.viewMainData.basicSliceAx2bin   = float(str(self.ax2Bin.text()))
        self.viewMainData.basicSliceAx2Scale = float(str(self.ax2ViewScale.text()))
        # ax3
        self.viewMainData.basicSliceAx3From  = float(str(self.ax3From.text()))
        self.viewMainData.basicSliceAx3To    = float(str(self.ax3To.text()))
        self.viewMainData.basicSliceAx3bin   = float(str(self.ax3Bin.text()))
        self.viewMainData.basicSliceAx3Scale = float(str(self.ax3ViewScale.text()))
        # intensity
        self.viewSubData.scalarRangeMin = float(str(self.intensityMin.text()))
        self.viewSubData.scalarRangeMax = float(str(self.intensityMax.text()))
        # logscale
        if self.logscaleCheck.isChecked():
            self.viewSubData.scale = ViewSubData.ViewSubData.LOG_SCALE
        else:
            self.viewSubData.scale = ViewSubData.ViewSubData.LINEAR_SCALE

        # color map
        self.viewSubData.colorBarPreset = str(self.colorMapCombo2.currentText())


    def freeSlicePlaneTodata(self):
        if self.freeSliceViewCheck.isChecked():
            self.viewMainData.freeSlice.visible = True
        else:
            self.viewMainData.freeSlice.visible = False

        self.viewMainData.freeSlice.org[0] = float(str(self.freeOriginX.text()))     
        self.viewMainData.freeSlice.org[1] = float(str(self.freeOriginY.text()))     
        self.viewMainData.freeSlice.org[2] = float(str(self.freeOriginZ.text()))     

        self.viewMainData.freeSlice.x[0] = float(str(self.freeX1.text()))     
        self.viewMainData.freeSlice.x[1] = float(str(self.freeX2.text()))     
        self.viewMainData.freeSlice.x[2] = float(str(self.freeX3.text()))     

        self.viewMainData.freeSlice.y[0] = float(str(self.freeY1.text()))     
        self.viewMainData.freeSlice.y[1] = float(str(self.freeY2.text()))     
        self.viewMainData.freeSlice.y[2] = float(str(self.freeY3.text()))     

        self.viewMainData.freeSlice.xbin = float(str(self.freeXbin.text()))     
        self.viewMainData.freeSlice.ybin = float(str(self.freeYbin.text()))     
        self.viewMainData.freeSlice.rangex[0] = float(str(self.freeXrangeMin.text()))     
        self.viewMainData.freeSlice.rangex[1] = float(str(self.freeXrangeMax.text()))     
        self.viewMainData.freeSlice.rangey[0] = float(str(self.freeYrangeMin.text()))     
        self.viewMainData.freeSlice.rangey[1] = float(str(self.freeYrangeMax.text()))     
        self.viewMainData.freeSlice.thickness = float(str(self.freeThickness.text()))     
        self.viewMainData.freeSlice.xdiff = float(str(self.freeSliceXdiff.text()))
        self.viewMainData.freeSlice.ydiff = float(str(self.freeSliceYdiff.text()))
        self.viewMainData.freeSlice.zdiff = float(str(self.freeSliceZdiff.text()))

# Widget To Data(基本3面スライス(スライス面情報))
#--------------------------------------
    def basicSlicePlaneTodata(self):
        if self.ax1ax2PlaneViewCheck.isChecked():
            self.viewMainData.ax3Slice.visible = True
        else:
            self.viewMainData.ax3Slice.visible = False

        if self.ax2ax3PlaneViewCheck.isChecked():
            self.viewMainData.ax1Slice.visible = True
        else:
            self.viewMainData.ax1Slice.visible = False

        if self.ax3ax1PlaneViewCheck.isChecked():
            self.viewMainData.ax2Slice.visible = True
        else:
            self.viewMainData.ax2Slice.visible = False
           
        self.viewMainData.ax1Slice.position  = str(self.ax1.text())
        self.viewMainData.ax1Slice.thickness = float(str(self.ax1Thickness.text()))
        self.viewMainData.ax2Slice.position  = str(self.ax2.text())
        self.viewMainData.ax2Slice.thickness = float(str(self.ax2Thickness.text()))
        self.viewMainData.ax3Slice.position  = str(self.ax3.text())
        self.viewMainData.ax3Slice.thickness = float(str(self.ax3Thickness.text()))

        
# Widget To Data(Axis/Grid)
#--------------------------------------
    def axisGridWidgetToData(self):
        # axis
        if self.axisViewCheck.isChecked():
            self.viewSubData.axisVisible = True
        else:
            self.viewSubData.axisVisible = False
 
        if self.axisTickCheck.isChecked():
            self.viewSubData.axisTickVisible = True
        else:
            self.viewSubData.axisTickVisible = False

        self.viewSubData.lenXaxis = float(str(self.axisLengthX.text()))
        self.viewSubData.lenYaxis = float(str(self.axisLengthY.text()))
        self.viewSubData.lenZaxis = float(str(self.axisLengthZ.text()))

        # grid
        if self.gridXYViewCheck.isChecked():
            self.viewSubData.gridXYVisible = True
        else:
            self.viewSubData.gridXYVisible = False

        if self.gridYZViewCheck.isChecked():
            self.viewSubData.gridYZVisible = True
        else:
            self.viewSubData.gridYZVisible = False

        if self.gridZXViewCheck.isChecked():
            self.viewSubData.gridZXVisible = True
        else:
            self.viewSubData.gridZXVisible = False
      
        self.viewSubData.gridSpace[0] = float(str(self.gridSpaceX.text()))
        self.viewSubData.gridSpace[1] = float(str(self.gridSpaceY.text()))
        self.viewSubData.gridSpace[2] = float(str(self.gridSpaceZ.text()))

        self.viewMainData.ax1Slice.axisTitle = str(self.ax1Title.text())
        self.viewMainData.ax2Slice.axisTitle = str(self.ax2Title.text())
        self.viewMainData.ax3Slice.axisTitle = str(self.ax3Title.text())
           
# Widget To Data(ColorBar)
#--------------------------------------
    def colorBarWidgetToData(self):
           if self.linearRadio.isChecked():
               self.viewSubData.scale = ViewSubData.ViewSubData.LINEAR_SCALE
           else:
               self.viewSubData.scale = ViewSubData.ViewSubData.LOG_SCALE

           if self.autoScale.isChecked():
               self.viewSubData.autoScale = True
           else:            
               self.viewSubData.autoScale = False

           self.viewSubData.scalarRangeMin = float(str(self.scalarRangeMinimum.text()))
           self.viewSubData.scalarRangeMax = float(str(self.scalarRangeMaximum.text()))

#================================================================================
#
# 活性制御（不要なケースでウィジェットをグレーアウト）
#
#================================================================================
# ウィジェットの活性制御
#----------------------------
    def enableControl(self):
        # Basic Slice
        # Ax1-Ax2 
        if self.ax1ax2PlaneViewCheck.isChecked():
            enable = True
        else:
            enable = False

        self.zscroll.setEnabled(enable)
        self.ax3.setEnabled(enable)
        self.ax3Thickness.setEnabled(enable)

        if self.ax2ax3PlaneViewCheck.isChecked():
            enable = True
        else:
            enable = False

        self.xscroll.setEnabled(enable)
        self.ax1.setEnabled(enable)
        self.ax1Thickness.setEnabled(enable)

        if self.ax3ax1PlaneViewCheck.isChecked():
            enable = True
        else:
            enable = False

        self.yscroll.setEnabled(enable)
        self.ax2.setEnabled(enable)
        self.ax2Thickness.setEnabled(enable)

        # Axis/Grid
        if self.axisViewCheck.isChecked():
            enable = True 
        else:
            enable = False
        self.axisLengthX.setEnabled(enable)
        self.axisLengthY.setEnabled(enable)
        self.axisLengthZ.setEnabled(enable)

        # ColorBar Setting
        if self.autoScale.isChecked():
            enable = False
        else:
            enable = True
        self.scalarRangeMinimum.setEnabled(enable)
        self.scalarRangeMaximum.setEnabled(enable)

        # # Free Slice
        # if self.sender() == self.normalVecRadio or self.sender() == self.vecVecRadio:
        #     normalVecFlag = False
        #     vecVecFlag    = False
        #     if self.normalVecRadio.isChecked():
        #         normalVecFlag = True
        #     else:
        #         normalVecFlag = False;
        #     if self.vecVecRadio.isChecked():
        #         vecVecFlag = True
        #     else:
        #         vecVecFlag = False;
                
        #     self.normVecX.setEnabled(normalVecFlag)
        #     self.normVecY.setEnabled(normalVecFlag)
        #     self.normVecZ.setEnabled(normalVecFlag)
        #     self.originX.setEnabled(normalVecFlag)
        #     self.originY.setEnabled(normalVecFlag)
        #     self.originZ.setEnabled(normalVecFlag)

        #     self.vec1X.setEnabled(vecVecFlag)
        #     self.vec1Y.setEnabled(vecVecFlag)
        #     self.vec1Z.setEnabled(vecVecFlag)
        #     self.vec2X.setEnabled(vecVecFlag)
        #     self.vec2Y.setEnabled(vecVecFlag)
        #     self.vec2Z.setEnabled(vecVecFlag)            

        # Free Slice
        if self.sender() == self.viewMethod1Radio or self.sender() == self.viewMethod2Radio:
            ppFlag = False
            paFlag = False
            if self.viewMethod1Radio.isChecked():
                ppFlag = True
                paFlag = False 
            else:
                ppFlag = False
                paFlag = True
            
            self.viewPointX.setEnabled(ppFlag)
            self.viewPointY.setEnabled(ppFlag)
            self.viewPointZ.setEnabled(ppFlag)

            self.distEdit.setEnabled(paFlag)
            self.azEdit.setEnabled(paFlag)
            self.eleEdit.setEnabled(paFlag)
           
#================================================================================
#
# スロット/シグナルの定義
#
#================================================================================
# Adjust Window Size
#-------------------------------
    def AdjustWindowSize(self):
        desktop = QtGui.qApp.desktop()
        #width  = desktop.width()
        #height = desktop.height()
        geom = desktop.availableGeometry()
        w = geom.width()
        h = geom.height()

        currentSize = self.size()
        cw = currentSize.width()
        ch = currentSize.height()
        
        if w < cw:
            cw = w
        if h < ch:
            ch = h - 30
        self.resize(cw, ch)
    
# Increase Vertical Size of Main Window
#--------------------------------------------
    def IncreaseWindowVerticalSize(self):
         desktop = QtGui.qApp.desktop()
         geom = desktop.availableGeometry()
         w = geom.width()
         h = geom.height()

         dsize = 50

         currentSize = self.size()
         cw = currentSize.width()
         ch = currentSize.height()

#         if h < (ch + dsize):
#              return 

         self.glViewH = self.glViewH + dsize
         self.glView.setMinimumSize(self.glViewW, self.glViewH)
         self.glView.setMaximumSize(self.glViewW, self.glViewH)
#        self.resize(cw, ch + dsize)

         self.minimizeMainWindowSize()

# Decrease Vertical Size of Main Window
#--------------------------------------------
    def DecreaseWindowVerticalSize(self):
        dsize = 50

        currentSize = self.size()
        cw = currentSize.width()
        ch = currentSize.height()

        self.glViewH = self.glViewH - dsize
        self.glView.setMinimumSize(self.glViewW, self.glViewH)
        self.glView.setMaximumSize(self.glViewW, self.glViewH)
#        self.resize(cw, ch - dsize)

        self.minimizeMainWindowSize()

# Increase Horizontal Size of Main Window
#--------------------------------------------
    def IncreaseWindowHorizontalSize(self):
        desktop = QtGui.qApp.desktop()
        geom = desktop.availableGeometry()
        w = geom.width()
        h = geom.height()

        dsize = 50

        currentSize = self.size()
        cw = currentSize.width()
        ch = currentSize.height()

 #       if w < (cw + dsize):
 #            return 

        self.glViewW = self.glViewW + dsize
        self.glView.setMinimumSize(self.glViewW, self.glViewH)
        self.glView.setMaximumSize(self.glViewW, self.glViewH)
#        self.resize(cw + dsize, ch)

        self.minimizeMainWindowSize()

# Decrease Horizontal Size of Main Window
#--------------------------------------------
    def DecreaseWindowHorizontalSize(self):
        dsize = 50

        currentSize = self.size()
        cw = currentSize.width()
        ch = currentSize.height()

        self.glViewW = self.glViewW - dsize
        self.glView.setMinimumSize(self.glViewW, self.glViewH)
        self.glView.setMaximumSize(self.glViewW, self.glViewH)
#        self.resize(cw - dsize, ch)

        self.minimizeMainWindowSize()

# ウィジェットの表示/非表示切替
#-------------------------------------
    def viewWidget(self, view):
        glW = self.glView.width()
        glH = self.glView.height()

        if self.sender() == self.data_load_view_action:
            if view:
                self.dataLoadWidget.show()
            else:
                self.dataLoadWidget.hide()
        elif self.sender() == self.data_info_view_action:
            if view:
                self.dataInfoWidget.show()
                self.updateDataInformation()
            else:
                self.dataInfoWidget.hide()        
        elif self.sender() == self.basic_slice_view_action:
            if view:
                self.basicSliceWidget.show()
            else:
                self.basicSliceWidget.hide()        
#        elif self.sender() == self.basic_slice_slider_view_action:
#            if view:
#                self.sliceScrollWidget.show()
#            else:
#                self.sliceScrollWidget.hide()
        elif self.sender() == self.free_slice_view_action:
            if view:
                self.freeSliceWidget.show()
            else:
                self.freeSliceWidget.hide()
        elif self.sender() == self.axis_grid_view_action:
            if view:
                self.axisGridWidget.show()                
            else:
                self.axisGridWidget.hide()         
        elif self.sender() == self.color_bar_view_action:
            if view:
                self.colorBarWidget.show()                
            else:
                self.colorBarWidget.hide()         
        elif self.sender() == self.color_bar_setting_view_action:
            if view:
                self.colorBarSettingWidget.show()                
            else:
                self.colorBarSettingWidget.hide() 
        elif self.sender() == self.view_setting_view_action:
            if view:
                self.dataToViewWidget()                 
                self.viewSettingWidget.show()
            else:
                self.viewSettingWidget.hide()
        elif self.sender() == self.label_setting_view_action:
            if view:
                self.labelSettingWidget.show()
            else:
                self.labelSettingWidget.hide()                                             

#        self.AdjustWindowSize()

        self.minimizeMainWindowSize()

    def minimizeMainWindowSize(self):
        # some events have to be processed in the event loop befoare computing minimum size
        for i in range(10):
            QtGui.QApplication.processEvents()

        # shrink main window to minimum size
        self.resize(self.minimumSizeHint())

    def adjustGlViewSizeThread(self, sleepSec, glW, glH):
        time.sleep(sleepSec)
        # currentSize = self.size()
        # cw = currentSize.width()
        # ch = currentSize.height()
        
        # cglW = self.glView.width()
        # cglH = self.glView.height()

        # dw = glW - cglW
        # dh = glH - cglH

        # self.resize(cw+dw, ch+dh)

        self.glView.resize(glW, glH)
        self.glView.update()


# データファイル選択ダイアログ
#--------------------------------
    def openFileDialog(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file', os.path.expanduser('~') + '/Desktop', "Binary File(*.srlz);; Text File(*.txt);; All Files (*)")
        if not filename: # isEmpty
            return
        self.filePath.setText(filename)
        path = self.filePath.text().toLocal8Bit().data()
        
        self.viewMainData.ReadSerializationFileBinary(path)
        title = "Slice Viewer : %s" % self.viewMainData.filePath
        #[inamura 170227]-->
        self.initializeViewer(title)
        
    def initializeViewer(self, title=""):#<--[inamura 170227]
        self.setWindowTitle(title)        
        self.dataToBasicSliceWidget()
        
        #self.viewMainData.update_slice_view_flag = False
        #self.ax1ExeButton.emit(QtCore.SIGNAL("clicked()"))
        process = ViewMainData.ViewMainData.PROCESS_MAIN
        planeID = ViewMainData.ViewMainData.SLICE_XY
        self.viewMainData.doBasicSliceView(process, planeID, "", False, False, True)
        self.viewMainData.sliceThread.join()

        planeID = ViewMainData.ViewMainData.SLICE_YZ
        self.viewMainData.doBasicSliceView(process, planeID, "", True, False, False)
        self.viewMainData.sliceThread.join()

        planeID = ViewMainData.ViewMainData.SLICE_ZX
        self.viewMainData.doBasicSliceView(process, planeID, "", False, True, False)
        self.viewMainData.sliceThread.join()
        
        self.updateAxisSize()
        self.dataToAxisGridWidget()
        self.updateGridSize()
        self.updateAxisGrid()
#        self.zoomBestFit()

        ##self.viewMainData.update_slice_view_flag = True

    def updateAxisSize(self):
        if not hasattr(self.viewMainData, 'rangex'):
            return
        # Axis 
#        self.viewSubData.lenXaxis  = (self.viewMainData.rangex[1] - self.viewMainData.rangex[0]) * self.viewMainData.basicSliceAx1Scale
#        self.viewSubData.lenYaxis  = (self.viewMainData.rangey[1] - self.viewMainData.rangey[0]) * self.viewMainData.basicSliceAx2Scale
#        self.viewSubData.lenZaxis  = (self.viewMainData.rangez[1] - self.viewMainData.rangez[0]) * self.viewMainData.basicSliceAx3Scale
#        self.viewSubData.origin[0] = (self.viewMainData.rangex[0]) * self.viewMainData.basicSliceAx1Scale
#        self.viewSubData.origin[1] = (self.viewMainData.rangey[0]) * self.viewMainData.basicSliceAx2Scale
#        self.viewSubData.origin[2] = (self.viewMainData.rangez[0]) * self.viewMainData.basicSliceAx3Scale

        self.viewSubData.lenXaxis  = (self.viewMainData.rangex[1] - self.viewMainData.rangex[0])
        self.viewSubData.lenYaxis  = (self.viewMainData.rangey[1] - self.viewMainData.rangey[0])
        self.viewSubData.lenZaxis  = (self.viewMainData.rangez[1] - self.viewMainData.rangez[0])
        self.viewSubData.origin[0] = (self.viewMainData.rangex[0])
        self.viewSubData.origin[1] = (self.viewMainData.rangey[0])
        self.viewSubData.origin[2] = (self.viewMainData.rangez[0])

        #----
#        self.viewSubData.updateAxis()

    def updateGridSize(self):
        # Grid
        if not hasattr(self.viewMainData, 'rangex'):
            return

        self.viewSubData.gridSize[0] =  (self.viewMainData.rangex[1] - self.viewMainData.rangex[0])
        self.viewSubData.gridSize[1] =  (self.viewMainData.rangey[1] - self.viewMainData.rangey[0])
        self.viewSubData.gridSize[2] =  (self.viewMainData.rangez[1] - self.viewMainData.rangez[0])
        self.viewSubData.gridPos[0]  = self.viewMainData.data_yz_pos
        self.viewSubData.gridPos[1]  = self.viewMainData.data_zx_pos
        self.viewSubData.gridPos[2]  = self.viewMainData.data_xy_pos
        self.viewSubData.gridScaleX  = self.viewMainData.basicSliceAx1Scale
        self.viewSubData.gridScaleY  = self.viewMainData.basicSliceAx2Scale
        self.viewSubData.gridScaleZ  = self.viewMainData.basicSliceAx3Scale

# Update Data Information
#-----------------------------
    def updateDataInformation(self):
        #if not hasattr(self.viewMainData, 'data_ecm'): #[inamura 170227]
        if self.viewMainData.data_ecm==None:
            self.dataInfo.setPlainText("File Path: ---\n")
            return
        
        str = ""
        # file path
        str = str + "FilePath: %s\n" % self.viewMainData.filePath

        # keys
        str = str + "Keys:   %s,   %s,   %s\n" \
             % (self.viewMainData.ax1Key, self.viewMainData.ax2Key, self.viewMainData.ax3Key)

        # x range
        str = str + "X Range:   %g,  %g\n" % (self.viewMainData.rangex[0], self.viewMainData.rangex[1])
        # y range
        str = str + "Y Range:   %g,  %g\n" % (self.viewMainData.rangey[0], self.viewMainData.rangey[1])
        # z range
        str = str + "Z Range:   %g,  %g\n" % (self.viewMainData.rangez[0], self.viewMainData.rangez[1])

        # bin
        str = str + "bin(dX, dY, dZ):   %g,  %g,   %g\n" \
             % (self.viewMainData.basicSliceAx1bin, self.viewMainData.basicSliceAx2bin, self.viewMainData.basicSliceAx3bin)

        self.dataInfo.setPlainText(str)
        pass
              
# Update Data Information
#-----------------------------
    def updateBasicSlice(self):
        #if not hasattr(self.viewMainData, 'data_ecm'): #[inamura 170227]
        if self.viewMainData.data_ecm==None:
            return
        #self.viewMainData.ax1Slice.position = str(self.viewMainData.rangex[0])
        #self.viewMainData.ax2Slice.position = str(self.viewMainData.rangey[0])
        #self.viewMainData.ax3Slice.position = str(self.viewMainData.rangez[0])

        self.dataToBasicSliceWidget()


# 旧：ファイル読み込みボタンクリック(現在不使用)
#-------------------------------------------------
    def loadFile(self):
        path = self.filePath.text()
        self.viewMainData.ReadSerializationFileBinary(path)
        title = "Slice Viewer : %s" % self.viewMainData.filePath
        self.setWindowTitle(title)
        #QApplication.restoreOverrideCursor()

#-------------------------------------------------
# Update Axis grid origin
#-------------------------------------------------
    def updateAxisGridOrigin(self):
        self.viewSubData.setOrigin(self.viewMainData.rangex[0], self.viewMainData.rangey[0], self.viewMainData.rangez[0])        
        self.viewSubData.updateAxis()
        self.viewSubData.updateAxisTick()
        self.viewSubData.updateGrid()
        self.viewSubData.updateAxisLabel()
        self.glView.update()


    def onClickViewRangeApplyButton(self):
        if hasattr(self, "freeSliceItem"):
            ax1Scale = float(str(self.ax1ViewScale.text()))            
            ax2Scale = float(str(self.ax2ViewScale.text()))            
            ax3Scale = float(str(self.ax3ViewScale.text()))
            if ax1Scale != 1.0 or ax2Scale != 1.0 or ax3Scale != 1.0:
                msg    = "The free slice plane will be removed since given view scale is not equal 1.0. Are you sure you want to continue?"
                reply = QtGui.QMessageBox.question(self, 'Confirm', msg, QtGui.QMessageBox.Yes| QtGui.QMessageBox.No| QtGui.QMessageBox.Cancel)
                if reply != QtGui.QMessageBox.Yes:
                    return
                self.glView.addItem(self.freeSliceItem)
                del self.freeSliceItem

        self.widgetToDataForBasicSliceViewRange()
        self.updateColorBar()
        self.updateAxisSize()
        self.updateGridSize()
        self.updateAxisGrid()

#********************************************
# 基本3面関連ボタンクリック
#********************************************
# 基本スライス面の作成
#-------------------------------------------------
    def createBasicSliceItem(self, args):
        planeID = float(args[0])

        #[inamura 180516]-->
        #gradient = pg.GradientEditorItem()
        #gradient.loadPreset(self.viewSubData.colorBarPreset)
        nPts = 200
        #lookuptable = gradient.getLookupTable(nPts, alpha=None)
        if self.viewSubData.colorBarPreset in self.colorMap_utsusemi.keys():
            cbar,lut = self.colorMap_utsusemi[self.viewSubData.colorBarPreset]
            lookuptable=lut
            self.colorBar.setColorMap( cbar )
            for i in range(len(self.colorBar.item.listTicks())):
                wt = self.colorBar.item.getTick(i)
                wt.setVisible(False)
        else:
            gradient = pg.GradientEditorItem()
            gradient.loadPreset(self.viewSubData.colorBarPreset)
            lookuptable = gradient.getLookupTable(nPts, alpha=None)
        ##<--[inamura 180516]

        scalarRange = (self.viewSubData.scalarRangeMin, self.viewSubData.scalarRangeMax)
        if self.viewSubData.scale == ViewSubData.ViewSubData.LOG_SCALE:
            scalarRange = (math.log10(self.viewSubData.scalarRangeMin), math.log10(self.viewSubData.scalarRangeMax))

        logOffset = 1e-16
        xmin = self.viewMainData.rangex[0]
        ymin = self.viewMainData.rangey[0]
        zmin = self.viewMainData.rangez[0]
        scaleX = 1.0
        scaleY = 1.0
        scaleZ = 1.0
        posX = 0.0
        posY = 0.0
        posZ = 0.0 

        if planeID == ViewMainData.ViewMainData.SLICE_XY:
            dx = self.viewMainData.basicSliceAx1From - self.viewMainData.data_xy_range[0]
            idx0 = int(round(dx/self.viewMainData.data_ax1bin))
            dx = self.viewMainData.basicSliceAx1To   - self.viewMainData.data_xy_range[0]
            idx1 = int(round(dx/self.viewMainData.data_ax1bin))

            dy = self.viewMainData.basicSliceAx2From - self.viewMainData.data_xy_range[2]
            idy0 = int(round(dy/self.viewMainData.data_ax2bin))
            dy = self.viewMainData.basicSliceAx2To   - self.viewMainData.data_xy_range[2]
            idy1 = int(round(dy/self.viewMainData.data_ax2bin))

            extractData = self.viewMainData.data_xy[idx0:idx1+1, idy0:idy1+1]
#            print self.viewMainData.data_xy.shape
#            print idx0, idx1, idy0, idy1
#            print extractData.shape

            if self.viewSubData.scale == ViewSubData.ViewSubData.LINEAR_SCALE:
#                tex = pg.makeARGB(self.viewMainData.data_xy, lut = lookuptable, levels = scalarRange, useRGBA = True)[0]
#                self.basicSliceItemXY = gl.GLImageItem(tex)
                tex = pg.makeARGB(extractData, lut = lookuptable, levels = scalarRange, useRGBA = True)[0]
                self.basicSliceItemXY = gl.GLImageItem(tex)
            elif self.viewSubData.scale == ViewSubData.ViewSubData.LOG_SCALE:
                #tmp = np.log10(self.viewMainData.data_xy + logOffset)
                tmp = np.log10(extractData + logOffset)
                tex = pg.makeARGB(tmp, lut = lookuptable, levels = scalarRange, useRGBA = True)[0]
                self.basicSliceItemXY = gl.GLImageItem(tex)

            if self.viewSubData.transFlag:
                self.basicSliceItemXY.setGLOptions('additive')
                #self.basicSliceItemXY.setGLOptions('translucent') #[inamura 180516]

            scaleX = self.viewMainData.basicSliceAx1Scale * self.viewMainData.data_ax1bin
            scaleY = self.viewMainData.basicSliceAx2Scale * self.viewMainData.data_ax2bin
            scaleZ = 1.0
            self.basicSliceItemXY.scale(scaleX, scaleY, scaleZ)
#            self.basicSliceItemXY.scale(self.viewMainData.basicSliceAx1bin, self.viewMainData.basicSliceAx2bin, 1.0)
#            posX = xmin                          * self.viewMainData.basicSliceAx1Scale
#            posY = ymin                          * self.viewMainData.basicSliceAx2Scale

            posX = (self.viewMainData.data_xy_range[0] + idx0 * self.viewMainData.data_ax1bin) * self.viewMainData.basicSliceAx1Scale
            posY = (self.viewMainData.data_xy_range[2] + idy0 * self.viewMainData.data_ax2bin) * self.viewMainData.basicSliceAx2Scale
            posZ = self.viewMainData.data_xy_pos * self.viewMainData.basicSliceAx3Scale

            self.basicSliceItemXY.translate(posX, posY, posZ)
#            self.basicSliceItemXY.translate(xmin, ymin, self.viewMainData.data_xy_pos)
        elif planeID == ViewMainData.ViewMainData.SLICE_YZ:
            dx = self.viewMainData.basicSliceAx2From - self.viewMainData.data_yz_range[0]
            idx0 = int(round(dx/self.viewMainData.data_ax2bin))
            dx = self.viewMainData.basicSliceAx2To   - self.viewMainData.data_yz_range[0]
            idx1 = int(round(dx/self.viewMainData.data_ax2bin))

            dy = self.viewMainData.basicSliceAx3From - self.viewMainData.data_yz_range[2]
            idy0 = int(round(dy/self.viewMainData.data_ax3bin))
            dy = self.viewMainData.basicSliceAx3To   - self.viewMainData.data_yz_range[2]
            idy1 = int(round(dy/self.viewMainData.data_ax3bin))

            extractData = self.viewMainData.data_yz[idx0:idx1+1, idy0:idy1+1]

            if self.viewSubData.scale == ViewSubData.ViewSubData.LINEAR_SCALE:
                #tex = pg.makeARGB(self.viewMainData.data_yz, lut = lookuptable, levels = scalarRange, useRGBA = True)[0]
                tex = pg.makeARGB(extractData, lut = lookuptable, levels = scalarRange, useRGBA = True)[0]
                self.basicSliceItemYZ = gl.GLImageItem(tex)
            elif self.viewSubData.scale == ViewSubData.ViewSubData.LOG_SCALE:
                #tmp = np.log10(self.viewMainData.data_yz + logOffset)
                tmp = np.log10(extractData + logOffset)
                tex = pg.makeARGB(tmp, lut = lookuptable, levels = scalarRange, useRGBA = True)[0]
                self.basicSliceItemYZ = gl.GLImageItem(tex)

            if self.viewSubData.transFlag:
                self.basicSliceItemYZ.setGLOptions('additive')
                #self.basicSliceItemYZ.setGLOptions('translucent') #[inamura 180516]

            scaleX = self.viewMainData.basicSliceAx2Scale * self.viewMainData.data_ax2bin
            scaleY = self.viewMainData.basicSliceAx3Scale * self.viewMainData.data_ax3bin
            scaleZ = 1.0
            self.basicSliceItemYZ.scale(scaleX, scaleY, scaleZ)

#            self.basicSliceItemYZ.scale(self.viewMainData.basicSliceAx2bin, self.viewMainData.basicSliceAx3bin, 1.0)
            self.basicSliceItemYZ.rotate(90, 0, 0, 1)
            self.basicSliceItemYZ.rotate(90, 0, 1, 0)
            posX = self.viewMainData.data_yz_pos * self.viewMainData.basicSliceAx1Scale
            posY = (self.viewMainData.data_yz_range[0] + idx0 * self.viewMainData.data_ax2bin) * self.viewMainData.basicSliceAx2Scale
            posZ = (self.viewMainData.data_yz_range[2] + idy0 * self.viewMainData.data_ax3bin) * self.viewMainData.basicSliceAx3Scale
#            posY = ymin                          * self.viewMainData.basicSliceAx2Scale
#            posZ = zmin                          * self.viewMainData.basicSliceAx3Scale
            self.basicSliceItemYZ.translate(posX, posY, posZ)
#            self.basicSliceItemYZ.translate(self.viewMainData.data_yz_pos, ymin, zmin)
        elif planeID == ViewMainData.ViewMainData.SLICE_ZX:
            dx = self.viewMainData.basicSliceAx1From - self.viewMainData.data_zx_range[0]
            idx0 = int(round(dx/self.viewMainData.data_ax1bin))
            dx = self.viewMainData.basicSliceAx1To   - self.viewMainData.data_zx_range[0]
            idx1 = int(round(dx/self.viewMainData.data_ax1bin))

            dy = self.viewMainData.basicSliceAx3From - self.viewMainData.data_zx_range[2]
            idy0 = int(round(dy/self.viewMainData.data_ax3bin))
            dy = self.viewMainData.basicSliceAx3To   - self.viewMainData.data_zx_range[2]
            idy1 = int(round(dy/self.viewMainData.data_ax3bin))

            extractData = self.viewMainData.data_zx[idx0:idx1+1, idy0:idy1+1]

            if self.viewSubData.scale == ViewSubData.ViewSubData.LINEAR_SCALE:
#                tex = pg.makeARGB(self.viewMainData.data_zx, lut = lookuptable, levels = scalarRange, useRGBA = True)[0]
                tex = pg.makeARGB(extractData, lut = lookuptable, levels = scalarRange, useRGBA = True)[0]
                self.basicSliceItemZX = gl.GLImageItem(tex)
            elif self.viewSubData.scale == ViewSubData.ViewSubData.LOG_SCALE:
#                tmp = np.log10(self.viewMainData.data_zx + logOffset)
                tmp = np.log10(extractData + logOffset)
                tex = pg.makeARGB(tmp, lut = lookuptable, levels = scalarRange, useRGBA = True)[0]
                self.basicSliceItemZX = gl.GLImageItem(tex)

            if self.viewSubData.transFlag:
                self.basicSliceItemZX.setGLOptions('additive')
                #self.basicSliceItemZX.setGLOptions('translucent') #[inamura 180516]

            scaleX = self.viewMainData.basicSliceAx1Scale * self.viewMainData.data_ax1bin
            scaleY = self.viewMainData.basicSliceAx3Scale * self.viewMainData.data_ax3bin
            scaleZ = 1.0
            self.basicSliceItemZX.scale(scaleX, scaleY, scaleZ)

#            self.basicSliceItemZX.scale(self.viewMainData.basicSliceAx1bin, self.viewMainData.basicSliceAx3bin, 1.0)
            self.basicSliceItemZX.rotate(90, 1, 0, 0)
#            posX = xmin                          * self.viewMainData.basicSliceAx1Scale
            posX = (self.viewMainData.data_zx_range[0] + idx0 * self.viewMainData.data_ax1bin) * self.viewMainData.basicSliceAx1Scale
            posY = self.viewMainData.data_zx_pos * self.viewMainData.basicSliceAx2Scale
            posZ = (self.viewMainData.data_zx_range[2] + idy0 * self.viewMainData.data_ax3bin) * self.viewMainData.basicSliceAx3Scale
#            posZ = zmin                          * self.viewMainData.basicSliceAx3Scale

            self.basicSliceItemZX.translate(posX, posY, posZ)
#            self.basicSliceItemZX.translate(xmin, self.viewMainData.data_zx_pos, zmin)

# Freeスライス面の作成
#-------------------------------------------------
    def createFreeSliceItem(self, args):
#        planeID = float(args[0])

        gradient = pg.GradientEditorItem()
        gradient.loadPreset(self.viewSubData.colorBarPreset)
        nPts = 200
        lookuptable = gradient.getLookupTable(nPts, alpha=None)

        scalarRange = (self.viewSubData.scalarRangeMin, self.viewSubData.scalarRangeMax)
        if self.viewSubData.scale == ViewSubData.ViewSubData.LOG_SCALE:
            scalarRange = (math.log10(self.viewSubData.scalarRangeMin), math.log10(self.viewSubData.scalarRangeMax))

        logOffset = 1e-16
        xmin = self.viewMainData.freeSlice.rangex[0]
        ymin = self.viewMainData.freeSlice.rangey[0]

        scaleX = 1.0
        scaleY = 1.0
        scaleZ = 1.0
        posX = 0.0
        posY = 0.0
        posZ = 0.0 


        if self.viewSubData.scale == ViewSubData.ViewSubData.LINEAR_SCALE:
            tex = pg.makeARGB(self.viewMainData.data_free, lut = lookuptable, levels = scalarRange, useRGBA = True)[0]
            self.freeSliceItem = gl.GLImageItem(tex)
        elif self.viewSubData.scale == ViewSubData.ViewSubData.LOG_SCALE:
            tmp = np.log10(self.viewMainData.data_free + logOffset)
            tex = pg.makeARGB(tmp, lut = lookuptable, levels = scalarRange, useRGBA = True)[0]
            self.freeSliceItem = gl.GLImageItem(tex)

        if self.viewSubData.transFlag:
            self.freeSliceItem.setGLOptions('additive')
            #self.freeSliceItem.setGLOptions('translucent') #[inamura 180516]
             
        scaleX = self.viewMainData.freeSlice.xbin
        scaleY = self.viewMainData.freeSlice.ybin
        scaleZ = 1.0
        self.freeSliceItem.scale(scaleX, scaleY, scaleZ)
        self.rotateItem(self.freeSliceItem, self.viewMainData.freeSlice.org,  
                   self.viewMainData.freeSlice.x, self.viewMainData.freeSlice.y)


#            self.basicSliceItemXY.scale(self.viewMainData.basicSliceAx1bin, self.viewMainData.basicSliceAx2bin, 1.0)
#            posX = xmin                          * self.viewMainData.basicSliceAx1Scale
#            posY = ymin                          * self.viewMainData.basicSliceAx2Scale

#            posX = (self.viewMainData.data_xy_range[0] + idx0 * self.viewMainData.data_ax1bin) * self.viewMainData.basicSliceAx1Scale
#            posY = (self.viewMainData.data_xy_range[2] + idy0 * self.viewMainData.data_ax2bin) * self.viewMainData.basicSliceAx2Scale
#            posZ = self.viewMainData.data_xy_pos * self.viewMainData.basicSliceAx3Scale

#            self.basicSliceItemXY.translate(posX, posY, posZ)
#            self.basicSliceItemXY.translate(xmin, ymin, self.viewMainData.data_xy_pos)

    def rotateItem(self, item, org, newX, newY):
        eps = 1e-6
            
        vecX = np.array(newX) - np.array(org)
        vecY = np.array(newY) - np.array(org)
        tmpVec = np.array(newX) - np.array(org)
        tmpVec[2] = 0.0        

        #print "%f" % (self.extMath.getAngle(vecX, vecY).item()*180.0/math.pi)

        
        ex = np.array([1, 0, 0])
        ey = np.array([0, 1, 0])
        ez = np.array([0, 0, 1])          
        
        az  = self.extMath.getAngle(ex, tmpVec).item()
        ele = self.extMath.getAngle(vecX, tmpVec).item()

        #print ele*180.0/math.pi
        
        # (1) Z軸(rotAxis1)を中心に方位方向への回転
        #     azは方位角でなく、ベクトル間の角度のため、rotAxis1は(0, 0, -1)に沿ったベクトルになることもありうる。
        
        rotAxis1 = np.cross(ex, tmpVec)
        
        tmp = self.extMath.rotateAroundVector(rotAxis1, az, ex)
        v1x = np.array(tmp)[0]
        tmp = self.extMath.rotateAroundVector(rotAxis1, az, ey)
        v1y = np.array(tmp)[0]


        # (2)
        rotAxis2 = np.cross(v1x, vecX)
        tmp = self.extMath.rotateAroundVector(rotAxis2, ele, v1x)
        v2x = np.array(tmp)[0]        
        tmp = self.extMath.rotateAroundVector(rotAxis2, ele, v1y)
        v2y = np.array(tmp)[0]        

        #print "%f" % (self.extMath.getAngle(vecX, v2x).item()*180.0/math.pi)

        # (3)
        delTheta = self.extMath.getAngle(vecY, v2y).item()
        rotAxis3 = np.cross(v2y, vecY)
        #print rotAxis3
        #print v2x

        # check
        tmp = self.extMath.rotateAroundVector(rotAxis3, delTheta, v2y)
        v3y = np.array(tmp)[0]
        #print "%f" % (self.extMath.getAngle(vecY, v3y).item()*180.0/math.pi)
        

        if isinstance(item, gl.GLImageItem):
            item.rotate(az*180.0/math.pi,  (rotAxis1[0].item()), (rotAxis1[1].item()), (rotAxis1[2].item()))
            item.rotate(ele*180.0/math.pi, (rotAxis2[0].item()), (rotAxis2[1].item()), (rotAxis2[2].item()))
            item.rotate(delTheta*180.0/math.pi, (rotAxis3[0].item()), (rotAxis3[1].item()), (rotAxis3[2].item()))
            item.translate(org[0], org[1], org[2]) 
            

# 基本3面Auto Button
#----------------------------------------------------------------------
    def basicSliceAutoRangeX(self):
        self.ax1From.setText(str(self.viewMainData.rangex[0]))
        self.ax1To.setText(str(self.viewMainData.rangex[1]))

    def basicSliceAutoRangeY(self):
        self.ax2From.setText(str(self.viewMainData.rangey[0]))
        self.ax2To.setText(str(self.viewMainData.rangey[1]))

    def basicSliceAutoRangeZ(self):
        self.ax3From.setText(str(self.viewMainData.rangez[0]))
        self.ax3To.setText(str(self.viewMainData.rangez[1]))


    def basicSliceAutoIntensity(self):
        self.intensityMin.setText(str('%.1e' % self.viewMainData.minIntensity.min()))
        self.intensityMax.setText(str('%.1e' % self.viewMainData.maxIntensity.max()))
        

# 基本3面Exe関連ボタンクリック(Apply, M2Plot, Save as Image, Save as ECA)
#----------------------------------------------------------------------
    def doBasicSliceView(self):
        process = ViewMainData.ViewMainData.PROCESS_M2PLOT
        # process
        if self.sender() == self.M2plotButton:
            process = ViewMainData.ViewMainData.PROCESS_M2PLOT
        elif self.sender() == self.basicSliceApplyButton:
            process = ViewMainData.ViewMainData.PROCESS_MAIN
        elif self.sender() == self.view_screenshot_action:
#        elif self.sender() == self.saveImageButton:
            process = ViewMainData.ViewMainData.PROCESS_OUT_IMAGE
        elif self.sender() == self.saveECAButton:
            process = ViewMainData.ViewMainData.PROCESS_OUT_BINARY
        
        self.doBasicSliceView2(process)
        
    def doBasicSliceView2(self, process):
        #if not hasattr(self.viewMainData, 'data_ecm'): #[inamura 170227]
        if self.viewMainData.data_ecm==None:
            msgbox = QtGui.QMessageBox.warning(self, 'Error', 'Please load a data file first.')
            return

        if self.viewMainData.isThreadRunning():
            msgbox = QtGui.QMessageBox.warning(self, 'Error', 'An other thread is running.')
            return 

        planeID = ViewMainData.ViewMainData.SLICE_XY

#         process = ViewMainData.ViewMainData.PROCESS_M2PLOT
#         # process
#         if self.sender() == self.M2plotButton:
#             process = ViewMainData.ViewMainData.PROCESS_M2PLOT
#         elif self.sender() == self.basicSliceApplyButton:
#             process = ViewMainData.ViewMainData.PROCESS_MAIN
#         elif self.sender() == self.view_screenshot_action:
# #        elif self.sender() == self.saveImageButton:
#             process = ViewMainData.ViewMainData.PROCESS_OUT_IMAGE
#         elif self.sender() == self.saveECAButton:
#             process = ViewMainData.ViewMainData.PROCESS_OUT_BINARY

        # outputPath
        outputPath = ""
        root, ext = os.path.splitext(str(self.viewMainData.filePath))
        if process == ViewMainData.ViewMainData.PROCESS_OUT_IMAGE:
            defaultPath = root + ".png"
            outputPath = QtGui.QFileDialog.getSaveFileName(self, 'Save file', defaultPath, "PNG file (*.png);; All Files (*)")
            if not outputPath: # isEmpty
                return
        if process == ViewMainData.ViewMainData.PROCESS_OUT_BINARY:
            defaultPath = root
            outputPath = QtGui.QFileDialog.getSaveFileName(self, 'Save file', defaultPath, "All Files (*)")
            if not outputPath: # isEmpty
                return

        #---
        ax3Changed = False
        if self.viewMainData.ax3Slice.position  != str(self.ax3.text()) or \
           str(self.viewMainData.ax3Slice.thickness) != str(self.ax3Thickness.text()):
           ax3Changed = True
        ax1Changed = False
        if self.viewMainData.ax1Slice.position  != str(self.ax1.text()) or \
           str(self.viewMainData.ax1Slice.thickness) != str(self.ax1Thickness.text()):
           ax1Changed = True
        ax2Changed = False
        if self.viewMainData.ax2Slice.position  != str(self.ax2.text()) or \
           str(self.viewMainData.ax2Slice.thickness) != str(self.ax2Thickness.text()):
           ax2Changed = True

        ax1Token = []
        ax2Token = []
        ax3Token = []
        if process == ViewMainData.ViewMainData.PROCESS_OUT_IMAGE:
            ax1Changed = ax2Changed = ax3Changed = False
            ax1Token = str(self.ax1.text()).split(":")
            if len(ax1Token) > 1:
                ax1Changed = True
            ax2Token = str(self.ax2.text()).split(":")
            if len(ax2Token) > 1:
                ax2Changed = True
            ax3Token = str(self.ax3.text()).split(":")
            if len(ax3Token) > 1:
                ax3Changed = True

            if ax1Changed == False and \
               ax2Changed == False and \
               ax3Changed == False:
               ax1Changed = True

        self.basicSlicePlaneTodata()
        self.updateScrollbarRange()

#        if process == ViewMainData.ViewMainData.PROCESS_MAIN:
        if process == ViewMainData.ViewMainData.PROCESS_MAIN or\
           process == ViewMainData.ViewMainData.PROCESS_OUT_IMAGE:
            self.viewMainData.doBasicSliceView(process, planeID, outputPath, ax1Changed, ax2Changed, ax3Changed)
            # if ax3Changed:
            #     planeID = ViewMainData.ViewMainData.SLICE_XY
            #     self.viewMainData.doBasicSliceView(process, planeID, outputPath)
            #     self.viewMainData.sliceThread.join()
            # if ax1Changed:
            #     planeID = ViewMainData.ViewMainData.SLICE_YZ
            #     self.viewMainData.doBasicSliceView(process, planeID, outputPath)
            #     self.viewMainData.sliceThread.join()
            # if ax2Changed:
            #     planeID = ViewMainData.ViewMainData.SLICE_ZX
            #     self.viewMainData.doBasicSliceView(process, planeID, outputPath)
            #     self.viewMainData.sliceThread.join()                
#        elif process == ViewMainData.ViewMainData.PROCESS_OUT_IMAGE:
#            self.viewMainData.doBasicSliceView(process, planeID, outputPath, True, True, True)

#        elif process == ViewMainData.ViewMainData.PROCESS_M2PLOT or \
#             process == ViewMainData.ViewMainData.PROCESS_OUT_IMAGE or \
#             process == ViewMainData.ViewMainData.PROCESS_OUT_BINARY:
        elif process == ViewMainData.ViewMainData.PROCESS_M2PLOT or \
             process == ViewMainData.ViewMainData.PROCESS_OUT_BINARY:
               planeID = self.slicePlane.currentIndex()
               self.viewMainData.doBasicSliceView(process, planeID, outputPath)

# stop basic slicing
#----------------------------
    def cancelBasicSliceView(self):
        if not self.viewMainData.isThreadRunning():
            msgbox = QtGui.QMessageBox.warning(self, 'Error', 'No thread is running.')
            return 
        
        #replay = QtGui.QMessageBox.question(self, "Message", "Are you sure to stop the running thread?", \
        #         QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
        #if replay == QtGui.QMessageBox.No:
        #    return

        self.viewMainData.stop_event.set()
        self.viewMainData.sliceThread.join()
   
        #msgbox = QtGui.QMessageBox.information(self, '', 'The thread was stopped.')

# スライダーバーによる3面表示の更新 X
#--------------------------------------------
    def onXSliderPressed(self):
        self.xScrollPressed = True

    def onXSliderReleased(self):
        self.xScrollPressed = False
        self.onXScrollbarChanged("")

    def onXScrollbarActionTriggered(self):
        self.xScrollTriggered = True

    def onXScrollbarChanged(self,evt):
        if not hasattr(self, "basicSliceItemYZ") or not self.viewMainData.ax1Slice.visible:
            return

        # value = self.xscroll.value()
        # maxValue = self.viewSubData.xscrollMax
        # rangex   = self.viewMainData.rangex
        # r = float(value)/float(maxValue)
        # pos = (rangex[1]-rangex[0])*r + rangex[0]
        value = self.xscroll.value()
        rangex = self.viewMainData.rangex
        pos = rangex[0] + float(value) * self.viewMainData.ax1Slice.thickness

        #print "r = %f, pos = %f, value = %f @ onscroll" % (r, pos, float(value))

        if self.xScrollPressed or not self.xScrollTriggered:
        # The slider is moving
            if self.xScrollPressed:
                self.viewMainData.ax1Slice.position = str(pos)
                self.ax1.setText(self.viewMainData.ax1Slice.position)
            return

        process = ViewMainData.ViewMainData.PROCESS_MAIN
        planeID = ViewMainData.ViewMainData.SLICE_YZ
        
        self.viewMainData.ax1Slice.position = str(pos)

        # wait for avoiding multiple cast
        time.sleep(0.25)
        self.viewMainData.doBasicSliceView(process, planeID, "", True, False, False)
        self.viewMainData.sliceThread.join()
        self.dataToBasicSliceWidget()
        self.updateGridSize()
        self.updateGrid()

        self.xScrollTriggered = False

# スライダーバーによる3面表示の更新 Y
#--------------------------------------------
    def onYSliderPressed(self):
        self.yScrollPressed = True

    def onYSliderReleased(self):
        self.yScrollPressed = False
        self.onYScrollbarChanged("")

    def onYScrollbarActionTriggered(self):
        self.yScrollTriggered = True

    def onYScrollbarChanged(self,evt):
        if not hasattr(self, "basicSliceItemZX") or not self.viewMainData.ax2Slice.visible:
            return

        # value = self.yscroll.value()
        # maxValue = self.viewSubData.yscrollMax
        # rangey   = self.viewMainData.rangey
        # r = float(value)/float(maxValue)
        # pos = (rangey[1]-rangey[0])*r + rangey[0]

        value = self.yscroll.value()
        rangey = self.viewMainData.rangey
        pos = rangey[0] + float(value) * self.viewMainData.ax2Slice.thickness

        if self.yScrollPressed or not self.yScrollTriggered:
        # The slider is moving
            if self.yScrollPressed:
                self.viewMainData.ax2Slice.position = str(pos)
                self.ax2.setText(self.viewMainData.ax2Slice.position)
            return

        process = ViewMainData.ViewMainData.PROCESS_MAIN
        planeID = ViewMainData.ViewMainData.SLICE_ZX
        
        self.viewMainData.ax2Slice.position = str(pos)
        #self.ax3.setText(self.viewMainData.ax3Slice.position)

        # wait for avoiding multiple cast
        time.sleep(0.25)
        self.viewMainData.doBasicSliceView(process, planeID, "", False, True, False)
        self.viewMainData.sliceThread.join()
        self.dataToBasicSliceWidget()
        self.updateGridSize()
        self.updateGrid()

        self.yScrollTriggered = False

# スライダーバーによる3面表示の更新 Z
#--------------------------------------------
    def onZSliderPressed(self):
        self.zScrollPressed = True

    def onZSliderReleased(self):
        self.zScrollPressed = False
        self.onZScrollbarChanged("")

    def onZScrollbarActionTriggered(self):
        self.zScrollTriggered = True

    def onZScrollbarChanged(self,evt):
        if not hasattr(self, "basicSliceItemXY") or not self.viewMainData.ax3Slice.visible:
            return

        # value = self.zscroll.value()
        # maxValue = self.viewSubData.zscrollMax
        # rangez   = self.viewMainData.rangez
        # r = float(value)/float(maxValue)
        # pos = (rangez[1]-rangez[0])*r + rangez[0]
              
        value = self.zscroll.value()
        rangez = self.viewMainData.rangez
        pos = rangez[0] + float(value) * self.viewMainData.ax3Slice.thickness

        if self.zScrollPressed or not self.zScrollTriggered:
        # The slider is moving
            if self.zScrollPressed:
                self.viewMainData.ax3Slice.position = str(pos)
                self.ax3.setText(self.viewMainData.ax3Slice.position)
            return
      
        self.zScrollTriggered = False
        process = ViewMainData.ViewMainData.PROCESS_MAIN
        planeID = ViewMainData.ViewMainData.SLICE_XY
        
        self.viewMainData.ax3Slice.position = str(pos)
        #self.ax3.setText(self.viewMainData.ax3Slice.position)

        # wait for avoiding multiple cast
        time.sleep(0.25)
        self.viewMainData.doBasicSliceView(process, planeID, "", False, False, True)
        self.viewMainData.sliceThread.join()
        self.dataToBasicSliceWidget()
        self.updateGridSize()
        self.updateGrid()

# 任意面表示ボタンクリック
#----------------------------
    def doFreeSliceViewSlot(self):
        process = ViewMainData.ViewMainData.PROCESS_M2PLOT
        #process
        if self.sender() == self.freeSliceM2plotButton:
            process = ViewMainData.ViewMainData.PROCESS_M2PLOT
        elif self.sender() == self.freeSliceExeButton:
            process = ViewMainData.ViewMainData.PROCESS_MAIN
#        else self.sender() == self.view_screenshot_action:
        elif self.sender() == self.freeSliceSaveECAButton:
            process = ViewMainData.ViewMainData.PROCESS_OUT_BINARY
        
        self.doFreeSliceView(process)

    def doFreeSliceView(self, process):
        #if not hasattr(self.viewMainData, 'data_ecm'): #[inamura 170227]
        if self.viewMainData.data_ecm==None:
            msgbox = QtGui.QMessageBox.warning(self, 'Error', 'Please load a data file first.')
            return

        if self.viewMainData.isThreadRunning():
            msgbox = QtGui.QMessageBox.warning(self, 'Error', 'An other thread is running.')
            return

        self.freeSlicePlaneTodata()
        if self.viewMainData.freeSlice.checkPlaneAngle() == False:
            msg    = "The specified plane is not rectangle (angle = %f)." % (self.viewMainData.freeSlice.getPlaneAngle()*180.0/math.pi)
            msgbox = QtGui.QMessageBox.warning(self, 'Error', msg)
            return

        scalex = self.viewMainData.basicSliceAx1Scale
        scaley = self.viewMainData.basicSliceAx2Scale
        scalez = self.viewMainData.basicSliceAx3Scale

        if scalex != 1.0 or scaley != 1.0 or scalez != 1.0:
            msg = "View scale has to be set to (1, 1, 1)."
            msgbox = QtGui.QMessageBox.warning(self, 'Error', msg)
            return
        
        # process = ViewMainData.ViewMainData.PROCESS_M2PLOT
#         #process
#         if self.sender() == self.freeSliceM2plotButton:
#             process = ViewMainData.ViewMainData.PROCESS_M2PLOT
#         elif self.sender() == self.freeSliceExeButton:
#             process = ViewMainData.ViewMainData.PROCESS_MAIN
# #        else self.sender() == self.view_screenshot_action:
#         elif self.sender() == self.freeSliceSaveECAButton:
#             process = ViewMainData.ViewMainData.PROCESS_OUT_BINARY

        # outputpath
        outputPath = ""
        root, ext = os.path.splitext(str(self.viewMainData.filePath))
        if process == ViewMainData.ViewMainData.PROCESS_OUT_IMAGE:
            defaultPath = root + ".png"
            outputPath = QtGui.QFileDialog.getSaveFileName(self, 'Save file', defaultPath, "PNG file (*.png);; All Files (*)")
            if not outputPath: # isEmpty
                return
        if process == ViewMainData.ViewMainData.PROCESS_OUT_BINARY:
            defaultPath = root
            outputPath = QtGui.QFileDialog.getSaveFileName(self, 'Save file', defaultPath, "All Files (*)")
            if not outputPath: # isEmpty
                return


        self.viewMainData.doFreeSliceView(process, outputPath)
        

    def shiftFreeSlicePlane(self):
        #if not hasattr(self.viewMainData, 'data_ecm'): #[inamura 170227]
        if self.viewMainData.data_ecm==None:
            msgbox = QtGui.QMessageBox.warning(self, 'Error', 'Please load a data file first.')
            return

        if self.viewMainData.isThreadRunning():
            msgbox = QtGui.QMessageBox.warning(self, 'Error', 'An other thread is running.')
            return

        if not hasattr(self, 'freeSliceItem'):
            msgbox = QtGui.QMessageBox.warning(self, 'Error', 'The plane does not exist.')
            return
         
        self.freeSlicePlaneTodata()
        r = 1.0
        if self.sender() == self.freeSliceGoButton:
            r = 1.0
        elif self.sender() == self.freeSliceBackButton:
            r = -1.0

        xdiff, ok = self.freeSliceXdiff.text().toDouble()
        xdiff *= r
        ydiff, ok = self.freeSliceYdiff.text().toDouble()
        ydiff *= r
        zdiff, ok = self.freeSliceZdiff.text().toDouble()
        zdiff *= r

        roundFlag = False
        roundPos  = 5
        self.viewMainData.freeSlice.shiftPlane(xdiff, ydiff, zdiff, roundFlag, roundPos)

        #len = r * 1.0 # test
        #roundFlag = True
        #roundPos  = 5
        #self.viewMainData.freeSlice.shiftPlaneAlongNormalVector(len, roundFlag, roundPos)
        
        self.dataToFreeSliceWidget()
        process = ViewMainData.ViewMainData.PROCESS_MAIN
        outputPath = ""
        self.viewMainData.doFreeSliceView(process, outputPath)


# stop free slicing
#----------------------------
    def cancelFreeSliceView(self):
        if not self.viewMainData.isThreadRunning():
            msgbox = QtGui.QMessageBox.warning(self, 'Error', 'No thread is running.')
            return 
        
        replay = QtGui.QMessageBox.question(self, "Message", "Are you sure to stop the running thread?", \
                 QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
        if replay == QtGui.QMessageBox.No:
            return3

        self.viewMainData.stop_event.set()
        self.viewMainData.sliceThread.join()
   
        msgbox = QtGui.QMessageBox.information(self, '', 'The thread was stopped.')

# メインビュー画面の保存
#---------------------------------
    def saveAsImage(self, path):
        p = self.glView.readQImage()
        p.save(path)

# カラーテーブルやスケールの変更
#--------------------------------
    def updateColorBar(self):
        # カラーバー色の設定
        self.viewSubData.colorBarPreset = str(self.colorMapCombo2.currentText())
        #[inamura 180516]-->
        #self.colorBar.loadPreset(self.viewSubData.colorBarPreset)
        if self.viewSubData.colorBarPreset in self.colorMap_utsusemi.keys():
            if self.preColorBarName==None or not self.preColorBarName in self.colorMap_utsusemi.keys():
                cmap,lut = self.colorMap_utsusemi[self.viewSubData.colorBarPreset]
                self.colorBar.item.setColorMap( cmap )
                self.preColorBarName = self.viewSubData.colorBarPreset
        else:
            self.colorBar.loadPreset(self.viewSubData.colorBarPreset)
            self.preColorBarName = self.viewSubData.colorBarPreset
        #<--[inamura 180516]
        # ▽を非表示
        for i in range(len(self.colorBar.item.listTicks())):
            wt = self.colorBar.item.getTick(i)
            wt.setVisible(False)

        # update labels
        # remove all widgets on colorLabelLayout
        itemcount = self.colorLabelLayout.count()
        for i in reversed(range(itemcount)):
            self.colorLabelLayout.itemAt(i).widget().setParent(None)
  #          self.colorLabelLayout.itemAt(i).widget().close() # doesn't  work?

        logscale = False
        if self.viewSubData.scale == ViewSubData.ViewSubData.LOG_SCALE:
            logscale = True
        self.colorLevels = (self.viewSubData.scalarRangeMin, self.viewSubData.scalarRangeMax) #カラーバーの表示範囲の設定
        numLabel = 9
        step = (self.viewSubData.scalarRangeMax - self.viewSubData.scalarRangeMin)/(numLabel - 1)
        if logscale:
            if self.viewSubData.scalarRangeMin == 0:
                self.viewSubData.scalarRangeMin = self.viewSubData.scalarRangeMax/10000.0
            max = math.log10(self.viewSubData.scalarRangeMax)
            min = math.log10(self.viewSubData.scalarRangeMin)
            step = (max - min)/(numLabel - 1)

        for i in range(numLabel):
            if logscale:
                power = max - step*i
                #label = QtGui.QLabel("1.0E"+str(power))
                value = 10.0 ** power
                labstr   = '%.2e' % value
                label = QtGui.QLabel(labstr)
                #self.colorLabelLayout.setSpacing(0)
                self.colorLabelLayout.addWidget(label)    
            else:
                value = self.viewSubData.scalarRangeMax - (step * i)
                label = QtGui.QLabel(" "+str(value))
                #self.colorLabelLayout.setSpacing(0)
                self.colorLabelLayout.addWidget(label)    

        #gl = pg.GradientLegend((10, 200), (10, 30))
        #gl.setLabels(dict((('- %3.1f' % x), x) for x in np.arange(0, 1+0.2, 0.2)))
       
        self.updateSliceItem()

# Axis/Grid
#--------------------------------
    def updateAxisGrid(self):
        self.viewSubData.updateAxis()
        self.viewSubData.updateAxisLabel()
        self.viewSubData.updateAxisTick()
        self.viewSubData.updateGrid()
        self.glView.update()

    def updateGrid(self):
        self.viewSubData.updateGrid()
        self.glView.update()

# 軸ラベル
#--------------------------------
    def updateLabel(self):
        if self.axisFontCombo.currentIndex() == 0:
            self.viewSubData.updateAxisLabelFont(GLUT_BITMAP_8_BY_13)
        elif self.axisFontCombo.currentIndex() == 1:
            self.viewSubData.updateAxisLabelFont(GLUT_BITMAP_9_BY_15)
        elif self.axisFontCombo.currentIndex() == 2:
            self.viewSubData.updateAxisLabelFont(GLUT_BITMAP_HELVETICA_10)
        elif self.axisFontCombo.currentIndex() == 3:
            self.viewSubData.updateAxisLabelFont(GLUT_BITMAP_HELVETICA_12)
        elif self.axisFontCombo.currentIndex() == 4:
            self.viewSubData.updateAxisLabelFont(GLUT_BITMAP_HELVETICA_18)
        elif self.axisFontCombo.currentIndex() == 5:
            self.viewSubData.updateAxisLabelFont(GLUT_BITMAP_TIMES_ROMAN_10)
        elif self.axisFontCombo.currentIndex() == 6:
            self.viewSubData.updateAxisLabelFont(GLUT_BITMAP_TIMES_ROMAN_24)

        self.glView.update()

# Reset Scroll Bar
#-------------------------------
    def updateScrollbar(self):
        xvalue = 0
        if hasattr(self, "basicSliceItemYZ"):
            # rangex = self.viewMainData.rangex
            # lenx = rangex[1] - rangex[0]
            # x = self.viewMainData.data_yz_pos
            # r = 0.0
            # if lenx != 0:
            #     r = (x-rangex[0])/lenx
            # if r < 0:
            #     r = 0.0
            # if 1 < r:
            #     r = 1.0
            # xvalue = self.viewSubData.xscrollMax * r
            x = self.viewMainData.data_yz_pos
            rangex = self.viewMainData.rangex
            dx = x - rangex[0]
            xvalue = dx/self.viewMainData.ax1Slice.thickness
            
            #print "r = %f, pos = %f, val = %f" % (r, x, xvalue)  
            #print "floor = %f, ceil = %f, round = %f" % ( math.floor(xvalue), math.ceil(xvalue), round(xvalue, 0))
        self.xscroll.setValue(round(xvalue,0))
               
        val = self.xscroll.value()
        #print "val = %f" % val

        yvalue = 0
        if hasattr(self, "basicSliceItemZX"):
            # rangey = self.viewMainData.rangey
            # leny = rangey[1] - rangey[0]
            # y = self.viewMainData.data_zx_pos
            # r = 0.0
            # if leny != 0:
            #     r = (y-rangey[0])/leny
            # if r < 0:
            #     r = 0.0
            # if 1 < r:
            #     r = 1.0
            # yvalue = self.viewSubData.yscrollMax * r
            y = self.viewMainData.data_zx_pos
            rangey = self.viewMainData.rangey
            dy = y - rangey[0]
            yvalue = dy/self.viewMainData.ax2Slice.thickness
              
        self.yscroll.setValue(round(yvalue, 0))

        zvalue = 0
        if hasattr(self, "basicSliceItemXY"):
            # rangez = self.viewMainData.rangez
            # lenz = rangez[1] - rangez[0]
            # z = self.viewMainData.data_xy_pos
            # r = 0.0
            # if lenz != 0:
            #     r = (z-rangez[0])/lenz
            # if r < 0:
            #     r = 0.0
            # if 1 < r:
            #     r = 1.0
            # zvalue = self.viewSubData.zscrollMax * r
            z = self.viewMainData.data_xy_pos
            rangez = self.viewMainData.rangez
            dz = z - rangez[0]
            zvalue = dz/self.viewMainData.ax3Slice.thickness

        self.zscroll.setValue(round(zvalue, 0))

# Update scrollbar range
#-----------------------------
    def updateScrollbarRange(self):
        rangex = self.viewMainData.rangex
        rangey = self.viewMainData.rangey
        rangez = self.viewMainData.rangez
        lenX = rangex[1] - rangex[0]
        lenY = rangey[1] - rangey[0]
        lenZ = rangez[1] - rangez[0]

        self.viewSubData.xscrollMax = math.ceil(lenX/self.viewMainData.ax1Slice.thickness)
        self.viewSubData.yscrollMax = math.ceil(lenY/self.viewMainData.ax2Slice.thickness)
        self.viewSubData.zscrollMax = math.ceil(lenZ/self.viewMainData.ax3Slice.thickness)

        self.viewSubData.xscrollStep = 1
        self.viewSubData.yscrollStep = 1
        self.viewSubData.zscrollStep = 1

        self.xscroll.setMaximum(self.viewSubData.xscrollMax)
        self.xscroll.setPageStep(self.viewSubData.xscrollStep)
        self.yscroll.setMaximum(self.viewSubData.yscrollMax)
        self.yscroll.setPageStep(self.viewSubData.yscrollStep)
        self.zscroll.setMaximum(self.viewSubData.zscrollMax)
        self.zscroll.setPageStep(self.viewSubData.zscrollStep)

# Reset Scroll Bar
#-----------------------------
    def updateSliceView(self, args):
        planeID = int(args[0])
        if planeID == ViewMainData.ViewMainData.SLICE_XY:
            self.viewDirectionToMinusZ()
        elif planeID == ViewMainData.ViewMainData.SLICE_YZ:
            self.viewDirectionToMinusX()
        elif planeID == ViewMainData.ViewMainData.SLICE_ZX:
            self.viewDirectionToPlusY()

# ステータスバーの文字列を更新
#--------------------------------------------
    def updateStatusBar(self, message):
        self.status_bar.showMessage(message)


#********************************************
# 視点変更
#********************************************
    def changeViewPoint(self):
        fx, ok = self.focalPointX.text().toDouble()
        fy, ok = self.focalPointY.text().toDouble()
        fz, ok = self.focalPointZ.text().toDouble()
        vx, ok = self.viewPointX.text().toDouble()
        vy, ok = self.viewPointY.text().toDouble()
        vz, ok = self.viewPointZ.text().toDouble()
        dist, ok = self.distEdit.text().toDouble()
        az, ok = self.azEdit.text().toDouble()
        ele, ok = self.eleEdit.text().toDouble()
        
        fx = fx * self.viewMainData.basicSliceAx1Scale
        fy = fy * self.viewMainData.basicSliceAx2Scale
        fz = fz * self.viewMainData.basicSliceAx3Scale
        vx = vx * self.viewMainData.basicSliceAx1Scale
        vy = vy * self.viewMainData.basicSliceAx2Scale
        vz = vz * self.viewMainData.basicSliceAx3Scale

        if self.viewMethod1Radio.isChecked():
            vecX = vx-fx
            vecY = vy-fy
            vecZ = vz-fz
            dist = math.sqrt(vecX*vecX + vecY*vecY + vecZ*vecZ)
            tmp  = math.sqrt(vecX*vecX + vecY*vecY)
            ele  = math.atan2(vecZ, tmp) * 180.0 / math.pi
            az   = math.atan2(vecY, vecX) * 180.0 / math.pi
            
        #self.glView.opts['center']    = QtGui.QVector3D(x, y, z)
        self.glView.opts['center']    = pg.Vector(fx, fy, fz)
        self.glView.opts['distance']  = dist
        self.glView.opts['azimuth']   = az
        self.glView.opts['elevation'] = ele
        self.glView.update()
        self.dataToViewWidget()

# Zoom best fit
#------------------------------------
    def zoomBestFit(self):
        x = 0.0
        y = 0.0
        z = 0.0
#        lenXaxis = self.viewSubData.lenXaxis
#        lenYaxis = self.viewSubData.lenYaxis
#        lenZaxis = self.viewSubData.lenZaxis
        lenXaxis = self.viewSubData.lenXaxis * self.viewMainData.basicSliceAx1Scale
        lenYaxis = self.viewSubData.lenYaxis * self.viewMainData.basicSliceAx2Scale
        lenZaxis = self.viewSubData.lenZaxis * self.viewMainData.basicSliceAx3Scale
        dist = math.sqrt(pow(lenXaxis, 2) + pow(lenYaxis, 2) + pow(lenZaxis, 2)) * math.sqrt(2.0)
        az   = 45.0
        ele  = 30.0
        self.glView.opts['center']    = pg.Vector(x, y, z)
        self.glView.opts['distance']  = dist
        self.glView.opts['azimuth']   = az
        self.glView.opts['elevation'] = ele
        self.glView.update()
        
# Set view direction to +X
#------------------------------------
    def viewDirectionToPlusX(self):
        x = 0.0
        y = 0.0
        z = 0.0
        dist = 30.0
        az   = 180.0
        ele  = 0.0
        if hasattr(self, "basicSliceItemYZ") and self.viewMainData.ax1Slice.visible:
            rangey = self.viewMainData.rangey
            rangez = self.viewMainData.rangez
            leny = (rangey[1] - rangey[0]) * self.viewMainData.basicSliceAx2Scale
            lenz = (rangez[1] - rangez[0]) * self.viewMainData.basicSliceAx3Scale
            max = leny
            if max < lenz:
                max = lenz

            x = self.viewMainData.data_yz_pos
            y = (rangey[0] + rangey[1])/2.0
            z = (rangez[0] + rangez[1])/2.0
            dist = max
            x = x * self.viewMainData.basicSliceAx1Scale
            y = y * self.viewMainData.basicSliceAx2Scale
            z = z * self.viewMainData.basicSliceAx3Scale

        self.glView.opts['center']    = pg.Vector(x, y, z)
        self.glView.opts['distance']  = dist
        self.glView.opts['azimuth']   = az
        self.glView.opts['elevation'] = ele
        self.glView.update()

# Set view direction to -X
#------------------------------------
    def viewDirectionToMinusX(self):
        x = 0.0
        y = 0.0
        z = 0.0
        dist = 30.0
        az   = 0.0
        ele  = 0.0
        if hasattr(self, "basicSliceItemYZ") and self.viewMainData.ax1Slice.visible:
            rangey = self.viewMainData.rangey
            rangez = self.viewMainData.rangez
            leny = (rangey[1] - rangey[0]) * self.viewMainData.basicSliceAx2Scale
            lenz = (rangez[1] - rangez[0]) * self.viewMainData.basicSliceAx3Scale

            max = leny
            if max < lenz:
                max = lenz

            x = self.viewMainData.data_yz_pos
            y = (rangey[0] + rangey[1])/2.0
            z = (rangez[0] + rangez[1])/2.0
            dist = max

            x = x * self.viewMainData.basicSliceAx1Scale
            y = y * self.viewMainData.basicSliceAx2Scale
            z = z * self.viewMainData.basicSliceAx3Scale

        self.glView.opts['center']    = pg.Vector(x, y, z)
        self.glView.opts['distance']  = dist
        self.glView.opts['azimuth']   = az
        self.glView.opts['elevation'] = ele
        self.glView.update()

# Set view direction to +Y
#------------------------------------
    def viewDirectionToPlusY(self):
        x = 0.0
        y = 0.0
        z = 0.0
        dist = 30.0
        az   = -90.0
        ele  = 0.0
        if hasattr(self, "basicSliceItemZX") and self.viewMainData.ax2Slice.visible:
            rangex = self.viewMainData.rangex
            rangez = self.viewMainData.rangez
            lenx = (rangex[1] - rangex[0]) * self.viewMainData.basicSliceAx1Scale
            lenz = (rangez[1] - rangez[0]) * self.viewMainData.basicSliceAx3Scale
            max = lenx
            if max < lenz:
                max = lenz
            x = (rangex[0] + rangex[1])/2.0
            y = self.viewMainData.data_zx_pos
            z = (rangez[0] + rangez[1])/2.0
            dist = max
            x = x * self.viewMainData.basicSliceAx1Scale
            y = y * self.viewMainData.basicSliceAx2Scale
            z = z * self.viewMainData.basicSliceAx3Scale

        self.glView.opts['center']    = pg.Vector(x, y, z)
        self.glView.opts['distance']  = dist
        self.glView.opts['azimuth']   = az
        self.glView.opts['elevation'] = ele
        self.glView.update()

# Set view direction to -Y
#------------------------------------
    def viewDirectionToMinusY(self):
        x = 0.0
        y = 0.0
        z = 0.0
        dist = 100.0
        az   = 90.0
        ele  = 0.0
        if hasattr(self, "basicSliceItemZX") and self.viewMainData.ax2Slice.visible:
            rangex = self.viewMainData.rangex
            rangez = self.viewMainData.rangez
            lenx = (rangex[1] - rangex[0]) * self.viewMainData.basicSliceAx1Scale
            lenz = (rangez[1] - rangez[0]) * self.viewMainData.basicSliceAx3Scale
            max = lenx
            if max < lenz:
                max = lenz
            x = (rangex[0] + rangex[1])/2.0
            y = self.viewMainData.data_zx_pos
            z = (rangez[0] + rangez[1])/2.0
            dist = max
            x = x * self.viewMainData.basicSliceAx1Scale
            y = y * self.viewMainData.basicSliceAx2Scale
            z = z * self.viewMainData.basicSliceAx3Scale

        self.glView.opts['center']    = pg.Vector(x, y, z)
        self.glView.opts['distance']  = dist
        self.glView.opts['azimuth']   = az
        self.glView.opts['elevation'] = ele
        self.glView.update()

# Set view direction to +Z
#------------------------------------
    def viewDirectionToPlusZ(self):
        x = 0.0
        y = 0.0
        z = 0.0
        dist = 30.0
        az   = 90.0
        ele  = -90.0
        if hasattr(self, "basicSliceItemXY") and self.viewMainData.ax3Slice.visible:
            rangex = self.viewMainData.rangex
            rangey = self.viewMainData.rangey
            lenx = (rangex[1] - rangex[0]) * self.viewMainData.basicSliceAx1Scale
            leny = (rangey[1] - rangey[0]) * self.viewMainData.basicSliceAx2Scale
            max = lenx
            if max < leny:
                max = leny

            x = (rangex[0] + rangex[1])/2.0
            y = (rangey[0] + rangey[1])/2.0
            z = self.viewMainData.data_xy_pos
            dist = max
            x = x * self.viewMainData.basicSliceAx1Scale
            y = y * self.viewMainData.basicSliceAx2Scale
            z = z * self.viewMainData.basicSliceAx3Scale


        self.glView.opts['center']    = pg.Vector(x, y, z)
        self.glView.opts['distance']  = dist
        self.glView.opts['azimuth']   = az
        self.glView.opts['elevation'] = ele
        self.glView.update()

# Set view direction to -Z
#------------------------------------
    def viewDirectionToMinusZ(self):
        x = 0.0
        y = 0.0
        z = 0.0
        dist = 30.0
        az   = -90.0
        ele  =  90.0
        if hasattr(self, "basicSliceItemXY") and self.viewMainData.ax3Slice.visible:
            rangex = self.viewMainData.rangex
            rangey = self.viewMainData.rangey
            x = (rangex[0] + rangex[1])/2.0
            y = (rangey[0] + rangey[1])/2.0
            z = self.viewMainData.data_xy_pos
            lenx = (rangex[1] - rangex[0]) * self.viewMainData.basicSliceAx1Scale
            leny = (rangey[1] - rangey[0]) * self.viewMainData.basicSliceAx2Scale
            max = lenx
            if max < leny:
                max = leny

            dist = max
            x = x * self.viewMainData.basicSliceAx1Scale
            y = y * self.viewMainData.basicSliceAx2Scale
            z = z * self.viewMainData.basicSliceAx3Scale

        self.glView.opts['center']    = pg.Vector(x, y, z)
        self.glView.opts['distance']  = dist
        self.glView.opts['azimuth']   = az
        self.glView.opts['elevation'] = ele
        self.glView.update()

    def onChangeGLOption(self):
        if self.translucent_action.isChecked():
            self.viewSubData.transFlag = True
        else:
            self.viewSubData.transFlag = False

        
        updateFlag = False 
        if self.viewSubData.transFlag:
            if hasattr(self, "basicSliceItemXY"):
                updateFlag = True
                self.basicSliceItemXY.setGLOptions('additive')
                #self.basicSliceItemXY.setGLOptions('translucent') #[inamura 180516]
            if hasattr(self, "basicSliceItemYZ"):
                updateFlag = True
                self.basicSliceItemYZ.setGLOptions('additive')
                #self.basicSliceItemYZ.setGLOptions('translucent') #[inamura 180516]
            if hasattr(self, "basicSliceItemZX"):
                updateFlag = True
                self.basicSliceItemZX.setGLOptions('additive')
                #self.basicSliceItemZX.setGLOptions('translucent') #[inamura 180516]
            if hasattr(self, "freeSliceItem"):
                updateFlag = True
                self.freeSliceItem.setGLOptions('additive')
        else:
            if hasattr(self, "basicSliceItemXY"):
                updateFlag = True
                self.basicSliceItemXY.setGLOptions('opaque')
            if hasattr(self, "basicSliceItemYZ"):
                updateFlag = True
                self.basicSliceItemYZ.setGLOptions('opaque')
            if hasattr(self, "basicSliceItemZX"):
                updateFlag = True
                self.basicSliceItemZX.setGLOptions('opaque')
            if hasattr(self, "freeSliceItem"):
                updateFlag = True
                self.freeSliceItem.setGLOptions('opaque')

        if updateFlag:
            self.glView.update()

#================================================================================
#
# 
#
#================================================================================

# カラーテーブル変更時に描画中のスライス面があれば再描画
#--------------------------------------------------------
    def updateSliceItem(self):
        if hasattr(self, "basicSliceItemXY"):
            planeID = ViewMainData.ViewMainData.SLICE_XY
            self.createBasicSliceItem((planeID, ))
        if hasattr(self, "basicSliceItemYZ"):
            planeID = ViewMainData.ViewMainData.SLICE_YZ
            self.createBasicSliceItem((planeID, ))
        if hasattr(self, "basicSliceItemZX"):
            planeID = ViewMainData.ViewMainData.SLICE_ZX
            self.createBasicSliceItem((planeID, ))

        if hasattr(self, "freeSliceItem"):
            self.createFreeSliceItem((0,))

        self.dataToGLViewItemVisibility()

# test: 3面表示用アイテム
#-------------------------------------------------
    def addTestItem(self):
        x = np.linspace(0, 10, 21)[:, np.newaxis]
        y = np.linspace(0, 10, 21)[np.newaxis, :]
        data = np.array([np.abs(x+y-i) for i in range(21)])

        self.levels = (0.0, 20.0)
        section = 0
        nPts = 200
        gradient = pg.GradientEditorItem()
        gradient.loadPreset("thermal")
        self.lut = gradient.getLookupTable(nPts, alpha=None)
        tex1 = pg.makeARGB(data[section], lut=self.lut, levels=self.levels, useRGBA=True)[0]
        tex2 = pg.makeARGB(data[:,section], lut=self.lut, levels=self.levels, useRGBA=True)[0]
        tex3 = pg.makeARGB(data[:,:,section], lut=self.lut, levels=self.levels, useRGBA=True)[0]
       
        v1 = gl.GLImageItem(tex1)
        v1.rotate(90, 0, 0, 1)
        v1.rotate(90, 0, 1, 0)
        v1.translate(section, 0, 0)
        self.glView.addItem(v1) 

        v2 = gl.GLImageItem(tex2)
        v2.rotate(90, 1, 0, 0)
        v2.translate(0, section, 0)
        self.glView.addItem(v2) 
        
        v3 = gl.GLImageItem(tex3)
        v3.translate(0, 0, section)
        self.glView.addItem(v3) 
 
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
# class SliceViewerApplication
#
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class SliceViewerApplication(QtGui.QApplication):

    #############################################
    def OnStart(self, portno, closeFlag, func):
        """
        タイマー監視のスタート
        @param  portno     ソケットのポート番号
        @param  closeFlag  親プロセス終了時に自死するかどうかのフラグ
        @param  func       コマンド解析・実行用のコールバック関数
        @retval 無し
        """
        self.func = func
        self.closeFlag = closeFlag

        # ソケットサーバー準備
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(('127.0.0.1', portno))
        # タイムアウトを 15 秒に設定
        sock.settimeout(15.0)
        # 受信準備
        sock.listen(1)
        # クライアントと接続
        try:
            (conn, sa) = sock.accept()
        except socket.error, e:
            print 'Error: %s' % e
            return
        # 受信待ち時停止指定
        conn.setblocking(True)

        # スレッド間通信用のキューを準備
        self.datQueue = Queue.Queue()
        self.ansQueue = Queue.Queue()

        # サブスレッドの終了フラグを準備
        self.stopFlag = False

        # サブスレッドスタート
        th = threading.Thread(target=self.SocketServer, args=(conn,))
        th.setDaemon(True)
        th.start()

        ## 0.3　秒毎のタイマー
        #self.timer = wx.Timer(self)
        #self.timer.Start(300)
        #self.Bind(wx.EVT_TIMER, self.TimerHandler)

        self.timer = QtCore.QTimer()
        self.timer.start(300)
        self.timer.timeout.connect(self.TimerHandler)

    #############################################
    def TimerHandler(self):
        """
        タイマー監視ルーチン
        CUIからのコマンドを受信したらコマンド解析クラスを
        通じてデータを送信
        @param  evt イベント情報
        @retval 無し
        """

        # コマンドがあれば
        if self.datQueue.qsize() > 0:
            # キューからコマンドを読み出す
            strCmd = self.datQueue.get()
            # コマンド実行前の時間を保存
            t1 = time.time()
            # GUI アプリから渡されたコマンド解析処理コールバック関数を実行
            ret = apply(self.func, (strCmd,))

            # コマンド終了後の時間を取得
            t2 = time.time()
            # コマンドの実行に 10秒以上かかった場合は
            # 通信スレッドが既に NACK を送信しているため、ここでは送信しない
            if t1+10.0 > t2:
                # 応答が特に無ければ正常応答を返信
                if ret == None:
                    ret = "ACK\n"
                # 返信要求をだす
                self.ansQueue.put(ret)

    #####################################################
    def OnGUIClose(self):
        """
        トップレベルウィンドウクローズイベント対応処理
        @param  無し
        @retval 無し
        """
        # 
        if self.viewMainData.isThreadRunning():
            replay = QtGui.QMessageBox.question(self, "Message", "An thread is runnning. Are you sure to quit now?", \
                 QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
            if replay == QtGui.QMessageBox.No:
                 return
            self.viewMainData.stop_event.set()
            self.viewMainData.sliceThread.join()

        # タイマー停止
        self.timer.Stop()
        # サブスレッドの停止フラグを立てる
        self.stopFlag = True
        
    #############################################
    def SocketServer(self, sock) :
        """
        ソケットからコマンドを取得し、レスポンスを返す
        (サブスレッドにて実行)
        @param  sock ソケットオブジェクト
        @retval 無し
        """
        # 永久ループ(トップレベルのウィンドウクローズ時、またはクライアント終了時に終了)
        while True:
            # アプリケーションが終了したか
            if self.stopFlag:
                # 接続終了
                break
            # コマンドを読み込む
            cmd = self.GetCommand(sock)
            # 接続維持コマンドではないならば
            if not cmd == "keepalive":
                # コマンドをメインスレッドへ送信
                self.datQueue.put(cmd)
                # メインスレッドからの返信待ち(タイムアウト10秒)
                try:
                    # キューから応答を読み出す
                    answer = self.ansQueue.get(timeout = 10.0)
                except:
                    # タイムアウトでコマンド実行エラーを返信
                    answer = "NACK\n"
                try:
                    # CUIへ応答を返信
                    sock.send(answer)
                except:
                    # クライアントが接続を終了している
                    break

        # 接続終了
        sock.close()
        # wxPython のメインループを終了させる(Linux では必要)
        #wx.Exit()


    #############################################
    def GetCommand(self, sock) :
        """
        1個のコマンドを取得
        @param  sock ソケットオブジェクト
        @retval 無し
        """
        # コマンドを受信するまで待っている
        while True:
            cmd = ""
            # コマンドが分割された場合のプロテクト
            # 1個のコマンドが10以上に分割されていればコマンドを破棄
            for i in range(10):
                try:
                    # コマンド読み込み
                    data = sock.recv(1024)
                    # クライアントが終了したか
                    # (Linux Python 2.4　対応: 例外が発生せずに、ブロッキングされなくなるようだ)
                    if data == "":
                        # 親プロセス終了時の終了が指定されているか
                        if self.closeFlag:
                            self.stopFlag = True
                            # アプリケーション終了要求を出す
                            return "close"
                    # 改行コードがあるか
                    if '\n' in data:
                        # 改行コードの前までをコマンドとして取り出す
                        cmd = cmd + data[:data.find('\n')]
                        # コマンドを返す
                        return cmd

                    # コマンドが未完であれば
                    elif len(data) > 0:
                        # 連結
                        cmd = cmd + data
                        time.sleep(0.1)
                # クライアント終了による例外発生
                except:
                    # 親プロセス終了時の終了が指定されているか
                    #if self.closeFlag:
                    #    # クライアント終了による、アプリケーション終了
                    #    self.stopFlag = True
                    pass
#######################################
#  IFEvtProp
#######################################
class IFEvtProp(object):
    """
    イベントとプロパティ授受用のインターフェイスクラス
    """

    dicInstance = {}

    #########################################
    def __new__(cls, idno=0):

        """
        idno 毎に異なるインスタンスを返すコンストラクタ
        (同一グループ間では共通のインスタンスを使用)
        @param  cls 　クラス
        @param  idno  グループID
          　　　プロッタ番号をIDとして使用
        @retval クラスのインスタンス
        """

        # 指定されたID のクラスインスタンスが生成済みなら
        if cls.dicInstance.has_key(idno):
            # 生成済みのインスタンスを返す
            instance = cls.dicInstance[idno]
        else:
            #クラスインスタンスが未生成なら新規に構築
            instance = object.__new__(cls)

        return instance

    #########################################
    def __init__(self, idno=0):

        """
        インターフェイスクラスのコンストラクタ
        @param  idno  グループID
        @retval クラスのインスタンス
        """
        # クラスインスタンスが登録済みなら
        if self.dicInstance.has_key(idno):
            # 何もしない
            return

        # クラスインスタンスを登録
        self.dicInstance[idno] = self

        # 登録リストを初期化
        self.InitIF()

    #########################################
    def InitIF(self):
        """
        リスナーリストとプロパティディクショナリの初期化
        @param  無し
        @retval 無し
        """
        # リスナーリストの初期化
        self.listner = []
        # プロパティディクショナリの初期化
        self.property = {}

    #########################################
    def AddListner(self, evtType, func):
        """
        イベントに対するリスナー登録追加
        @param  evtType  イベントタイプ(文字列)
        @param  func     イベント発生時に実行する関数
        @retval 無し
        """
        # イベント発生時に実行する関数を登録
        self.listner.append((evtType, func))

    #########################################
    def AddProperty(self, propKey, func):
        """
        公開するプロパティを登録
        @param  propKey  属性名称(文字列)
        @param  func     プロパティが要求されたときに実行する関数(ラムダ式)
        @retval 無し
        """
        # プロパティを返すラムダ式を登録
        self.property[propKey] = func

    #########################################
    def NotifyEvent(self, wid, evtType, value=None):
        """
        イベントに登録されている関数を実行
        (同一イベントに複数登録されている場合は、順番にすべて実行)
        @param  wid      イベント発生元のインスタンス
        @param  evtType  発生したイベントのタイプ(文字列)
        @param  value    イベントの値(省略可)
        @retval 無し
        """

        # リスナーリストから、イベントに登録されているものを探す
        for listner in self.listner:
            evt, func = listner
            # イベントタイプが一致したなら
            if evt == evtType:
                # イベントに登録されている関数を全て実行
                apply(func, (wid,evtType,value))

    #########################################
    def GetProperty(self, propKey):
        """
        プロパティ取得
        @param  propKey  属性名称(文字列)
        @retval プロパティ
        """
        retval = None
        # プロパティのkey から lambda 式を取得
        try:
            try:
                func = self.property[propKey]
            except:
                raise PlotException('Common','C001',("Key error:"+propKey,"IFEvtProp:GetProperty"))
            else:
                # プロパティを取得(lambda 式実行)
                try:
                    retval = func()
                except:
                    raise PlotException('Common','C001',("Lambda execution","IFEvtProp:GetProperty"))
        except PlotException, ex:
            PlotMessage(None,ex)

        return retval

#######################################
#  MakeTempFile
#######################################
class TempFile(object):
    """
    テンポラリファイルクラス
    """
    ###################################################
    def GetTempName(self):
        """
        テンポラリファイルの名称を取得
        (モジュール tempfile を使用してファイル名を取得すると、
        消せなくなるため、自分でファイル名を作成)
        @param  無し
        @retval テンポラリファイル名称(フルパス)
                 名称取得に失敗した場合は、None を返す
        """
        # 現在の絶対時間(0.01秒単位)と、プロッタ番号よりテンポラリファイル名を作成
        tsec = int(time.time()*100.0)
        tmpf = "tmp%d" % tsec
        # テンポラリファイルの絶対パスを作成(指定されたテンポラリディレクトリの下)
        tmppath = os.path.join(tempfile.gettempdir(), tmpf)

        # テンポラリファイルの存在チェック
        for i in range(100):
            # 万一同じファイル名があったら、ファイル名を変更
            if os.path.exists(tmppath):
                tmppath = "%s%d" % (tmppath, i)
            else:
                # 無ければOK
                break
            if i == 99:
                return None

        return tmppath

    ###################################################
    def MakeTempFile(self, object, temppath):
        """
        Python オブジェクトをシリアライズして
        テンポラリファイルに書き込む
        @param  object    シリアライズするオブジェクト
        @param  temppath  シリアライズしたオブジェクトを書きこむファイル
        @retval  0: 成功、1: テンポラリファイルオープン失敗、2: シリアライズ失敗
        """
        try:
            # テンポラリファイルを開く
            fw = file(temppath,"wb")
        except:
            return 1
        try:
            # オブジェクトをバイナリモードでシリアライズ
            pickle.dump( object, fw, True )
        except:
            # テンポラリファイルをクローズ
            fw.close()
            return 2
        # テンポラリファイルをクローズ
        fw.close()
        # 正常終了
        return 0

    ###################################################
    def ReadTempFile(self, temppath):
        """
        テンポラリファイルを読み込み、デシリアライズかる。
        @param  temppath  シリアライズしたオブジェクトを書きこんだファイル
        @retval  デシリアライズしたデータ、デシリアライズ失敗時は None
        """
        try:
            # テンポラリファイルを読み込む
            fr = file(temppath,"rb")
            # データを復元(デシリアライズ)
            data = pickle.load(fr)
        except:
            return None
        # テンポラリファイルをクローズ
        fr.close()
        # テンポラリファイルを削除
        os.remove(temppath)
        # デシリアライズしたオブジェクトを返す
        return data

class CuiIF(object):
    """
    CUI からのコマンドを解析し、プロッタに対し
    イベントを発行する
    """
    ###################################################
    def StartPlot(self, plotNum, func):
        """
        コンストラクタ
        @param  sysarg 起動時の引数
        @param  func   起動した画面のクローズイベント発生時に実行する関数
        @retval 無し
        """
        self.func = func
        # テンポラリファイルクラスのインスタンス取得
        self.tp = TempFile()

        # プロッタ画面の起動
        #self.plot = PlotFrame(None, None, plotNum)

        self.plot=SliceViewerMain()
        self.plot.show()


        # プロッタが公開しているインターフェイスクラスのインスタンスを取得
        self.ifi = IFEvtProp(plotNum)

        # プロッタフレームクローズイベントのリスナー登録
        self.ifi.AddListner('plotclose', self.OnNotifyClose)

        # コマンドとその実行関数登録
        self.functions = {
                      "setFocalPoint"      : self.cuiCommand,
                      "setViewPoint"      : self.cuiCommand,
                      "setDistance"        : self.cuiCommand,
                      "setAzimuth"         : self.cuiCommand,
                      "setElevation"       : self.cuiCommand,
                      "setScalarRange"     : self.cuiCommand,
                      "setAxisLength"      : self.cuiCommand,
                      "setGridSpace"       : self.cuiCommand,
                      "setOutputDirectory" : self.cuiCommand,
                      "doSliceAx1"         : self.cuiCommand,
                      "doSliceAx2"         : self.cuiCommand,
                      "doSliceAx3"         : self.cuiCommand,
                      "doFreeSlice"        : self.cuiCommand,
                      "setData"            : self.cuiCommand, #[inamura 170227]
                      "setAxesTitles"      : self.cuiCommand, #[inamura 170227]
                      "getattr"            : self.GetAttr}


    #####################################################
    def OnNotifyClose(self, wid, evt, value=None):
        """
        プロッタクローズイベント対応処理
        @param  wid 　 イベント発生元のインスタンス
        @param  evt 　イベントの種類
        @param  value  無し
        @retval 無し
        """
        # メッセージの解放
        MessageFile().CloseDoc()
        # 通信クラスの終了処理コールバック関数を実行
        apply(self.func, ())

    ###################################################
    def TakeCommand(self, strCmd):
        """
        コマンドを解析し、プロッタ画面にイベントを発行
        @param  strCmd コマンド文字列
        @retval コマンドに対する応答
        """
        # 文字列を空白区切りで分解
        args = strCmd.split()
        # コマンド実行関数を取得
        try:
            function = self.functions[args[0]]
        except:
            print "Command error!!", args
            return
        # 関数の実行
        return function(args)
    ###################################################
    def _Rebuild(self, args):
        """
        文字列引数を復元(文字列に空白が含まれている場合)
        @param  args コマンドと引数のタプル
        @retval 復元後の文字列
        """
        strArg = ""
        # 引数文字列を連結
        for i in range(len(args)-1):
            strArg = strArg + " " + args[i+1]
        # 頭の余分な空白を消す
        ret = strArg[1:]
        # 復元後の文字列を返す
        return ret

    ###################################################
    def cuiCommand(self, args):
        """
        @param  args コマンドと引数のタプル
        @retval 無し
        """
        
        # スケールラベル設定コマンド送信
        self.ifi.NotifyEvent(self, args[0], args[1:len(args)])


    ###################################################
    def GetAttr(self, args):
        """
        属性の取得
        @param  args コマンドと引数のタプル
        @retval 無し
        """
        # 属性取得
        attr = self.ifi.GetProperty(args[1])

        # 属性が文字列か
        if args[2]=="0":
            return attr+'\n'
        # 整数か
        elif args[2]=="1":
            return "%d\n" % attr
        # 実数か
        elif args[2]=="2":
            return "%.5f\n" % attr
        # ブーリアンか
        elif args[2]=="3":
            if attr== True:
                return "True\n"
            else:
                return "False\n"
        # オブジェクトか
        elif args[2]=="4":
            # 現在の絶対時間(0.01秒単位)と、プロッタ番号よりテンポラリファイル名を作成
            tsec = int(time.time()*100.0)
            tmpf = "attrs%d" % tsec
            # テンポラリファイルの絶対パスを作成(指定されたテンポラリディレクトリの下)
            tmppath = os.path.join(tempfile.gettempdir(), tmpf)
            try:
                # テンポラリファイルを開く
                fw = file(tmppath, "wb")
                # オブジェクトをバイナリモードでシリアライズ
                pickle.dump(attr, fw, True)
            except:
                print "\nError!! Cant create a temp file."
            else:
                # テンポラリファイルをクローズ
                fw.close()
                # テンポラリファイル名を返信
                return tmppath + '\n'


if __name__ == '__main__':
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        pass
        QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
        app = SliceViewerApplication([])

        # 汎用プロッタ(FastPlot)の CUI IF のインスタンス取得
        cuif = CuiIF()
        # 起動時引数より、通信ポート番号を取得
        portno = int(sys.argv[1])
        # 起動時引数より、プロッタ番号を取得
        pno = int(sys.argv[3])
        # プロッタ終了フラグが指定されているか
        if len(sys.argv) >= 5:
            if sys.argv[4] == "True":
                closeFlag = True
            else:
                closeFlag = False
        else:
            # 指定無しの場合は、True とする。
            closeFlag = True

        cuif.StartPlot(pno, app.OnGUIClose)
        # CUI との通信スタート(ポート番号と、コマンド処理関数を引数として渡す)
        app.OnStart(portno, closeFlag, cuif.TakeCommand)

        app.exec_()



