/* ---------------------------------------------------------
  タッチパネルの検査、評価プログラム
-----------------------------------------------------------*/

#include <nn.h>
#include <nn/gx.h>
#include <nn/drivers/cal/CTR/cal_Api.h>
#include "../seq/TestSequencer.h"
#include "../seq/TestListManager.h"
#include "../seq/TestResult.h"
#include "../seq/TestIdDefine.h"
#include "sys.h"
#include "TestTouchPanel.h"
#include "../Application.h"
#include "../wireless/CommandUtil.h"
#include "../seq/TesterLog/ProductionLog.h"
#include "../seq/Reception_board_interface.h"

#ifdef EVA_COMPOSITE
extern       char VERSION_STRING[];
#else
static const char VERSION_STRING[]= UJI_APPVER;
#endif
static const char VERSION_DATE[]  =	__DATE__ " " __TIME__ ;

using namespace uji::sys;
using namespace uji::seq;

namespace uji{
namespace eva{


namespace{

    CoordinateType CheckPointList[] =
    {
        { 32, 24 }, { 288, 216 }, { 288, 24 }
    };

    CoordinateType PosLU = CheckPointList[0];
    CoordinateType PosRD = CheckPointList[1];
    CoordinateType PosRU = CheckPointList[2];

    const int MAX_LOG_SIZE = 80;
    
    char s_LogMessage[ MAX_LOG_SIZE ] = "";
    
    LineCoordinate TpModuleList[] =
    {
#if 1
        { { 32,  24  }, { 160, 24  } },
        { { 160, 24  }, { 288, 24  } },
        { { 96,  72  }, { 160, 120 } },
        { { 160, 120 }, { 224, 168 } },
        { { 288, 216 }, { 160, 216 } },
        { { 160, 216 }, { 32,  216 } }
#else
        { { 32,  24  }, { 288, 24  } },
        { { 96,  72  }, { 224, 168 } },
        { { 288, 216 }, { 32,  216 } }
#endif
    };

}

namespace TouchPanel
{

bool TestTouchPanel( uji::seq::TestResult &result )
{
    
    memset( s_LogMessage, 0x00, sizeof( s_LogMessage ));
    
    uji::seq::Config  *c = new uji::seq::Config;
    if( c->Get().TestMode == uji::seq::pl::LINE ) // ライン設定の時のみキャリブレーションを行う
    {
        TouchPanelCal* tpc = new TouchPanelCal;
        tpc->TPCalCommon( result, false );
        delete tpc;

    }else if( c->Get().TestMode == uji::seq::pl::DEBUG )
    {
        TPLinear* tpl = new TPLinear;
        tpl->TouchPanelModuleTest( result );
        delete tpl;
    }else
    {
        TouchPanelCheck* tpc = new TouchPanelCheck;
        tpc->TestTPCommon( result );
        delete tpc;
    }
    delete c;
    
    std::strcpy( s_LogMessage, result.m_String );
    //if( !result.m_Result )
    //{
    //    WriteTouchPanelLogCommon( result, false );
    //}
    
    return result.m_Result;
}

bool WriteTouchPanelLog( uji::seq::TestResult &result )
{
    return WriteTouchPanelLogCommon( result, true );
}

bool WriteTouchPanelLogCommon( uji::seq::TestResult &result, bool isOKLog )
{
    uji::seq::Config  *c = new uji::seq::Config;
    
    result.m_Result = isOKLog;
    
    if( c->Get().TestMode == uji::seq::pl::DEBUG )
    {
        delete c;
        return result.m_Result;
    }
    char resultStr[15] = "";
    
    if( isOKLog )
    {
        std::sprintf( resultStr, "OK" );
    }else
    {
        std::sprintf( resultStr, "%02d-%03d-%03u", G_TP, TID_TP_CALIBRATION, result.m_Micro );
    }
    
    std::strcpy( result.m_String, s_LogMessage );
    uji::seq::ProductionLog* pdl = new uji::seq::ProductionLog();
    pdl->Initialize();
    if( 0 > pdl->Add_1Line( c->Get().TestMode,
                            g_TestListSet[c->GetAlternative().TestList].m_Name,
                            resultStr,
                            VERSION_STRING,
                            "",
                            "",
                            "",
                            result.m_String              ))

    {
        if( isOKLog )
        {
            std::sprintf( result.m_String, "Write Log Error");
            result.m_Result = false;
        }
    }

    delete pdl;
    delete c;
    return result.m_Result;

}

void TestTPSequencer()
{
    uji::seq::TestSequencer *s = new TestSequencer;
    s->Initialize();

    uji::seq::Config  *c = new uji::seq::Config;
    uji::seq::TestListManager *tlm = new TestListManager;

    if( !c->Load() )    c->Initialize();
    if( !tlm->Load() )  tlm->Initialize();

    c->SetAlternative().TestList = TESTLIST_ID_TP;
#ifdef EVA_TP_MODULE
    c->Set().TestMode = uji::seq::pl::DEBUG;
#endif
    s->Execute();

    delete tlm;
    delete c;
    delete s;
}

extern bool CheckTPAccuracy( uji::seq::TestResult &result )
{
    TouchPanelCheck* tpc = new TouchPanelCheck;
    tpc->TestTPCommon( result );
    delete tpc;
    
    return result.m_Result;
}

}


/*------------------------------------------------------------------------------
  Desc  : TouchPanel用メニュー

  Args  : none
  Return: none
------------------------------------------------------------------------------*/
void TouchPanelMenu()
{
    ClassMenu *m = new ClassMenu( "TouchPanelMenu" );
    m->Add( " TestTouchPanelLinear ", TPLinear::Execute );
    m->Add( " TestTouchPanel ",       TouchPanelCheck::Execute );
    m->Add( " TouchPanelCal ",        TouchPanelCal::Execute );
    m->Add( " TPJigCalibration",      TouchPanelCal::ExecuteJigCal );
    m->Add( " TPModuleTest",          TPLinear::ExecuteModuleTest );
    m->Open();
    delete m;

}
void TouchPanelMenuForService()
{
    ClassMenu *m = new ClassMenu( "TouchPanelMenu" );
    m->Add( " TestTouchPanelLinear ", TPLinear::Execute );
    m->Add( " TestTouchPanel ",       TouchPanelCheck::Execute );
    m->Open();
    delete m;

}

void ShowTestResult( uji::seq::TestResult &result )
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    
    sys::Menu::m_SubWindow->Printf("\f");
    if( result.m_Result )
    {
        sys::Menu::m_SubWindow->Printf("OK!\n");
    }else
    {
        sys::Menu::m_SubWindow->Printf("NG!\n");
    }
    sys::Menu::m_SubWindow->Printf("%s\n", result.m_String );
    sys::Menu::m_SubWindow->Printf("\nPress B To Return!");  
    
    sys::Menu::m_WindowManager.Update();
    
    gfx->m_DrawFramework->SetRenderTarget(NN_GX_DISPLAY1);
    gfx->m_DrawFramework->Clear();        
    sys::Menu::m_WindowManager.DrawDisplay1();
    gfx->m_DrawFramework->SwapBuffers();
    gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);

    do{
        uji::sys::Pad().UpdatePad();
    }while( !uji::sys::Pad().IsButtonPress( sys::Pad::BUTTON_B ));
    
}


/*------------------------------------------------------------------------------
  Desc  : ディスプレイ消去

  Args  : none
  Return: none
------------------------------------------------------------------------------*/
void BaseTouchPanel::ClearCampus()
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    SetDrawColor( nw::ut::Color8::WHITE );
    gfx->m_DrawFramework->FillRectangle( 0, 0, gfx->DISPLAY1_WIDTH, gfx->DISPLAY1_HEIGHT );
    SetDrawColor( nw::ut::Color8::BLACK );
}

/*------------------------------------------------------------------------------
  Desc  : タッチペンのリリース待ち

  Args  : none
  Return: none
------------------------------------------------------------------------------*/
void BaseTouchPanel::WaitReleasePen()
{
    do{
        nngxWaitVSync( NN_GX_DISPLAY_BOTH );
        m_TPReader.ReadLatest( &m_TPStatus );
    }while( m_TPStatus.touch );

}


/*------------------------------------------------------------------------------
  Desc  : 検査用のタッチポイント表示

  Args  : pos 表示する中心の座標
  Return: none
------------------------------------------------------------------------------*/
void BaseTouchPanel::DrawCheckPoint( const CoordinateType &pos )
{
    uji::seq::Config config;
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
    
    gfx->m_DrawFramework->SetLineWidth( 1.0f );
    
    gfx->m_DrawFramework->FillSquare( pos.x - config.Get().TpLinearMargine,     pos.y - config.Get().TpLinearMargine,
                                      pos.x - config.Get().TpLinearMargine,     pos.y + config.Get().TpLinearMargine + 1,
                                      pos.x + config.Get().TpLinearMargine + 1, pos.y + config.Get().TpLinearMargine + 1,
                                      pos.x + config.Get().TpLinearMargine + 1, pos.y - config.Get().TpLinearMargine );

    SetDrawColor( nw::ut::Color8::WHITE );
    gfx->m_DrawFramework->DrawLine( pos.x, pos.y - config.Get().TpLinearMargine + 1,
                                    pos.x, pos.y + config.Get().TpLinearMargine );

    gfx->m_DrawFramework->DrawLine( pos.x - config.Get().TpLinearMargine + 1, pos.y,
                                    pos.x + config.Get().TpLinearMargine,     pos.y );

    SetDrawColor( nw::ut::Color8::BLACK );
    gfx->m_DrawFramework->SetLineWidth( m_LineWidth );

}



/*------------------------------------------------------------------------------
  Desc  : 判定用座標と実際の入力座標の比較

  Args  : touchpos 比較用座標(入力座標はメンバ変数として持たせています)
  Return: 判定結果
------------------------------------------------------------------------------*/

bool BaseTouchPanel::IsJudgeTP( const CoordinateType &touchPos )
{
    uji::seq::Config config;
    if( !m_TPStatus.touch )
    {
        return false;
    }
    
    if(( m_TPStatus.x >= touchPos.x - config.Get().TpLinearMargine ) && ( m_TPStatus.x <= touchPos.x + config.Get().TpLinearMargine )
    && ( m_TPStatus.y >= touchPos.y - config.Get().TpLinearMargine ) && ( m_TPStatus.y <= touchPos.y + config.Get().TpLinearMargine ))
    {
        return true;
    }
    else
    {
        return false;
    }
}

/*------------------------------------------------------------------------------
  Desc  : キャリブレーション用のタッチポイント表示

  Args  : posX posY 表示する中心の座標
  Return: none
------------------------------------------------------------------------------*/
void BaseTouchPanel::DrawTouchPoint( const CoordinateType &pos )
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    
    uji::seq::Config cfg;
    if( cfg.GetAlternative().TpCalAutoMode == true )
    {
        DrawCircle( pos, cfg.Get().TpCalDotSize );
    }
    else
    {
        int posUU = pos.y - 6;
        int posUD = pos.y - 2;
        int posDU = pos.y + 3;
        int posDD = pos.y + 7;
        int posRR = pos.x - 6;
        int posRL = pos.x - 2;
        int posLR = pos.x + 3;
        int posLL = pos.x + 7;
        
        gfx->m_DrawFramework->DrawPoint( pos.x, pos.y );
        gfx->m_DrawFramework->DrawLine( pos.x, posUU, pos.x, posUD);  // ↑
        gfx->m_DrawFramework->DrawLine( pos.x, posDU, pos.x, posDD);  // ↓
        gfx->m_DrawFramework->DrawLine( posRR, pos.y, posRL, pos.y);  // →
        gfx->m_DrawFramework->DrawLine( posLR, pos.y, posLL, pos.y);  // ←
    }
}


/*------------------------------------------------------------------------------
  Desc  : カメラによる位置合わせ用のモデル表示

  Args  : none
  Return: none
------------------------------------------------------------------------------*/

void BaseTouchPanel::DrawCenterSquare()
{
    uji::seq::Config cfg;
    if( cfg.GetAlternative().TpCalAutoMode == true )
    {
        uji::seq::drawer::DrawOK();
    }
    else
    {
        uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();    

        const int SQUARE_SIZE = 50;

        gfx->m_DrawFramework->SetLineWidth( 2.0f );

        gfx->m_DrawFramework->DrawLine( POS_DISP1_CENTER_X, POS_DISP1_CENTER_Y - SQUARE_SIZE,
                                        POS_DISP1_CENTER_X, POS_DISP1_CENTER_Y + SQUARE_SIZE );  // │
        gfx->m_DrawFramework->DrawLine( POS_DISP1_CENTER_X - SQUARE_SIZE, POS_DISP1_CENTER_Y,
                                        POS_DISP1_CENTER_X + SQUARE_SIZE, POS_DISP1_CENTER_Y );  // ─

        gfx->m_DrawFramework->DrawLine( POS_DISP1_CENTER_X - SQUARE_SIZE, POS_DISP1_CENTER_Y - SQUARE_SIZE,    // |
                                        POS_DISP1_CENTER_X - SQUARE_SIZE, POS_DISP1_CENTER_Y + SQUARE_SIZE );
        gfx->m_DrawFramework->DrawLine( POS_DISP1_CENTER_X + SQUARE_SIZE, POS_DISP1_CENTER_Y - SQUARE_SIZE,    //  ￣
                                        POS_DISP1_CENTER_X - SQUARE_SIZE, POS_DISP1_CENTER_Y - SQUARE_SIZE );
        gfx->m_DrawFramework->DrawLine( POS_DISP1_CENTER_X + SQUARE_SIZE, POS_DISP1_CENTER_Y - SQUARE_SIZE,    //    |
                                        POS_DISP1_CENTER_X + SQUARE_SIZE, POS_DISP1_CENTER_Y + SQUARE_SIZE );
        gfx->m_DrawFramework->DrawLine( POS_DISP1_CENTER_X + SQUARE_SIZE, POS_DISP1_CENTER_Y + SQUARE_SIZE,    //  ＿
                                        POS_DISP1_CENTER_X - SQUARE_SIZE, POS_DISP1_CENTER_Y + SQUARE_SIZE );

        gfx->m_DrawFramework->SetLineWidth( 1.0f );
    }
}

/*------------------------------------------------------------------------------
  Desc  : TouchPanelLinearityチェック

  Args  : none
  Return: none
------------------------------------------------------------------------------*/
void TPLinear::TouchPanelLinear()
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();

    //--------------------------------------------------------------------------
    // 情報表示ウィンドウ部
    //--------------------------------------------------------------------------
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY0 );
    gfx->m_DrawFramework->Clear();

    uji::sys::WindowManager tp_WindowManager;
    TextWindow tp_Window( INFO_WINDOW_WIDTH / ( FONT_SIZE / 2 ), INFO_WINDOW_HEIGHT / FONT_SIZE, FONT_SIZE );
    tp_Window.SetTitle("TPLinear Info");

    tp_WindowManager.CreateWindow( &tp_Window, NN_GX_DISPLAY0, INFO_WINDOW_POS_X, INFO_WINDOW_POS_Y );

    tp_Window.Printf("B  :Exit Sequence\n");
    tp_Window.Printf("X  :Clear Display\n");
    tp_Window.Printf("A/Y:Change LineWidth\n");
    tp_Window.Printf("L  :Draw Chart\n");

    tp_WindowManager.Update();
    tp_WindowManager.DrawDisplay0();
    gfx->m_DrawFramework->SwapBuffers();

    //--------------------------------------------------------------------------
    // 下画面 お絵かき用
    //--------------------------------------------------------------------------
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
    gfx->m_DrawFramework->Clear();

    ClearCampus();

    DrawChartGrid();

    //--------------------------------------------------------------------------
    // TouchPanel準備
    //--------------------------------------------------------------------------
    nn::hid::CTR::TouchPanelStatus lastTPStatus;  // 線描画用に一つ前の座標を保持

    gfx->m_DrawFramework->SwapBuffers();
    while( true )
    {
        //----------------------------------------------------------------------
        // 各ステータス更新
        //----------------------------------------------------------------------
        m_TPReader.ReadLatest( &m_TPStatus );
        sys::Pad().UpdatePad();

        //----------------------------------------------------------------------
        // 上画面更新
        //----------------------------------------------------------------------


        //----------------------------------------------------------------------
        // 下画面処理
        //----------------------------------------------------------------------
        gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
        
        // Bボタン 抜ける
        if( sys::Pad().IsButtonDown( Pad::BUTTON_B ))
        {
            break;
        }
        
        // Xボタン 画面をクリア
        if( sys::Pad().IsButtonDown( Pad::BUTTON_X ))
        {
            TPLinear::DrawChartGrid();
        }
        
        // Aボタン 描画する線を太く
        if( sys::Pad().IsButtonDown( Pad::BUTTON_A ))
        {
            if( m_LineWidth < LINE_WIDTH_MAX )
            {
                m_LineWidth++;
                gfx->m_DrawFramework->SetLineWidth( m_LineWidth );
                gfx->m_DrawFramework->SetPointSize( m_LineWidth - 1.0f );
            }
        }
        
        // Yボタン 描画する線を細く
        if( sys::Pad().IsButtonDown( Pad::BUTTON_Y ))
        {
            if( m_LineWidth > LINE_WIDTH_MIN )
            {
                m_LineWidth--;
                gfx->m_DrawFramework->SetLineWidth( m_LineWidth );
                gfx->m_DrawFramework->SetPointSize( m_LineWidth - 1.0f );
            }
        }

        // Lボタン チャートを引き直す
        if( sys::Pad().IsButtonDown( Pad::BUTTON_L ))
        {
            TPLinear::DrawChartGrid();
        }
        
        // 前回の座標から今回の座標に向けて線を引く
        if( lastTPStatus.touch && m_TPStatus.touch )
        {
            {
                gfx->m_DrawFramework->DrawLine( m_TPStatus.x, m_TPStatus.y,
                                                  lastTPStatus.x, lastTPStatus.y );

                // 太さを上げた時に線がジャギるので対策
                // 前回の座標と今回の座標にドットを打つ
                gfx->m_DrawFramework->DrawPoint( m_TPStatus.x, m_TPStatus.y );
                gfx->m_DrawFramework->DrawPoint( lastTPStatus.x, lastTPStatus.y );
            }
        }

        //----------------------------------------------------------------------
        // ループ 後処理
        //----------------------------------------------------------------------
        lastTPStatus = m_TPStatus;  // 一つ前の座標をコピー
        gfx->m_DrawFramework->SwapBuffers();

    }
    
    gfx->m_DrawFramework->SetLineWidth( 1.0f );
    gfx->m_DrawFramework->SetPointSize( 1.0f );

    // Windowの破棄
    tp_WindowManager.DestroyWindow( &tp_Window );
    tp_Window.Destroy();

}

/*------------------------------------------------------------------------------
  Desc  : TouchPanelLinearityチェック

  Args  : none
  Return: none
------------------------------------------------------------------------------*/
bool TPLinear::TouchPanelModuleTest( uji::seq::TestResult &result )
{
    // まずはキャリブレーションを行う
    TouchPanelCal* tpc = new TouchPanelCal;
    tpc->TPCalCommon( result, true );
    delete tpc;
    
    if( result.m_Result == false )
    {
        result.m_Micro = ERROR_CAL;
        return result.m_Result;
    }
    
    // 暫定値
    {
        uji::seq::Config* config = new uji::seq::Config;
        config->Set().TpLinearMargine = 6;
        delete config;
    }
    
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();

    //--------------------------------------------------------------------------
    // 情報表示ウィンドウ部
    //--------------------------------------------------------------------------
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY0 );
    gfx->m_DrawFramework->Clear();

    uji::sys::WindowManager tp_WindowManager;
    TextWindow tp_Window( INFO_WINDOW_WIDTH / ( FONT_SIZE / 2 ), INFO_WINDOW_HEIGHT / FONT_SIZE, FONT_SIZE );
    tp_Window.SetTitle("TPLinear Info");

    tp_WindowManager.CreateWindow( &tp_Window, NN_GX_DISPLAY0, INFO_WINDOW_POS_X, INFO_WINDOW_POS_Y );

    tp_Window.Printf("B  :Exit Sequence\n");
    tp_Window.Printf("X  :Clear Display\n");
    tp_Window.Printf("A/Y:Change LineWidth\n");
    tp_Window.Printf("L  :Draw Chart\n");

    tp_WindowManager.Update();
    tp_WindowManager.DrawDisplay0();
    gfx->m_DrawFramework->SwapBuffers();

    //--------------------------------------------------------------------------
    // 下画面 お絵かき用
    //--------------------------------------------------------------------------
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
    gfx->m_DrawFramework->Clear();

    ClearCampus();
    DrawTestLine();
    
    const int CheckPointNum = sizeof( TpModuleList ) / sizeof( TpModuleList[0] );
    
    bool isTouchCheckStart[ CheckPointNum ];
    bool isTouchCheckEnd[ CheckPointNum ];
    bool isTestEnd;
    
    //--------------------------------------------------------------------------
    // TouchPanel準備
    //--------------------------------------------------------------------------
    nn::hid::CTR::TouchPanelStatus lastTPStatus;  // 線描画用に一つ前の座標を保持
    
    for( int i = 0; i < CheckPointNum; i++ )
    {
        isTouchCheckStart[i] = false;
        isTouchCheckEnd[i] = false;

        DrawTestMarker( isTouchCheckStart[i], TpModuleList[i].start );
        DrawTestMarker( isTouchCheckEnd[i], TpModuleList[i].end );
    }
    
    gfx->m_DrawFramework->SwapBuffers();
    while( true )
    {
        //----------------------------------------------------------------------
        // 各ステータス更新
        //----------------------------------------------------------------------
        m_TPReader.ReadLatest( &m_TPStatus );
        sys::Pad().UpdatePad();


        //----------------------------------------------------------------------
        // 下画面処理
        //----------------------------------------------------------------------
        gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );


        //----------------------------------------------------------------------
        // キー操作
        
        if( sys::Pad().IsButtonDown( Pad::BUTTON_X ))
        {
            ClearCampus();
        }

        if( sys::Pad().IsButtonDown( Pad::BUTTON_A ))
        {
            if( m_LineWidth < LINE_WIDTH_MAX )
            {
                m_LineWidth++;
                gfx->m_DrawFramework->SetLineWidth( m_LineWidth );
                gfx->m_DrawFramework->SetPointSize( m_LineWidth - 1.0f );
            }
        }
        if( sys::Pad().IsButtonDown( Pad::BUTTON_Y ))
        {
            if( m_LineWidth > LINE_WIDTH_MIN )
            {
                m_LineWidth--;
                gfx->m_DrawFramework->SetLineWidth( m_LineWidth );
                gfx->m_DrawFramework->SetPointSize( m_LineWidth - 1.0f );
            }
        }

        if( sys::Pad().IsButtonDown( Pad::BUTTON_L ))
        {
            TPLinear::DrawTestLine();
        }

        //----------------------------------------------------------------------
        // 描画処理
        if( lastTPStatus.touch && m_TPStatus.touch )
        {
            {
                gfx->m_DrawFramework->DrawLine( m_TPStatus.x, m_TPStatus.y,
                                                lastTPStatus.x, lastTPStatus.y );

                // 太さを上げた時に線がジャギるので対策
                gfx->m_DrawFramework->DrawPoint( m_TPStatus.x, m_TPStatus.y );
                gfx->m_DrawFramework->DrawPoint( lastTPStatus.x, lastTPStatus.y );
            }
            for( int i = 0; i < CheckPointNum; i++ )
            {
                if( IsJudgeTP( TpModuleList[i].start ))
                {
                    isTouchCheckStart[i] = true;
                }

                if( IsJudgeTP( TpModuleList[i].end ))
                {
                    isTouchCheckEnd[i] = true;
                }

            }

        }
        
        //----------------------------------------------------------------------
        // 判定処理
        isTestEnd = true;
        for( int j = 0; j < CheckPointNum;j++ )
        {
            if( !m_TPStatus.touch && ( isTouchCheckStart[j] ^ isTouchCheckEnd[j] ))
            {
                #if 0
                isTouchCheckStart[j] = false;
                isTouchCheckEnd[j]   = false;
                #endif
                isTestEnd = true;
                result.m_Result = false;
                break;
            }
            DrawTestMarker( isTouchCheckStart[j], TpModuleList[j].start );
            DrawTestMarker( isTouchCheckEnd[j], TpModuleList[j].end );
            isTestEnd &= isTouchCheckStart[j] & isTouchCheckEnd[j];
        }
        
        if( isTestEnd )
        {
            break;
        }

        //----------------------------------------------------------------------
        // ループ 後処理
        //----------------------------------------------------------------------
        lastTPStatus = m_TPStatus;  // 一つ前の座標をコピー
        gfx->m_DrawFramework->SwapBuffers();

    }
    
    gfx->m_DrawFramework->SetLineWidth( 1.0f );
    gfx->m_DrawFramework->SetPointSize( 1.0f );

    // Windowの破棄
    tp_WindowManager.DestroyWindow( &tp_Window );
    tp_Window.Destroy();

    return result.m_Result;

}

//------------------------------------------------------------------------------
// ライン引き
//------------------------------------------------------------------------------
void TPLinear::DrawChartGrid()
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    ClearCampus();
    SetDrawColor( nw::ut::Color8::GREEN );

    gfx->m_DrawFramework->SetLineWidth( 2.0f );

    gfx->m_DrawFramework->DrawLine( POS_DISP1_CENTER_X, 0, POS_DISP1_CENTER_X, POS_DISP1_HEIGHT ); // │
    gfx->m_DrawFramework->DrawLine( 0, POS_DISP1_CENTER_Y, POS_DISP1_WIDTH, POS_DISP1_CENTER_Y );  // ─
    gfx->m_DrawFramework->DrawLine( 0, 0, POS_DISP1_WIDTH, POS_DISP1_HEIGHT );                     // ＼
    gfx->m_DrawFramework->DrawLine( 0, POS_DISP1_HEIGHT, POS_DISP1_WIDTH, 0 );                     // ／

    gfx->m_DrawFramework->SetLineWidth( m_LineWidth );
    SetDrawColor( nw::ut::Color8::BLACK );
}

//------------------------------------------------------------------------------
// マーカー
//------------------------------------------------------------------------------
void TPLinear::DrawTestMarker( bool isTouched, CoordinateType pos )
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();

    if( isTouched )
    {
        SetDrawColor( nw::ut::Color8::BLUE );
    }
    else
    {
        SetDrawColor( nw::ut::Color8::RED );
    }
    DrawCheckPoint( pos );

    gfx->m_DrawFramework->SetLineWidth( m_LineWidth );
    SetDrawColor( nw::ut::Color8::BLACK );
}

void TPLinear::DrawTestLine()
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    ClearCampus();

    SetDrawColor( nw::ut::Color8::GREEN );

    gfx->m_DrawFramework->SetLineWidth( 13.0f );
    for( int i = 0; i < sizeof( TpModuleList ) / sizeof( TpModuleList[0]); i++ )
    {
        gfx->m_DrawFramework->DrawLine( TpModuleList[i].start.x, TpModuleList[i].start.y, TpModuleList[i].end.x, TpModuleList[i].end.y );
    }

    gfx->m_DrawFramework->SetLineWidth( m_LineWidth );
    SetDrawColor( nw::ut::Color8::BLACK );
}


/*------------------------------------------------------------------------------
  Desc  : 通常のタッチパネル検査

  Args  : none
  Return: none
------------------------------------------------------------------------------*/

bool TouchPanelCheck::TestTPCommon( uji::seq::TestResult &testResult )
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    
    uji::seq::Config cfg;
    //--------------------------------------------------------------------------
    // 情報表示ウィンドウ部
    //--------------------------------------------------------------------------
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY0 );
    gfx->m_DrawFramework->Clear();

    uji::sys::WindowManager tp_WindowManager;
    TextWindow tp_Window( INFO_WINDOW_WIDTH / ( FONT_SIZE / 2 ), ( sizeof( CheckPointList ) / sizeof( CheckPointList[0] )) + 4, FONT_SIZE );
    TextWindow tp_VerWindow( TP_VER_WINDOW_WIDTH / ( FONT_SIZE / 2 ), TP_VER_WINDOW_HEIGHT / FONT_SIZE, FONT_SIZE );

    tp_Window.SetTitle("TPTest Info");
    tp_VerWindow.SetTitle("TPTest Ver");

    tp_Window.SetTextColor( uji::sys::ATTR_COLOR_WHITE );

    tp_WindowManager.CreateWindow( &tp_Window, NN_GX_DISPLAY0, INFO_WINDOW_POS_X, INFO_WINDOW_POS_Y );
    tp_WindowManager.CreateWindow( &tp_VerWindow, NN_GX_DISPLAY0, TP_VER_WINDOW_POS_X, TP_VER_WINDOW_POS_Y );

    tp_VerWindow.Printf("Ver : %s ( %s )\n",VERSION_STRING, VERSION_DATE );

    tp_Window.Printf("TouchMargin = %dpx\n", cfg.Get().TpLinearMargine );
    tp_Window.Printf("Retry = 0 / %1d\n\n", cfg.Get().TpCheckRetry );

    tp_WindowManager.Update();
    tp_WindowManager.DrawDisplay0();

    gfx->m_DrawFramework->SwapBuffers();

    //--------------------------------------------------------------------------
    // 下画面 タッチパネル検査
    //--------------------------------------------------------------------------
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
    gfx->m_DrawFramework->Clear();

    ClearCampus();
    gfx->m_DrawFramework->SwapBuffers();
    gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);

    //--------------------------------------------------------------------------
    // 前処理＆テストループ
    //--------------------------------------------------------------------------
    bool isError = false;
    u8   Retry   = 0;

    int CheckNum = sizeof( CheckPointList ) / sizeof( CheckPointList[0] );
    
    LoadCalData();
    
    nn::hid::TouchPanelStatus tp_StatusList[ cfg.Get().TpCheckRetry + 1 ][ CheckNum ];
    std::memset( tp_StatusList, 0x00, sizeof( tp_StatusList ));
    
    WaitReleasePen();
    
    for( int nowState = 0; nowState < CheckNum; nowState++ )
    {
        if( isError )
        {
            nowState = 0;

            if( ++Retry > cfg.Get().TpCheckRetry )
            {
                NN_LOG("NG!\n");
                std::sprintf( testResult.m_String, "" );
                char messageBuf[80] = "";
                for( int j = 0; j <= cfg.Get().TpCheckRetry; j++ )
                {
                    std::memset( messageBuf, 0x00, sizeof( messageBuf ));
                    std::sprintf( messageBuf, "(%d.%d)-(%d.%d)-(%d.%d)",    tp_StatusList[j][0].x, tp_StatusList[j][0].y,
                                                                            tp_StatusList[j][1].x, tp_StatusList[j][1].y,
                                                                            tp_StatusList[j][2].x, tp_StatusList[j][2].y );
                    std::strcat( testResult.m_String, messageBuf );
                    std::strcat( testResult.m_String, "\n" );
                }
                testResult.m_Result = false;
                testResult.m_Micro = TP_CHECK_RETRY_ERROR;
                goto END_CHECK;
            }

            isError  = false;

            tp_Window.Printf("\f");
            tp_Window.Printf("TouchMargin = %dpx\n", cfg.Get().TpLinearMargine );
            tp_Window.Printf("Retry = %1d / %1d\n\n", Retry, cfg.Get().TpCheckRetry );
        }

        tp_Window.Printf("( %3d, %3d ) = ", CheckPointList[nowState].x, CheckPointList[nowState].y );

        do{
            // TPの情報取得
            m_TPReader.ReadLatest( &m_TPStatus );
            tp_StatusList[ Retry ][ nowState ] = m_TPStatus;

            // 上画面描画
            gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY0 );
            gfx->m_DrawFramework->Clear();
            tp_WindowManager.Update();
            tp_WindowManager.DrawDisplay0();

            gfx->m_DrawFramework->SwapBuffers();

            // 下画面描画
            gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
            gfx->m_DrawFramework->Clear();
            ClearCampus();
            
            if( cfg.GetAlternative().TpCalAutoMode == true )
            {
                for( int i = 0; i <= nowState; i++ )
                {
                    DrawTouchPoint( CheckPointList[i] );
                }
            }else
            {
                if( nowState >= 1 )
                {
                    PaintOutSquareLU();
                    if( nowState == 2 )
                    {
                        PaintOutSquareRD();
                    }
                }
                                
                for( int i = 0; i < nowState; i++ )
                {
                    DrawCheckPoint( CheckPointList[i] );
                }
                DrawCheckPointBlue( CheckPointList[nowState] );
            }
            DrawCenterSquare();
            gfx->m_DrawFramework->SwapBuffers();

            // VBlank待ち
            gfx->m_DrawFramework->WaitVsync(NN_GX_DISPLAY_BOTH);
        }while( !m_TPStatus.touch );

        nn::os::Thread::Sleep( nn::fnd::TimeSpan::FromMilliSeconds(100));

        if( !IsJudgeTP( CheckPointList[nowState] ))
        {
            isError = true;
            nowState--;
        }
        else
        {
            tp_Window.Printf("( %3d, %3d )\n", m_TPStatus.x, m_TPStatus.y );
        }

        WaitReleasePen();
    }
    
    // 上画面描画
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY0 );
    gfx->m_DrawFramework->Clear();
    tp_WindowManager.Update();
    tp_WindowManager.DrawDisplay0();
    
    gfx->m_DrawFramework->SwapBuffers();
    //std::sprintf( testResult.m_String, "OK");
    testResult.m_Result = true;
    std::sprintf( testResult.m_String, "( %d. %d ) - ( %d. %d )", tp_StatusList[ Retry ][0].x, tp_StatusList[ Retry ][0].y,
                                                                  tp_StatusList[ Retry ][1].x, tp_StatusList[ Retry ][1].y );

// SDカードへのデータ取り
#if 0
    {    
        NN_LOG("Write SD to Data\n");
        // コンフィグ用
        char sdMessage[200] = "";
        char macAddressStr[12+1];
#ifndef EVA_SP_AND_TP
        if( cfg.Get().TestMode == 0 )
#endif
        {
            
            nn::Result nnr = nn::fs::MountSdmc();
            if (nnr.IsFailure())
            {
                goto END_CHECK;;
            }
            
            nn::fs::TryCreateDirectory(L"sdmc:/uji/");
            nn::fs::TryCreateDirectory(L"sdmc:/uji/tp/");
            
            nn::fs::FileStream fos;
            nnr = fos.TryInitialize( L"sdmc:/uji/tp/tpData.csv", nn::fs::OPEN_MODE_READ   |
                                                                 nn::fs::OPEN_MODE_WRITE  |
                                                                 nn::fs::OPEN_MODE_CREATE );
                                                                 
            if( nnr.IsFailure())
            {
                // ファイルを閉じる
                NN_LOG("SDMC OPEN FAILURE\n");
                fos.Finalize();
                nn::fs::Unmount("sdmc:");
                goto END_CHECK;
            }
            
            s64 size = fos.GetSize();
            NN_LOG("FILE_SIZE= %lld\n", size);

            if( size == 0 )
            {
                char TITLE[200] = "";
                sprintf( TITLE, "MacAddress,Retry,X1(%d),Y1(%d),X2(%d),Y2(%d),X3(%d),Y3(%d),Day,Time,\n",
                         PosLU.x, PosLU.y, PosRD.x, PosRD.y, PosRU.x, PosRU.y );
                // 初回のみ上記TITLE文字列をファイルに書き込む
                fos.Write( TITLE, strlen(TITLE) );
            }
            else
            {
                // 二回目以降はファイルの終端に移動
                fos.Seek( -1, nn::fs::POSITION_BASE_END );
            }
            uji::sys::GetMacAddressStr( macAddressStr );
            nn::fnd::DateTime now = nn::fnd::DateTime::GetNow();
            sprintf( sdMessage, "%s,%d,%d,%d,%d,%d,%d,%d,%04d/%02d/%02d,%02d:%02d:%02d,\n@", macAddressStr, Retry,
                                                               tp_StatusList[ Retry ][0].x, tp_StatusList[ Retry ][0].y,
                                                               tp_StatusList[ Retry ][1].x, tp_StatusList[ Retry ][1].y,
                                                               tp_StatusList[ Retry ][2].x, tp_StatusList[ Retry ][2].y,
                                                               now.GetYear(), now.GetMonth(), now.GetDay(),
                                                               now.GetHour(), now.GetMinute(),now.GetSecond());
            fos.Write( sdMessage, strlen( sdMessage ));
            if( nnr.IsFailure())
            {
                // ファイルを閉じる
                NN_LOG("SDMC OPEN FAILURE\n");
                fos.Finalize();
                nn::fs::Unmount("sdmc:");
                goto END_CHECK;
            }
            // ファイルを閉じる
            fos.Finalize();
            nn::fs::Unmount("sdmc:");
        }
    }
#endif

    END_CHECK:
    // Windowの破棄
    tp_WindowManager.DestroyWindow( &tp_Window );
    tp_Window.Destroy();
    return testResult.m_Result;


}

void BaseTouchPanel::LoadCalData()
{
    nn::hid::CTR::TouchPanelCalibrator tpCal;
    nn::drivers::cal::CTR::TouchPanelCalDataCore tpDataCore;
    nn::drivers::cal::CTR::Calibration cal;
    cal.Initialize();
    cal.Get( &tpDataCore, nn::drivers::cal::CTR::CAL_DATA_TOUCH_PANEL );

    tpCal.SetCalibrateParam( tpDataCore.point0.dx, tpDataCore.point0.dy, tpDataCore.point0.raw_x, tpDataCore.point0.raw_y,
                             tpDataCore.point1.dx, tpDataCore.point1.dy, tpDataCore.point1.raw_x, tpDataCore.point1.raw_y );
}

/*------------------------------------------------------------------------------
  Desc  : キャリブレーション本体
          現在はA/Yボタンでチェックポイントの表示のみ

  Args  : none
  Return: none
------------------------------------------------------------------------------*/

bool TouchPanelCal::TPCalCommon( uji::seq::TestResult &result, bool isModuleTest )
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    
    uji::seq::Config cfg;
    
    //--------------------------------------------------------------------------
    // 情報表示ウィンドウ部
    //--------------------------------------------------------------------------
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY0 );
    gfx->m_DrawFramework->Clear();

    uji::sys::WindowManager tp_WindowManager;
    TextWindow tp_InfoWindow( INFO_WINDOW_WIDTH / ( FONT_SIZE / 2 ), INFO_WINDOW_HEIGHT / FONT_SIZE, FONT_SIZE );
    TextWindow tp_VerWindow( TP_VER_WINDOW_WIDTH / ( FONT_SIZE / 2 ), TP_VER_WINDOW_HEIGHT / FONT_SIZE, FONT_SIZE );

    tp_InfoWindow.SetTitle("TPCal Info");
    tp_VerWindow.SetTitle("TPCal Ver");

    tp_WindowManager.CreateWindow( &tp_InfoWindow, NN_GX_DISPLAY0, INFO_WINDOW_POS_X, INFO_WINDOW_POS_Y );
    tp_WindowManager.CreateWindow( &tp_VerWindow, NN_GX_DISPLAY0, TP_VER_WINDOW_POS_X, TP_VER_WINDOW_POS_Y );

    tp_VerWindow.Printf("Ver : %s ( %s )\n",VERSION_STRING, VERSION_DATE );

    tp_WindowManager.Update();
    tp_WindowManager.DrawDisplay0();

    gfx->m_DrawFramework->SwapBuffers();


    //--------------------------------------------------------------------------
    // 下画面 キャリブレーション表示
    //--------------------------------------------------------------------------
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );

    ClearCampus();
    gfx->m_DrawFramework->SwapBuffers();


    //--------------------------------------------------------------------------
    // TouchPanel準備
    //--------------------------------------------------------------------------

    DrawCenterSquare();


    nn::hid::TouchPanelStatus rawLU;
    nn::hid::TouchPanelStatus rawRD;

    m_NowCalibState     = STATE_NO_GET_RAW;
    int Cal_Retry       = 0;
    int Cal_Check_Retry = 0;

    nn::Result nnr;
    
    while( m_NowCalibState != STATE_END )
    {
        gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
        gfx->m_DrawFramework->Clear();

        ClearCampus();
        DrawCenterSquare();
        gfx->m_DrawFramework->SwapBuffers();

        gfx->m_DrawFramework->WaitVsync( NN_GX_DISPLAY_BOTH );

        switch( m_NowCalibState )
        {
            case STATE_NO_GET_RAW:
                if( !GetRawDataForCalibration( &rawLU, PosLU ))
                {
                    result.m_Result = false;
                    std::sprintf( result.m_String, "TimeOut" );
                    result.m_Micro = TP_CAL_TIMEOUT_ERROR;
                    m_NowCalibState = STATE_END;
                    break;
                }
                m_NowCalibState = STATE_GET_RAW_LU;
                tp_InfoWindow.Printf("(%d,%d)", rawLU.x, rawLU.y );
                break;

            case STATE_GET_RAW_LU:
                DrawTouchPoint( PosLU );
                if( cfg.GetAlternative().TpCalAutoMode == false )
                {
                    PaintOutSquareLU();
                    
                }
                DrawCenterSquare();
                if( !GetRawDataForCalibration( &rawRD, PosRD ))
                {
                    result.m_Result = false;
                    std::sprintf( result.m_String, "TimeOut" );
                    result.m_Micro = TP_CAL_TIMEOUT_ERROR;
                    m_NowCalibState = STATE_END;
                    break;
                }
                m_NowCalibState = STATE_GET_RAW_RD;
                tp_InfoWindow.Printf("-(%d,%d)\n", rawRD.x, rawRD.y );
                break;

            case STATE_GET_RAW_RD:
          
                nnr = m_TPCal.SetCalibrateParam( PosLU.x, PosLU.y, rawLU.x, rawLU.y,
                                                 PosRD.x, PosRD.y, rawRD.x, rawRD.y );
                if( nnr.IsFailure())
                {
                    if( ++Cal_Retry >= cfg.GetAlternative().TpCalRetry )
                    {
                        result.m_Result = false;
                        result.m_Micro = TP_CAL_RETRY_ERROR;
                        std::sprintf( result.m_String, "SetCalErr:(%d,%d)-(%d,%d)", rawLU.x, rawLU.y, rawRD.x, rawRD.y );
                        m_NowCalibState = STATE_END;
                        break;
                    }
                    tp_InfoWindow.Printf("\f");
                    m_NowCalibState = STATE_NO_GET_RAW;
                    break;
                }
                
                if( isModuleTest )
                {
                    result.m_Result = true;
                    m_NowCalibState = STATE_END;
                    break;
                }
                
                DrawTouchPoint( PosLU );
                DrawTouchPoint( PosRD );
                if( cfg.GetAlternative().TpCalAutoMode == false )
                {
                    PaintOutSquareLU();
                    PaintOutSquareRD();
                }
                DrawCenterSquare();
                
                DrawTouchPoint( PosRU );
                
                gfx->m_DrawFramework->SwapBuffers();
                if( !IsJudgeCalibration( PosRU ) )
                {
                    if( ++Cal_Check_Retry >= cfg.GetAlternative().TpCalCheckRetry )
                    {
                        result.m_Result = false;
                        result.m_Micro = TP_CHECK_RETRY_ERROR;
                        std::sprintf( result.m_String, "CheckErr:(%d.%d->%d.%d)", PosRU.x, PosRU.y, m_TPStatus.x, m_TPStatus.y );
                        m_NowCalibState = STATE_END;
                        break;
                    }
                    m_NowCalibState = STATE_NO_GET_RAW;
                    Cal_Retry = 0;
                    tp_InfoWindow.Printf("\f");
                    WaitReleasePen();
                    break;
                }
                result.m_Result = true;
                std::sprintf( result.m_String, "(%d.%d)-(%d.%d)->(%d.%d)", rawLU.x, rawLU.y, rawRD.x, rawRD.y, m_TPStatus.x, m_TPStatus.y );
                WaitReleasePen();
                m_NowCalibState = STATE_FLUSH_CAL;
                break;
                
            case STATE_FLUSH_CAL:
                NN_LOG("State_Cal\n");
                if( !FlushCalData( rawLU, rawRD ))
                {
                    result.m_Result = false;
                    result.m_Micro = TP_CAL_WRITE_ERROR;
                    std::sprintf( result.m_String, "Write CalData Error" );
                }
                m_NowCalibState = STATE_END;
                break;

        }

        gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY0 );
        gfx->m_DrawFramework->Clear();


        tp_WindowManager.Update();
        tp_WindowManager.DrawDisplay0();

        gfx->m_DrawFramework->SwapBuffers();
    }



    // Windowの破棄
    tp_WindowManager.DestroyWindow( &tp_InfoWindow );
    tp_InfoWindow.Destroy();

    return result.m_Result;
}

bool TouchPanelCal::FlushCalData( const nn::hid::TouchPanelStatus &rawLU, const nn::hid::TouchPanelStatus &rawRD )
{
    nn::drivers::cal::CTR::Calibration calibration;
    nn::drivers::cal::CTR::TouchPanelPoint tpPointLU,tpPointRD;
    nn::drivers::cal::CTR::TouchPanelCalDataCore tpCalDataCore;

    bool result = true;
    calibration.Initialize();

    tpPointLU.raw_x = rawLU.x;
    tpPointLU.raw_y = rawLU.y;
    tpPointLU.dx    = PosLU.x;
    tpPointLU.dy    = PosLU.y;
    tpPointRD.raw_x = rawRD.x;
    tpPointRD.raw_y = rawRD.y;
    tpPointRD.dx    = PosRD.x;
    tpPointRD.dy    = PosRD.y;

    tpCalDataCore.point0 = tpPointLU;
    tpCalDataCore.point1 = tpPointRD;

    if( !calibration.Set( &tpCalDataCore, nn::drivers::cal::CTR::CAL_DATA_TOUCH_PANEL ))
    {
        result = false;
    }

    // NANDへの書き出し
    if( !calibration.Flush())
    {
        result = false;
    }
    if( !calibration.IsAdjusted( nn::drivers::cal::CTR::CAL_DATA_TOUCH_PANEL ))
    {
        result = false;
    }

    nn::drivers::cal::CTR::TouchPanelCalData tpCalVerify;
    calibration.Get( &tpCalVerify, nn::drivers::cal::CTR::CAL_DATA_TOUCH_PANEL );

    {
        NN_LOG("-------------------------------------------\n");
        NN_LOG("  Cal.point0.Raw_x = %4d  rawLU.x = %4d\n", tpCalVerify.c.point0.raw_x, rawLU.x );
        NN_LOG("  Cal.point0.Raw_y = %4d  rawLU.y = %4d\n", tpCalVerify.c.point0.raw_y, rawLU.y );
        NN_LOG("  Cal.point1.Raw_x = %4d  rawRD.x = %4d\n", tpCalVerify.c.point1.raw_x, rawRD.x );
        NN_LOG("  Cal.point1.Raw_y = %4d  rawRD.y = %4d\n", tpCalVerify.c.point1.raw_y, rawRD.y );
        NN_LOG("-------------------------------------------\n");
    }
    return result;
}


// 直径引数
void BaseTouchPanel::DrawCircle( const CoordinateType &pos, const int size )
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();
    
    int x = 0;
    int y = size/2+1;
    double d;
    d = -size*size + 4*y*y -4*y +2;
    int dx, dy;
    dx = 4;
    dy = -8*y+8;
    CoordinateType mirror_center = pos;
    if ((size&1) ==0)
    {
        mirror_center.x++;
        mirror_center.y++;
    }

    for (x=0; x <= y ; x++)
    {
        if (d>0) {
            d += dy;
            dy += 8;
            y--;
        }
        gfx->m_DrawFramework->DrawPoint(  y + pos.x, x + pos.y );        // 0-45     度の間
        gfx->m_DrawFramework->DrawPoint(  x + pos.x, y + pos.y );        // 45-90    度の間

        gfx->m_DrawFramework->DrawPoint( -x + mirror_center.x, y + pos.y ); // 90-135   度の間
        gfx->m_DrawFramework->DrawPoint( -y + mirror_center.x, x + pos.y ); // 135-180  度の間

        gfx->m_DrawFramework->DrawPoint( -y + mirror_center.x, -x + mirror_center.y );  // 180-225  度の間
        gfx->m_DrawFramework->DrawPoint( -x + mirror_center.x, -y + mirror_center.y );  // 225-270  度の間

        gfx->m_DrawFramework->DrawPoint(  x + pos.x, -y + mirror_center.y ); // 270-315  度の間
        gfx->m_DrawFramework->DrawPoint(  y + pos.x, -x + mirror_center.y ); // 315-360  度の間
        
        gfx->m_DrawFramework->DrawLine( y + pos.x, x + pos.y, -y + mirror_center.x, x + pos.y );
        gfx->m_DrawFramework->DrawLine( x + pos.x, y + pos.y, -x + mirror_center.x, y + pos.y );
        gfx->m_DrawFramework->DrawLine( -y + mirror_center.x, -x + mirror_center.y, y + pos.x, -x + mirror_center.y );
        gfx->m_DrawFramework->DrawLine( -x + mirror_center.x, -y + mirror_center.y, x + pos.x, -y + mirror_center.y );

        d += dx;
        dx+=8;
    }
    SetDrawColor( nw::ut::Color8::WHITE );
    gfx->m_DrawFramework->DrawPoint( pos.x, pos.y );              // Center
    SetDrawColor( nw::ut::Color8::BLACK );
    
}

void BaseTouchPanel::PaintOutSquareLU()
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();

    const int SQUARE_SIZE = 50;

    SetDrawColor( nw::ut::Color8::GREEN );

    gfx->m_DrawFramework->FillSquare( POS_DISP1_CENTER_X - SQUARE_SIZE, POS_DISP1_CENTER_Y - SQUARE_SIZE,
                                      POS_DISP1_CENTER_X - SQUARE_SIZE, POS_DISP1_CENTER_Y,
                                      POS_DISP1_CENTER_X,               POS_DISP1_CENTER_Y,
                                      POS_DISP1_CENTER_X,               POS_DISP1_CENTER_Y - SQUARE_SIZE );

    SetDrawColor( nw::ut::Color8::BLACK );
}


void BaseTouchPanel::PaintOutSquareRD()
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();

    const int SQUARE_SIZE = 50;

    SetDrawColor( nw::ut::Color8::GREEN );

    gfx->m_DrawFramework->FillSquare( POS_DISP1_CENTER_X,               POS_DISP1_CENTER_Y,
                                      POS_DISP1_CENTER_X,               POS_DISP1_CENTER_Y + SQUARE_SIZE,
                                      POS_DISP1_CENTER_X + SQUARE_SIZE, POS_DISP1_CENTER_Y + SQUARE_SIZE,
                                      POS_DISP1_CENTER_X + SQUARE_SIZE, POS_DISP1_CENTER_Y );

    SetDrawColor( nw::ut::Color8::BLACK );
}



bool TouchPanelCal::GetRawDataForCalibration( nn::hid::TouchPanelStatus* pReturnRaw, const CoordinateType &point )
{
    DrawTouchPoint( point );

    uji::sys::GraphicsDrawing* gfx = uji::sys::GraphicsDrawing::GetInstance();
    gfx->m_DrawFramework->WaitVsync( NN_GX_DISPLAY_BOTH );
    gfx->m_DrawFramework->SwapBuffers();
    
    uji::seq::Config cfg;
    nn::hid::TouchPanelStatus checkTPStatus[ cfg.Get().TpCheckRawNum ];

    const u32 TPRAW_PER_LCD_X = 4095 / 320;
    const u32 TPRAW_PER_LCD_Y = 4095 / 240;
    const u32 TPRAW_MARGINE   = 1000;

    const int TP_X_MIN_MARGINE = (( point.x * TPRAW_PER_LCD_X ) - TPRAW_MARGINE );
    const int TP_Y_MIN_MARGINE = (( point.y * TPRAW_PER_LCD_Y ) - TPRAW_MARGINE );
    const int TP_X_MAX_MARGINE = (( point.x * TPRAW_PER_LCD_X ) + TPRAW_MARGINE );
    const int TP_Y_MAX_MARGINE = (( point.y * TPRAW_PER_LCD_Y ) + TPRAW_MARGINE );
    
    // 時間計測用
    nn::os::Tick start_tick = nn::os::Tick::GetSystemCurrent();


    NN_LOG("x = %d, y = %d\n",( point.x * TPRAW_PER_LCD_X ), ( point.y * TPRAW_PER_LCD_Y ));
    NN_LOG("x margine = %d\n", TP_X_MIN_MARGINE );
    do{
        int i = 0;
        while( i < cfg.Get().TpCheckRawNum )
        {
            if( cfg.GetAlternative().TpCalAutoMode && ( nn::os::Tick::GetSystemCurrent() - start_tick ).ToTimeSpan().GetSeconds() >= cfg.Get().TpCalTimeOut )
            {
                return false;
            }
            
            nn::os::Thread::Sleep( nn::fnd::TimeSpan::FromMilliSeconds(4));

            m_TPCal.ReadRaw( &checkTPStatus[i] );

            if( ( checkTPStatus[i].x > TP_X_MIN_MARGINE ) &&
                ( checkTPStatus[i].x < TP_X_MAX_MARGINE ) &&
                ( checkTPStatus[i].y > TP_Y_MIN_MARGINE ) &&
                ( checkTPStatus[i].y < TP_Y_MAX_MARGINE ) &&
                ( checkTPStatus[i].touch ))
            {
                i++;
            }
            else
            {
                i = 0;      // ペンが離れたら振り出しに戻る
                continue;
            }
        }
    }while(!IsJudgeRawDataValiety( checkTPStatus, cfg.Get().TpCheckRawNum ));

    pReturnRaw->x       = checkTPStatus[ cfg.Get().TpCheckRawNum-1 ].x;
    pReturnRaw->y       = checkTPStatus[ cfg.Get().TpCheckRawNum-1 ].y;
    pReturnRaw->touch   = checkTPStatus[ cfg.Get().TpCheckRawNum-1 ].touch;

    WaitReleasePen();
    return true;
}

bool TouchPanelCal::IsJudgeCalibration( const CoordinateType &pos )
{
    // 時間計測用
    nn::os::Tick start_tick = nn::os::Tick::GetSystemCurrent();
    uji::seq::Config cfg;

    while( true )
    {
        if( cfg.GetAlternative().TpCalAutoMode && ( nn::os::Tick::GetSystemCurrent() - start_tick ).ToTimeSpan().GetSeconds() >= cfg.Get().TpCalTimeOut )
        {
            return false;
        }
        // TPの情報取得
        m_TPReader.ReadLatest( &m_TPStatus );

        if( !m_TPStatus.touch )
        {
            nn::os::Thread::Sleep( nn::fnd::TimeSpan::FromMilliSeconds(4));
            continue;
        }
        else if( !IsJudgeTP( pos ) )
        {
            return false;
        }
        return true;
    }
}


bool TouchPanelCal::IsJudgeRawDataValiety( const nn::hid::TouchPanelStatus* pTPStatus, const u16 &checkNum )
{
    NN_UNUSED_VAR( pTPStatus )
    u32 minX = pTPStatus[0].x;
    u32 minY = pTPStatus[0].y;
    u32 maxX = pTPStatus[0].x;
    u32 maxY = pTPStatus[0].y;
    
    uji::seq::Config cfg;
    
    for( int i = 0; i < checkNum; i++ )
    {
        if( pTPStatus[i].x < minX ) { minX = pTPStatus[i].x; }
        if( pTPStatus[i].y < minY ) { minY = pTPStatus[i].y; }
        if( pTPStatus[i].x > maxX ) { maxX = pTPStatus[i].x; }
        if( pTPStatus[i].y > maxY ) { maxX = pTPStatus[i].y; }
    }

    NN_LOG("maxX = %d\nminX = %d\nmaxY = %d\nminY = %d\n", maxX, minX, maxY, minY );

    if(( maxX - minX ) < cfg.Get().TpCalibValiety && ( maxY - minY ) < cfg.Get().TpCalibValiety )
    {
        return true;
    }
    else
    {
        return false;
    }

}


bool TouchPanelCal::forJigCalibration( uji::seq::TestResult &result )
{
    uji::sys::GraphicsDrawing *gfx = uji::sys::GraphicsDrawing::GetInstance();

    //--------------------------------------------------------------------------
    // 情報表示ウィンドウ部
    //--------------------------------------------------------------------------
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY0 );
    gfx->m_DrawFramework->Clear();

    uji::sys::WindowManager tp_WindowManager;
    TextWindow tp_InfoWindow( INFO_WINDOW_WIDTH / ( FONT_SIZE / 2 ), INFO_WINDOW_HEIGHT / FONT_SIZE, FONT_SIZE );
    TextWindow tp_VerWindow( TP_VER_WINDOW_WIDTH / ( FONT_SIZE / 2 ), TP_VER_WINDOW_HEIGHT / FONT_SIZE, FONT_SIZE );

    tp_InfoWindow.SetTitle("TPCal Info");
    tp_VerWindow.SetTitle("TPCal Ver");

    tp_WindowManager.CreateWindow( &tp_InfoWindow, NN_GX_DISPLAY0, INFO_WINDOW_POS_X, INFO_WINDOW_POS_Y );
    tp_WindowManager.CreateWindow( &tp_VerWindow, NN_GX_DISPLAY0, TP_VER_WINDOW_POS_X, TP_VER_WINDOW_POS_Y );

    tp_VerWindow.Printf("Ver : %s ( %s )\n",VERSION_STRING, VERSION_DATE );

    tp_WindowManager.Update();
    tp_WindowManager.DrawDisplay0();

    gfx->m_DrawFramework->SwapBuffers();


    //--------------------------------------------------------------------------
    // 下画面 キャリブレーション表示
    //--------------------------------------------------------------------------
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );

    ClearCampus();
    gfx->m_DrawFramework->SwapBuffers();


    //--------------------------------------------------------------------------
    // TouchPanel準備
    //--------------------------------------------------------------------------

    nn::hid::TouchPanelStatus RawCenter;

    nn::Result nnr;
    
    const CoordinateType center = { 160, 120 };
    
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY1 );
    gfx->m_DrawFramework->Clear();

    ClearCampus();
    DrawCenterSquare();
    gfx->m_DrawFramework->SwapBuffers();

    gfx->m_DrawFramework->WaitVsync( NN_GX_DISPLAY_BOTH );
    
#if 0
    GetRawDataForCalibration( &RawCenter, center );
    
    NN_LOG("center,x = %d\n", RawCenter.x );
    NN_LOG("center,x = %d\n", RawCenter.y );
    

    nn::drivers::cal::CTR::Calibration calibration;
    nn::drivers::cal::CTR::TouchPanelPoint tpPointLU,tpPointRD;
    nn::drivers::cal::CTR::TouchPanelCalDataCore tpCalDataCore;

    calibration.Initialize();

    nn::drivers::cal::CTR::TouchPanelCalDataCore tpRaw;
    calibration.Get( &tpRaw, nn::drivers::cal::CTR::CAL_DATA_TOUCH_PANEL );
    
    u32 dot_div_x = tpRaw.point1.dx - tpRaw.point0.dx;
    u32 raw_div_x = tpRaw.point1.raw_x - tpRaw.point0.raw_x;
    
    u32 dot_div_y = tpRaw.point1.dy - tpRaw.point0.dy;
    u32 raw_div_y = tpRaw.point1.raw_y - tpRaw.point0.raw_y;
    
    double asDot_x = (double)dot_div_x / (double)raw_div_x;
    //double center_dot_x = RawCenter.x * asDot_x;
    double center_dot_x = (((( RawCenter.x - tpRaw.point0.raw_x ) * asDot_x ) + tpRaw.point0.dx ) +
                          ((( RawCenter.x - tpRaw.point1.raw_x ) * asDot_x ) + tpRaw.point1.dx )) / 2 ;
    //double center_dot_x = ((( RawCenter.x - tpRaw.point1.raw_x ) * asDot_x ) + tpRaw.point1.dx );
    
    double asDot_y = (double)dot_div_y / (double)raw_div_y;
    //double center_dot_y = RawCenter.y * asDot_y;
    double center_dot_y = (((( RawCenter.y - tpRaw.point0.raw_y ) * asDot_y ) + tpRaw.point0.dy ) +
                          ((( RawCenter.y - tpRaw.point1.raw_y ) * asDot_y ) + tpRaw.point1.dy )) / 2 ;
    //double center_dot_y = ((( RawCenter.y - tpRaw.point1.raw_y ) * asDot_y ) + tpRaw.point1.dy );

    
    NN_LOG("dot_div_X = %d\n", dot_div_x );
    NN_LOG("raw_div_X = %d\n", raw_div_x );
    NN_LOG("asDotX = %f\n", asDot_x );
    NN_LOG("centerDotX = %f\n", center_dot_x );
    
    NN_LOG("\ndot_div_y = %d\n", dot_div_y );
    NN_LOG("raw_div_y = %d\n", raw_div_y );
    NN_LOG("asDoty = %f\n", asDot_y );
    NN_LOG("centerDoty = %f\n", center_dot_y );
    
    tp_InfoWindow.Printf("Center_X = %f\nCenter_Y = %f\n", center_dot_x - center.x, center_dot_y - center.y );
#else
    LoadCalData();
    WaitReleasePen();
    DrawTouchPoint( center );
    gfx->m_DrawFramework->WaitVsync( NN_GX_DISPLAY_BOTH );
    gfx->m_DrawFramework->SwapBuffers();
    
    const int READ_NUM = 10;
    double center_dot_x, center_dot_y;
    int nowReadNum = 0;
    while( true )
    {
        nn::os::Thread::Sleep( nn::fnd::TimeSpan::FromMilliSeconds(4));
        m_TPReader.ReadLatest( &m_TPStatus );

        if( !m_TPStatus.touch )
        {
            continue;
        }
        
        center_dot_x += m_TPStatus.x;
        center_dot_y += m_TPStatus.y;
        if( ++nowReadNum >= READ_NUM )
        {
            break;
        }
    }

    center_dot_x = center_dot_x / nowReadNum;
    center_dot_y = center_dot_y / nowReadNum;

    
    tp_InfoWindow.Printf("Center_X = %f\nCenter_Y = %f\n", center_dot_x - center.x, center_dot_y - center.y );
    

    #endif
    gfx->m_DrawFramework->SetRenderTarget( NN_GX_DISPLAY0 );
    gfx->m_DrawFramework->Clear();

    tp_WindowManager.Update();
    tp_WindowManager.DrawDisplay0();

    gfx->m_DrawFramework->SwapBuffers();
        

    // Windowの破棄
    tp_WindowManager.DestroyWindow( &tp_InfoWindow );
    tp_InfoWindow.Destroy();

    return result.m_Result;
}



} // namespace eva
} // namespace uji



