<commit_before>/*************************************************************************
 *
 *  $RCSfile: addinlis.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 10:32:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "core_pch.hxx"
#endif

#pragma hdrstop

#include <tools/debug.hxx>
#include <sfx2/objsh.hxx>

#include "addinlis.hxx"
#include "miscuno.hxx"      // SC_IMPL_SERVICE_INFO
#include "document.hxx"
#include "brdcst.hxx"
#include "unoguard.hxx"
#include "sc.hrc"

using namespace com::sun::star;

//------------------------------------------------------------------------

//SMART_UNO_IMPLEMENTATION( ScAddInListener, UsrObject );

SC_SIMPLE_SERVICE_INFO( ScAddInListener, "ScAddInListener", "stardiv.one.sheet.AddInListener" )

//------------------------------------------------------------------------

List ScAddInListener::aAllListeners;

//------------------------------------------------------------------------

//  static
ScAddInListener* ScAddInListener::CreateListener(
                        uno::Reference<sheet::XVolatileResult> xVR, ScDocument* pDoc )
{
    ScAddInListener* pNew = new ScAddInListener( xVR, pDoc );

    pNew->acquire();                                // for aAllListeners
    aAllListeners.Insert( pNew, LIST_APPEND );

    if ( xVR.is() )
        xVR->addResultListener( pNew );             // after at least 1 ref exists!

    return pNew;
}

ScAddInListener::ScAddInListener( uno::Reference<sheet::XVolatileResult> xVR, ScDocument* pDoc ) :
    xVolRes( xVR )
{
    pDocs = new ScAddInDocs( 1, 1 );
    pDocs->Insert( pDoc );
}

ScAddInListener::~ScAddInListener()
{
    delete pDocs;
}

// static
ScAddInListener* ScAddInListener::Get( uno::Reference<sheet::XVolatileResult> xVR )
{
    sheet::XVolatileResult* pComp = xVR.get();

    ULONG nCount = aAllListeners.Count();
    for (ULONG nPos=0; nPos<nCount; nPos++)
    {
        ScAddInListener* pLst = (ScAddInListener*)aAllListeners.GetObject(nPos);
        if ( pComp == (sheet::XVolatileResult*)pLst->xVolRes.get() )
            return pLst;
    }
    return NULL;        // not found
}

//! move to some container object?
// static
void ScAddInListener::RemoveDocument( ScDocument* pDocumentP )
{
    ULONG nPos = aAllListeners.Count();
    while (nPos)
    {
        //  loop backwards because elements are removed
        --nPos;
        ScAddInListener* pLst = (ScAddInListener*)aAllListeners.GetObject(nPos);
        ScAddInDocs* p = pLst->pDocs;
        USHORT nFoundPos;
        if ( p->Seek_Entry( pDocumentP, &nFoundPos ) )
        {
            p->Remove( nFoundPos );
            if ( p->Count() == 0 )
            {
                // this AddIn is no longer used
                //  dont delete, just remove the ref for the list

                aAllListeners.Remove( nPos );

                if ( pLst->xVolRes.is() )
                    pLst->xVolRes->removeResultListener( pLst );

                pLst->release();    // Ref for aAllListeners - pLst may be deleted here
            }
        }
    }
}

//------------------------------------------------------------------------

// XResultListener

void SAL_CALL ScAddInListener::modified( const ::com::sun::star::sheet::ResultEvent& aEvent )
                                throw(::com::sun::star::uno::RuntimeException)
{
    ScUnoGuard aGuard;          //! or generate a UserEvent

    aResult = aEvent.Value;     // store result

    if ( !HasListeners() )
    {
        //! remove from list and removeListener, as in RemoveDocument ???

#if 0
        //! this will crash if called before first StartListening !!!
        aAllListeners.Remove( this );
        if ( xVolRes.is() )
            xVolRes->removeResultListener( this );
        release();  // Ref for aAllListeners - this may be deleted here
        return;
#endif
    }

    //  notify document of changes

    Broadcast( ScHint( SC_HINT_DATACHANGED, ScAddress(), NULL ) );

    const ScDocument** ppDoc = (const ScDocument**) pDocs->GetData();
    USHORT nCount = pDocs->Count();
    for ( USHORT j=0; j<nCount; j++, ppDoc++ )
    {
        ScDocument* pDoc = (ScDocument*)*ppDoc;
        pDoc->TrackFormulas();
        pDoc->GetDocumentShell()->Broadcast( SfxSimpleHint( FID_DATACHANGED ) );
        pDoc->ResetChanged( ScRange(0,0,0,MAXCOL,MAXROW,MAXTAB) );
    }
}

// XEventListener

void SAL_CALL ScAddInListener::disposing( const ::com::sun::star::lang::EventObject& Source )
                                throw(::com::sun::star::uno::RuntimeException)
{
    // hold a ref so this is not deleted at removeResultListener
    uno::Reference<sheet::XResultListener> xRef( this );

    if ( xVolRes.is() )
    {
        xVolRes->removeResultListener( this );
        xVolRes = NULL;
    }
}

//------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.452); FILE MERGED 2005/09/05 15:01:56 rt 1.2.452.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: addinlis.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:38:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifdef PCH
#include "core_pch.hxx"
#endif

#pragma hdrstop

#include <tools/debug.hxx>
#include <sfx2/objsh.hxx>

#include "addinlis.hxx"
#include "miscuno.hxx"      // SC_IMPL_SERVICE_INFO
#include "document.hxx"
#include "brdcst.hxx"
#include "unoguard.hxx"
#include "sc.hrc"

using namespace com::sun::star;

//------------------------------------------------------------------------

//SMART_UNO_IMPLEMENTATION( ScAddInListener, UsrObject );

SC_SIMPLE_SERVICE_INFO( ScAddInListener, "ScAddInListener", "stardiv.one.sheet.AddInListener" )

//------------------------------------------------------------------------

List ScAddInListener::aAllListeners;

//------------------------------------------------------------------------

//  static
ScAddInListener* ScAddInListener::CreateListener(
                        uno::Reference<sheet::XVolatileResult> xVR, ScDocument* pDoc )
{
    ScAddInListener* pNew = new ScAddInListener( xVR, pDoc );

    pNew->acquire();                                // for aAllListeners
    aAllListeners.Insert( pNew, LIST_APPEND );

    if ( xVR.is() )
        xVR->addResultListener( pNew );             // after at least 1 ref exists!

    return pNew;
}

ScAddInListener::ScAddInListener( uno::Reference<sheet::XVolatileResult> xVR, ScDocument* pDoc ) :
    xVolRes( xVR )
{
    pDocs = new ScAddInDocs( 1, 1 );
    pDocs->Insert( pDoc );
}

ScAddInListener::~ScAddInListener()
{
    delete pDocs;
}

// static
ScAddInListener* ScAddInListener::Get( uno::Reference<sheet::XVolatileResult> xVR )
{
    sheet::XVolatileResult* pComp = xVR.get();

    ULONG nCount = aAllListeners.Count();
    for (ULONG nPos=0; nPos<nCount; nPos++)
    {
        ScAddInListener* pLst = (ScAddInListener*)aAllListeners.GetObject(nPos);
        if ( pComp == (sheet::XVolatileResult*)pLst->xVolRes.get() )
            return pLst;
    }
    return NULL;        // not found
}

//! move to some container object?
// static
void ScAddInListener::RemoveDocument( ScDocument* pDocumentP )
{
    ULONG nPos = aAllListeners.Count();
    while (nPos)
    {
        //  loop backwards because elements are removed
        --nPos;
        ScAddInListener* pLst = (ScAddInListener*)aAllListeners.GetObject(nPos);
        ScAddInDocs* p = pLst->pDocs;
        USHORT nFoundPos;
        if ( p->Seek_Entry( pDocumentP, &nFoundPos ) )
        {
            p->Remove( nFoundPos );
            if ( p->Count() == 0 )
            {
                // this AddIn is no longer used
                //  dont delete, just remove the ref for the list

                aAllListeners.Remove( nPos );

                if ( pLst->xVolRes.is() )
                    pLst->xVolRes->removeResultListener( pLst );

                pLst->release();    // Ref for aAllListeners - pLst may be deleted here
            }
        }
    }
}

//------------------------------------------------------------------------

// XResultListener

void SAL_CALL ScAddInListener::modified( const ::com::sun::star::sheet::ResultEvent& aEvent )
                                throw(::com::sun::star::uno::RuntimeException)
{
    ScUnoGuard aGuard;          //! or generate a UserEvent

    aResult = aEvent.Value;     // store result

    if ( !HasListeners() )
    {
        //! remove from list and removeListener, as in RemoveDocument ???

#if 0
        //! this will crash if called before first StartListening !!!
        aAllListeners.Remove( this );
        if ( xVolRes.is() )
            xVolRes->removeResultListener( this );
        release();  // Ref for aAllListeners - this may be deleted here
        return;
#endif
    }

    //  notify document of changes

    Broadcast( ScHint( SC_HINT_DATACHANGED, ScAddress(), NULL ) );

    const ScDocument** ppDoc = (const ScDocument**) pDocs->GetData();
    USHORT nCount = pDocs->Count();
    for ( USHORT j=0; j<nCount; j++, ppDoc++ )
    {
        ScDocument* pDoc = (ScDocument*)*ppDoc;
        pDoc->TrackFormulas();
        pDoc->GetDocumentShell()->Broadcast( SfxSimpleHint( FID_DATACHANGED ) );
        pDoc->ResetChanged( ScRange(0,0,0,MAXCOL,MAXROW,MAXTAB) );
    }
}

// XEventListener

void SAL_CALL ScAddInListener::disposing( const ::com::sun::star::lang::EventObject& Source )
                                throw(::com::sun::star::uno::RuntimeException)
{
    // hold a ref so this is not deleted at removeResultListener
    uno::Reference<sheet::XResultListener> xRef( this );

    if ( xVolRes.is() )
    {
        xVolRes->removeResultListener( this );
        xVolRes = NULL;
    }
}

//------------------------------------------------------------------------

<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\SimModule\Geo.h"
#include <limits>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace GeoTest
{
	TEST_CLASS(geoTest1)
	{
	public:

		TEST_METHOD(Nullity)
		{
			Point P;

			P.nullify();

			Assert::IsTrue(P.getX()==0);
			Assert::IsTrue(P.getY() == 0);
			Assert::IsTrue(P.getZ() == 0);
		}

		TEST_METHOD(CreatePoint_min200000_0_200000)
		{
			Point P(-200000,0,200000);

			Assert::IsTrue(P.getX() == -200000);
			Assert::IsTrue(P.getY() == 0);
			Assert::IsTrue(P.getZ() == 200000);
		}

		TEST_METHOD(CreatePoint_origin)
		{
			Point P(-200000, 0, 200000);

			Assert::IsTrue(P.getX() == -200000);
			Assert::IsTrue(P.getY() == 0);
			Assert::IsTrue(P.getZ() == 200000);
		}

		TEST_METHOD(CreatePoint_infRange_supRange_limitPrecision)
		{
			Point P(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(), std::numeric_limits<double>::min());

			Assert::IsTrue(P.getX() == std::numeric_limits<double>::lowest());
			Assert::IsTrue(P.getY() == std::numeric_limits<double>::max());
			Assert::IsTrue(P.getZ() == std::numeric_limits<double>::min());
		}

		TEST_METHOD(PlaceTest_infRange_supRange_limitPrecision)
		{
			Point P;

			P.place(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(), std::numeric_limits<double>::min());

			Assert::IsTrue(P.getX() == std::numeric_limits<double>::lowest());
			Assert::IsTrue(P.getY() == std::numeric_limits<double>::max());
			Assert::IsTrue(P.getZ() == std::numeric_limits<double>::min());
		}

		TEST_METHOD(AdditionTest_integers)
		{
			Point A(1000000,-2000000,0);
			Point B(1,1,1);

			A = A + B;

			Assert::IsTrue(A.getX() == 1000001);
			Assert::IsTrue(A.getY() == -1999999);
			Assert::IsTrue(A.getZ() == 1);
		}

		TEST_METHOD(AdditionTest_Doublelimits_suitableInterger)
		{
			Point A(1000000, -2000000, 0);
			Point B(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(), std::numeric_limits<double>::min());

			A = A + B;

			Assert::IsTrue(A.getX() == std::numeric_limits<double>::lowest() + 1000000.0);
			Assert::IsTrue(A.getY() == std::numeric_limits<double>::max() - 2000000.0);
			Assert::IsTrue(A.getZ() == std::numeric_limits<double>::min());
		}

		TEST_METHOD(AdditionTest_Doublelimits_integerfraction)
		{
			Point A(1000000/2, -2000001/2, 3);
			Point B(1000000/2, -2000001/2, 0);

			A = A + B;

			Assert::IsTrue(A.getX() == 1000000);
			Assert::IsTrue(A.getY() == -2000001);
			Assert::IsTrue(A.getZ() == 3);
		}

	};
}
<commit_msg>Update geoTest.cpp<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\SimModule\Geo.h"
#include <limits>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace GeoTest
{
	TEST_CLASS(geoTest1)
	{
	public:

		TEST_METHOD(Nullity)
		{
			Point P;

			P.nullify();

			Assert::IsTrue(P.getX()==0);
			Assert::IsTrue(P.getY() == 0);
			Assert::IsTrue(P.getZ() == 0);
		}

		TEST_METHOD(CreatePoint_min200000_0_200000)
		{
			Point P(-200000,0,200000);

			Assert::IsTrue(P.getX() == -200000);
			Assert::IsTrue(P.getY() == 0);
			Assert::IsTrue(P.getZ() == 200000);
		}

		TEST_METHOD(CreatePoint_origin)
		{
			Point P(-200000, 0, 200000);

			Assert::IsTrue(P.getX() == -200000);
			Assert::IsTrue(P.getY() == 0);
			Assert::IsTrue(P.getZ() == 200000);
		}

		TEST_METHOD(CreatePoint_infRange_supRange_limitPrecision)
		{
			Point P(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(), std::numeric_limits<double>::min());

			Assert::IsTrue(P.getX() == std::numeric_limits<double>::lowest());
			Assert::IsTrue(P.getY() == std::numeric_limits<double>::max());
			Assert::IsTrue(P.getZ() == std::numeric_limits<double>::min());
		}

		TEST_METHOD(PlaceTest_infRange_supRange_limitPrecision)
		{
			Point P;

			P.place(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(), std::numeric_limits<double>::min());

			Assert::IsTrue(P.getX() == std::numeric_limits<double>::lowest());
			Assert::IsTrue(P.getY() == std::numeric_limits<double>::max());
			Assert::IsTrue(P.getZ() == std::numeric_limits<double>::min());
		}

		TEST_METHOD(AdditionTest_integers)
		{
			Point A(1000000,-2000000,0);
			Point B(1,1,1);

			A = A + B;

			Assert::IsTrue(A.getX() == 1000001);
			Assert::IsTrue(A.getY() == -1999999);
			Assert::IsTrue(A.getZ() == 1);
		}

		TEST_METHOD(AdditionTest_Doublelimits_suitableInterger)
		{
			Point A(1000000, -2000000, 0);
			Point B(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(), std::numeric_limits<double>::min());

			A = A + B;

			Assert::IsTrue(A.getX() == std::numeric_limits<double>::lowest() + 1000000.0);
			Assert::IsTrue(A.getY() == std::numeric_limits<double>::max() - 2000000.0);
			Assert::IsTrue(A.getZ() == std::numeric_limits<double>::min());
		}

			TEST_METHOD(AdditionTest_integerfraction)  //assumes compiler performs integer division
		{
			Point A(1000000/2, -2000001/2, 3);
			Point B(1000000/2, -2000001/2, 0);

			A = A + B;
			Assert::IsTrue(A.getX() == 1000000);
			Assert::IsTrue(A.getY() == -2000000);
			Assert::IsTrue(A.getZ() == 3);
		}

	};
}
<|endoftext|>


<commit_before><commit_msg>For mutable axis types, clarify which tests can work on const-ref<commit_after><|endoftext|>


<commit_before>/*
======================================================
 Copyright 2016 Liang Ma

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
======================================================
*
* Author:   Liang Ma (liang-ma@polito.it)
*
*  NUM_RNGS is the number of RNG objects implemented
*  NUM_SIMGROUPS 	is the number simulation groups (it must be an even number)
*  NUM_STEPS	is the number of time steps/partitions, which is 128 for the Asian option.
*
* init_array(), a static member function of RNG is defined here due to the dimension of the array.
*
* The algorithm in sampleSIM() is optimized from the mathematical and FPGA
* implementation points of view for the Asian option.
*
*----------------------------------------------------------------------------
*/
#include "../common/blackScholes.h"

const int blackScholes::NUM_RNGS=2;
#ifdef LONG_SIMULATION
const int blackScholes::NUM_SIMS=512;
#else
const int blackScholes::NUM_SIMS=64;
#endif
const int blackScholes::NUM_SIMGROUPS=2;
const int blackScholes::NUM_STEPS=128;

blackScholes::blackScholes(stockData data):data(data)
{
}
void blackScholes::sampleSIM(RNG* mt_rng, data_t *pCall, data_t *pPut)
{
	const data_t Dt=data.timeT/data_t(NUM_STEPS);
	const data_t ratio1=expf(-data.freeRate*data.timeT);
	const data_t ratio2=(data.freeRate-data.volatility*data.volatility*0.5)*Dt;
	const data_t ratio3=Dt*data.volatility*data.volatility;
	const data_t initValue=logf(data.initPrice/NUM_STEPS/1.0f);
	data_t call=0,put=0;

	data_t sum_call[NUM_RNGS], sum_put[NUM_RNGS];
#pragma HLS ARRAY_PARTITION variable=sum_call complete dim=1
#pragma HLS ARRAY_PARTITION variable=sum_put complete dim=1

	data_t sum_call1[NUM_RNGS], sum_put1[NUM_RNGS];
#pragma HLS ARRAY_PARTITION variable=sum_call1 complete dim=1
#pragma HLS ARRAY_PARTITION variable=sum_put1 complete dim=1

	data_t acc1[NUM_RNGS][NUM_SIMS],acc[NUM_RNGS][NUM_SIMS];
#pragma HLS ARRAY_PARTITION variable=acc1 complete dim=1
#pragma HLS ARRAY_PARTITION variable=acc complete dim=1

	data_t ave1[NUM_RNGS][NUM_SIMS],ave[NUM_RNGS][NUM_SIMS];
#pragma HLS ARRAY_PARTITION variable=ave1 complete dim=1
#pragma HLS ARRAY_PARTITION variable=ave complete dim=1
	data_t num1[NUM_RNGS][NUM_SIMS],num2[NUM_RNGS][NUM_SIMS];
#pragma HLS ARRAY_PARTITION variable=num2 complete dim=1
#pragma HLS ARRAY_PARTITION variable=num1 complete dim=1

	loop_set:for(int k=0;k<NUM_SIMS;k++) {
#pragma HLS PIPELINE
		loop_set1:for(int i=0;i<NUM_RNGS;i++) {
	#pragma HLS UNROLL
			if(k==0) {
				sum_call[i]=0;
				sum_put[i]=0;
				sum_call1[i]=0;
				sum_put1[i]=0;
			}
			acc1[i][k]=initValue;
			ave1[i][k]=-data.strikePrice;
			acc[i][k]=initValue;
			ave[i][k]=-data.strikePrice;
		}
	}
	loop_main:for(int s=0;s<NUM_SIMGROUPS;s+=2) {
		loop_sim:for(int p=0;p<NUM_STEPS;p++) {
			loop_share:for(int k=0;k<NUM_SIMS;k++) {
	#pragma HLS PIPELINE
				loop_parallel:for(int i=0;i<NUM_RNGS;i++) {
					mt_rng[i].BOX_MULLER(&num1[i][k],&num2[i][k],ratio3);

					acc1[i][k]+=ratio2+num1[i][k];
					ave1[i][k]+=expf(acc1[i][k]);

					acc[i][k]+=ratio2+num2[i][k];
					ave[i][k]+=expf(acc[i][k]);
				}
			}
		}
		loop_sumShare:for(int k=0;k<NUM_SIMS;k++) {
			loop_sum:for(int i=0;i<NUM_RNGS;i++) {
#pragma HLS UNROLL
			//	std::cout<<"i="<<i<<" k="<<k<<" ave="<<ave[i][k]<<" ave1="<<ave1[i][k]<<std::endl;
				if(ave[i][k]>0)
					sum_call[i]+=ave[i][k];
				else
					sum_put[i]+=ave[i][k];
				if(ave1[i][k]>0)
					sum_call1[i]+=ave1[i][k];
				else
					sum_put1[i]+=ave1[i][k];
				acc1[i][k]=initValue;
				ave1[i][k]=-data.strikePrice;
				acc[i][k]=initValue;
				ave[i][k]=-data.strikePrice;
			}
		}
	}
	loop_sum_all:for(uint i=0;i<NUM_RNGS;i++) {
			call+=sum_call[i]+sum_call1[i];
			put+=sum_put[i]+sum_put1[i];
	}
	*pCall=ratio1*call/(NUM_SIMS*NUM_RNGS*NUM_SIMGROUPS*1.0f);
	*pPut =-ratio1*put/(NUM_SIMS*NUM_RNGS*NUM_SIMGROUPS*1.0f);
}

void blackScholes::simulation(data_t *call, data_t *put)
{

	RNG mt_rng[NUM_RNGS];
#pragma HLS ARRAY_PARTITION variable=mt_rng complete dim=1

	uint seeds[NUM_RNGS];
#pragma HLS ARRAY_PARTITION variable=seeds complete dim=1

	loop_seed:for(int i=0;i<NUM_RNGS;i++)
	{
#pragma HLS UNROLL
		seeds[i]=i;
	}
	RNG::init_array(mt_rng,seeds,NUM_RNGS);
	sampleSIM(mt_rng,call,put);

}
<commit_msg>const floating point number<commit_after>/*
======================================================
 Copyright 2016 Liang Ma

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
======================================================
*
* Author:   Liang Ma (liang-ma@polito.it)
*
*  NUM_RNGS is the number of RNG objects implemented
*  NUM_SIMGROUPS 	is the number simulation groups (it must be an even number)
*  NUM_STEPS	is the number of time steps/partitions, which is 128 for the Asian option.
*
* init_array(), a static member function of RNG is defined here due to the dimension of the array.
*
* The algorithm in sampleSIM() is optimized from the mathematical and FPGA
* implementation points of view for the Asian option.
*
*----------------------------------------------------------------------------
*/
#include "../common/blackScholes.h"

const int blackScholes::NUM_RNGS=2;
#ifdef LONG_SIMULATION
const int blackScholes::NUM_SIMS=512;
#else
const int blackScholes::NUM_SIMS=64;
#endif
const int blackScholes::NUM_SIMGROUPS=2;
const int blackScholes::NUM_STEPS=128;

blackScholes::blackScholes(stockData data):data(data)
{
}
void blackScholes::sampleSIM(RNG* mt_rng, data_t *pCall, data_t *pPut)
{
	const data_t Dt=data.timeT/data_t(NUM_STEPS);
	const data_t ratio1=expf(-data.freeRate*data.timeT);
	const data_t ratio2=(data.freeRate-data.volatility*data.volatility*0.5f)*Dt;
	const data_t ratio3=Dt*data.volatility*data.volatility;
	const data_t initValue=logf(data.initPrice/NUM_STEPS/1.0f);
	data_t call=0.0f,put=0.0f;

	data_t sum_call[NUM_RNGS], sum_put[NUM_RNGS];
#pragma HLS ARRAY_PARTITION variable=sum_call complete dim=1
#pragma HLS ARRAY_PARTITION variable=sum_put complete dim=1

	data_t sum_call1[NUM_RNGS], sum_put1[NUM_RNGS];
#pragma HLS ARRAY_PARTITION variable=sum_call1 complete dim=1
#pragma HLS ARRAY_PARTITION variable=sum_put1 complete dim=1

	data_t acc1[NUM_RNGS][NUM_SIMS],acc[NUM_RNGS][NUM_SIMS];
#pragma HLS ARRAY_PARTITION variable=acc1 complete dim=1
#pragma HLS ARRAY_PARTITION variable=acc complete dim=1

	data_t ave1[NUM_RNGS][NUM_SIMS],ave[NUM_RNGS][NUM_SIMS];
#pragma HLS ARRAY_PARTITION variable=ave1 complete dim=1
#pragma HLS ARRAY_PARTITION variable=ave complete dim=1
	data_t num1[NUM_RNGS][NUM_SIMS],num2[NUM_RNGS][NUM_SIMS];
#pragma HLS ARRAY_PARTITION variable=num2 complete dim=1
#pragma HLS ARRAY_PARTITION variable=num1 complete dim=1

	loop_set:for(int k=0;k<NUM_SIMS;k++) {
#pragma HLS PIPELINE
		loop_set1:for(int i=0;i<NUM_RNGS;i++) {
	#pragma HLS UNROLL
			if(k==0) {
				sum_call[i]=0.0f;
				sum_put[i]=0.0f;
				sum_call1[i]=0.0f;
				sum_put1[i]=0.0f;
			}
			acc1[i][k]=initValue;
			ave1[i][k]=-data.strikePrice;
			acc[i][k]=initValue;
			ave[i][k]=-data.strikePrice;
		}
	}
	loop_main:for(int s=0;s<NUM_SIMGROUPS;s+=2) {
		loop_sim:for(int p=0;p<NUM_STEPS;p++) {
			loop_share:for(int k=0;k<NUM_SIMS;k++) {
	#pragma HLS PIPELINE
				loop_parallel:for(int i=0;i<NUM_RNGS;i++) {
					mt_rng[i].BOX_MULLER(&num1[i][k],&num2[i][k],ratio3);

					acc1[i][k]+=ratio2+num1[i][k];
					ave1[i][k]+=expf(acc1[i][k]);

					acc[i][k]+=ratio2+num2[i][k];
					ave[i][k]+=expf(acc[i][k]);
				}
			}
		}
		loop_sumShare:for(int k=0;k<NUM_SIMS;k++) {
			loop_sum:for(int i=0;i<NUM_RNGS;i++) {
#pragma HLS UNROLL
			//	std::cout<<"i="<<i<<" k="<<k<<" ave="<<ave[i][k]<<" ave1="<<ave1[i][k]<<std::endl;
				if(ave[i][k]>0.0f)
					sum_call[i]+=ave[i][k];
				else
					sum_put[i]+=ave[i][k];
				if(ave1[i][k]>0.0f)
					sum_call1[i]+=ave1[i][k];
				else
					sum_put1[i]+=ave1[i][k];
				acc1[i][k]=initValue;
				ave1[i][k]=-data.strikePrice;
				acc[i][k]=initValue;
				ave[i][k]=-data.strikePrice;
			}
		}
	}
	loop_sum_all:for(uint i=0;i<NUM_RNGS;i++) {
			call+=sum_call[i]+sum_call1[i];
			put+=sum_put[i]+sum_put1[i];
	}
	*pCall=ratio1*call/(NUM_SIMS*NUM_RNGS*NUM_SIMGROUPS*1.0f);
	*pPut =-ratio1*put/(NUM_SIMS*NUM_RNGS*NUM_SIMGROUPS*1.0f);
}

void blackScholes::simulation(data_t *call, data_t *put)
{

	RNG mt_rng[NUM_RNGS];
#pragma HLS ARRAY_PARTITION variable=mt_rng complete dim=1

	uint seeds[NUM_RNGS];
#pragma HLS ARRAY_PARTITION variable=seeds complete dim=1

	loop_seed:for(int i=0;i<NUM_RNGS;i++)
	{
#pragma HLS UNROLL
		seeds[i]=i;
	}
	RNG::init_array(mt_rng,seeds,NUM_RNGS);
	sampleSIM(mt_rng,call,put);

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ViewShellManager.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-12-16 10:12:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_VIEW_SHELL_MANAGER_HXX
#define SD_VIEW_SHELL_MANAGER_HXX

#include "ShellFactory.hxx"

#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#include <memory>
#include <vector>

class SfxShell;
class VclWindowEvent;

namespace sd {

class ViewShell;
class ViewShellBase;
class ViewShellCache;

/** The sub-shell manager has the responsibility to maintain the sub shells
    stacked on a ViewShellBase object.  They form a two level hierarchy.  On
    the first level there are the view shells which are managed directly by
    this class.  On the second level there are the object bars wrapped into
    an SfxShell.  They are managed by ObjectBarManager objects, one for each
    view shell.

View shell management consists of maintaining the correct order of
    all stacked shells.  Those that belong to the view shell that currently
    has the focus have to be top-most to be considered first by the slot call
    dispatcher.  Object bars have to be on top of their view shells so that
    the associated functions are called first.

This class uses pointers to the ::sd::ViewShell class instead of its
    ::SfxShell base class because it needs access to the object bar manager
    of the ViewShell class so that that manager can be instructed to
    activate or deactivate its object bars.

*/
class ViewShellManager
{
public:
    typedef ShellFactory<ViewShell> ViewShellFactory;

    ViewShellManager (ViewShellBase& rBase);

    /** Before the destructor is called the method Shutdown() has to have
        been called.
    */
    ~ViewShellManager (void);

    /** Tell a ViewShellManager object to prepare to be deleted, i.e. to
        destroy all of its resources.
    */
    void Shutdown (void);

    /** Register the default factory that is called to create a new instance
        of a shell for a given id when there is no factory that has been
        registered specially for that id.
        @param pFactory
            The factory object that is called to create a new shell instance.
    */
    void RegisterDefaultFactory (::std::auto_ptr<ViewShellFactory> pFactory);

    /** Register a factory that is called to create a shell for the
        specified id.  This takes precedence over the default factory.
    */
    void RegisterFactory (
        ShellId nId,
        ::std::auto_ptr<ViewShellFactory> pFactory);

    /** Create a new (or possibly recycle an existing) instance of a view
        shell that is specified by the given id.  When called multiple times
        with the same id then multiple instances of the associated view
        shell are created.  Use the returned pointer to distinguish between
        these.
        @param nId
            The id of the shell to activate.
        @return
            A pointer to the activated shell is returned.  Use this pointer
            to identify the shell in other method calls.  When an activation
            is not possible then NULL is returned.
    */
    ViewShell* ActivateViewShell (
        ShellId nId,
        ::Window* pParentWindow,
        FrameView* pFrameView);

    /** Deactivate the specified shell, i.e. take it and all of its
        object bars from the shell stack.
        @param pShell
            The shell to deactivate.
    */
    void DeactivateViewShell (const ViewShell* pShell);

    /** Call this method when a 'secondary' shell is moved to or from the
        stack, e.g. an object bar.  As a result a pending
        TakeShellsFromStack() is executed and at the next UnlockUpdate() to
        lock level 0 the shells are asked about their secondary shells to
        push on the shell stack.
    */
    void InvalidateShellStack (void);

    /** Move the specified view shell to the top most position on the stack
        of view shells in relation to the other view shells.  After this the
        only shells that are higher on the stack are its object bars.

        Call this method after a focus change to bring a view mode view
        shell and ist associated tool bar shells to the top of the
        stack.

        The mbKeepMainViewShellOnTop flag is not obeyed.

        @param nId
            The id of the shell to move to the top.
    */
    void MoveToTop (const ViewShell* pShell);

    /** Return the first, i.e. top most, view shell that has been activated
        under the given id.
        @param nId
            The id of the shell for which to return a pointer.
        @return
            When the specified shell is currently not active then NULL is
            returned.
    */
    ViewShell* GetShell (ShellId nId);

    /** Return the id of the given shell.
    */
    ShellId GetShellId (const ViewShell* pShell);

    /** Prevent updates of the shell stack.  While the sub shell manager is
        locked it will update its internal data structures but not alter the
        shell stack.  Use this method when there are several modifications
        to the shell stack to prevent multiple rebuilds of the shell stack
        and resulting broadcasts.
    */
    void LockUpdate (void);

    /** Allow updates of the shell stack.  This method has to be called the
        same number of times as LockUpdate() to really allow a rebuild of
        the shell stack.
        */
    void UnlockUpdate (void);

    /** Return the ViewShellBase for which objects of this class manage the
        stacked view shells.
    */
    ViewShellBase& GetViewShellBase (void) const;

    /** Deactivate the view shell manager so that it pretty much ignores all
        subsequent calls.  Use this when the owner of the view shell manager
        is about being destroyed but the view shell manager itself can not
        yet be deleted.
    */
    void ShutDown (void);

    /** Use one of the registered factories to create the requested view
        shell.
        @return
            When a view shell of the requested type can not be created,
            e.g. because no factory for it has been registered, NULL is
            returned.
            The returned view shell can be destroyed by the caller.
    */
    ViewShell* CreateViewShell (
        ShellId nShellId,
        ::Window* pParentWindow,
        FrameView* pFrameView);

    /** Use this class to safely lock updates of the view shell stack.
    */
    class UpdateLocker
    {
    public:
        explicit UpdateLocker (ViewShellManager& rManager);
        ~UpdateLocker (void);
    private:
        ViewShellManager&mrManager;
    };

private:
    ViewShellBase& mrBase;

    ::std::auto_ptr<ViewShellFactory> mpDefaultFactory;
    class SpecializedFactoryList;
    ::std::auto_ptr<SpecializedFactoryList> mpSpecializedFactories;
    class ActiveShellList;
    ::std::auto_ptr<ActiveShellList> mpActiveViewShells;
    ::std::auto_ptr<ViewShellCache> mpCache;

    int mnUpdateLockCount;

    /** When this flag is set then the main view shell is always kept at the
        top of the shell stack.
    */
    bool mbKeepMainViewShellOnTop;

    /** This flag is <TRUE/> until ShutDown() is called.  When it its value
        is <FALSE/> then the internal structures may be updated by
        subsequent method calls but no outside calls take place anymore.
    */
    bool mbIsValid;

    /** When this flag is set to <TRUE/> then before the next activation or
        deactivation of a shell the shell stack is cleared.  It is set to
        <TRUE/> in LockUpdate().  This avoids unnecessary modifications of
        the shell stack when no (de-)activation takes place in Lock/Unlock
        blocks.
    */
    bool mbTakeShellsFromStackPending;

    /** The PushShellsOnStack() method can be called recursively.  This flag
        is used to communicate between different levels of invocation: if
        the stack has been updated in an inner call the outer call can (has
        to) stop and return immediately.
    */
    bool mbShellStackIsUpToDate;

    void GatherActiveShells (::std::vector<SfxShell*>& aShellsList);

    void TakeShellsFromStack (void);

    /** This method rebuilds the stack of shells that are stacked upon the
        view shell base.
    */
    void PushShellsOnStack (void);

    /** Called from ActivateViewShell() and DeactivateViewShell() this
        method calls TakeShellsFromStack() if necessary.  It is necessary
        when mbTakeShellsFromStackPending is <TRUE/>.
    */
    void PrepareStackModification (void);

    DECL_LINK(WindowEventHandler, VclWindowEvent*);
};

} // end of namespace sd

#endif

<commit_msg>INTEGRATION: CWS impress20 (1.3.76); FILE MERGED 2004/12/07 17:09:17 af 1.3.76.2: RESYNC: (1.3-1.4); FILE MERGED 2004/11/23 17:52:52 af 1.3.76.1: #118543# Introduction of inner Implementation class.  Major modification of how the internal and the SFX shell stacks are synchronized.<commit_after>/*************************************************************************
 *
 *  $RCSfile: ViewShellManager.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2005-01-28 16:23:36 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_VIEW_SHELL_MANAGER_HXX
#define SD_VIEW_SHELL_MANAGER_HXX

#include "ShellFactory.hxx"

#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#include <memory>
#include <vector>

class SfxShell;

namespace sd {

class ViewShell;
class ViewShellBase;

/** The sub-shell manager has the responsibility to maintain the sub shells
    stacked on a ViewShellBase object.  They form a two level hierarchy.  On
    the first level there are the view shells which are managed directly by
    this class.  On the second level there are the object bars wrapped into
    an SfxShell.  They are managed by ObjectBarManager objects, one for each
    view shell.

View shell management consists of maintaining the correct order of
    all stacked shells.  Those that belong to the view shell that currently
    has the focus have to be top-most to be considered first by the slot call
    dispatcher.  Object bars have to be on top of their view shells so that
    the associated functions are called first.

This class uses pointers to the ::sd::ViewShell class instead of its
    ::SfxShell base class because it needs access to the object bar manager
    of the ViewShell class so that that manager can be instructed to
    activate or deactivate its object bars.

*/
class ViewShellManager
{
public:
    typedef ShellFactory<ViewShell> ViewShellFactory;

    ViewShellManager (ViewShellBase& rBase);

    /** Before the destructor is called the method Shutdown() has to have
        been called.
    */
    ~ViewShellManager (void);

    /** Tell a ViewShellManager object to prepare to be deleted, i.e. to
        destroy all of its resources and to ignore all following calls.
        Use this when the owner of the view shell manager is about being
        destroyed but the view shell manager itself can not yet be deleted.
    */
    void Shutdown (void);

    /** Register the default factory that is called to create a new instance
        of a shell for a given id when there is no factory that has been
        registered specially for that id.
        @param pFactory
            The factory object that is called to create a new shell instance.
    */
    void RegisterDefaultFactory (::std::auto_ptr<ViewShellFactory> pFactory);

    /** Register a factory that is called to create a shell for the
        specified id.  This takes precedence over the default factory.
    */
    void RegisterFactory (
        ShellId nId,
        ::std::auto_ptr<ViewShellFactory> pFactory);

    /** Create a new (or possibly recycle an existing) instance of a view
        shell that is specified by the given id.  When called multiple times
        with the same id then multiple instances of the associated view
        shell are created.  Use the returned pointer to distinguish between
        these.
        @param nId
            The id of the shell to activate.
        @return
            A pointer to the activated shell is returned.  Use this pointer
            to identify the shell in other method calls.  When an activation
            is not possible then NULL is returned.
    */
    ViewShell* ActivateViewShell (
        ShellId nId,
        ::Window* pParentWindow,
        FrameView* pFrameView);

    /** Deactivate the specified shell, i.e. take it and all of its
        object bars from the shell stack.
        @param pShell
            The shell to deactivate.
    */
    void DeactivateViewShell (const ViewShell* pShell);

    /** Call this method to when a 'secondary' shell is moved to or from the
        stack, e.g. an object bar.  As a result a pending
        TakeShellsFromStack() is executed and at the next UnlockUpdate() to
        lock level 0 the shells are asked about their secondary shells to
        push on the shell stack.
    */
    void InvalidateShellStack (const SfxShell* pShell);

    /** Move the specified view shell to the top most position on the stack
        of view shells in relation to the other view shells.  After this the
        only shells that are higher on the stack are its object bars.

        Call this method after a focus change to bring a view mode view
        shell and ist associated tool bar shells to the top of the
        stack.

        The mbKeepMainViewShellOnTop flag is not obeyed.

        @param nId
            The id of the shell to move to the top.
    */
    void MoveToTop (const ViewShell* pShell);

    /** Return the first, i.e. top most, view shell that has been activated
        under the given id.
        @param nId
            The id of the shell for which to return a pointer.
        @return
            When the specified shell is currently not active then NULL is
            returned.
    */
    ViewShell* GetShell (ShellId nId);

    /** Return the id of the given shell.
    */
    ShellId GetShellId (const ViewShell* pShell);

    /** Return the ViewShellBase for which objects of this class manage the
        stacked view shells.
    */
    ViewShellBase& GetViewShellBase (void) const;

    /** Use one of the registered factories to create the requested view
        shell.
        @return
            When a view shell of the requested type can not be created,
            e.g. because no factory for it has been registered, NULL is
            returned.
            The returned view shell can be destroyed by the caller.
    */
    ViewShell* CreateViewShell (
        ShellId nShellId,
        ::Window* pParentWindow,
        FrameView* pFrameView);

    class Implementation;

    /** Use this class to safely lock updates of the view shell stack.
    */
    class UpdateLock
    {
    public:
        explicit UpdateLock (ViewShellManager& rManager);
        explicit UpdateLock (Implementation& rManagerImplementation);
        ~UpdateLock (void);
    private:
        ViewShellManager::Implementation& mrManagerImplementation;
    };
    friend class UpdateLock;

private:
    ::std::auto_ptr<ViewShellManager::Implementation> mpImpl;
    bool mbValid;
};

} // end of namespace sd

#endif

<|endoftext|>


<commit_before>#include "BlackBox.h"
#include <blackbox/common.h>
#include <bblib/utils_paths.h>
#include "utils_window.h"

namespace bb {

	void BlackBox::Quit (uint32_t arg)
	{
		m_quit = true;
	}

	void BlackBox::LoadPlugin (bbstring const & plugin_id)
	{
		m_plugins.LoadPlugin(plugin_id);
	}
	void BlackBox::UnloadPlugin (bbstring const & plugin_id)
	{
		m_plugins.UnloadPlugin(plugin_id);
	}
	bool BlackBox::IsPluginLoaded (bbstring const & plugin_id) const
	{
		return m_plugins.IsPluginLoaded(plugin_id);
	}

	void BlackBox::CreateWidgetFromId (bbstring const & widget_id)
	{
		m_gfx->MkWidgetFromId(widget_id.c_str());
	}

	void BlackBox::MoveOrDestroyOnToggle (bool is_new, bb::GuiWidget * w)
	{
		POINT p;
		if (::GetCursorPos(&p))
		{
			RECT r;
			::GetWindowRect(w->m_gfxWindow->m_hwnd, &r);
			if (::PtInRect(&r, p))
			{
				if (!is_new)
					m_gfx->DestroyWindow(w->GetId().c_str());
			}
			else
			{
				w->MoveWindow(p.x, p.y);
				m_tasks.Focus(w->m_gfxWindow->m_hwnd);
				w->Show(true);
			}
		}
	}

	void BlackBox::ToggleMenu (std::shared_ptr<bb::MenuConfig> menu_cfg)
	{
		bool new_menu = false;
		GuiWidget * w = m_gfx->FindWidget(menu_cfg->m_id.c_str());
		if (!w)
		{
			w = m_gfx->MkWidgetFromConfig(*menu_cfg);
			new_menu = true;
		}

		MoveOrDestroyOnToggle(new_menu, w);
	}

	BOOL CALLBACK enumWindowsProc (HWND hwnd, LPARAM lParam)
	{
		wchar_t buffer[128];
		int const written = ::GetClassName(hwnd, buffer, 128);
		if (written && wcscmp(buffer, L"SHELLDLL_DefView") == 0)
		{
			wchar_t buffer2[128];
			int const written2 = ::GetWindowText(hwnd, buffer2, 128);
			if (written2 == 0)
			{
				*(HWND*)lParam = hwnd;
				return FALSE;
			}
		}
		return TRUE;
	}
	HWND getDesktopParentHandle ()
	{
		HWND hWnd = NULL;
		EnumChildWindows(::GetDesktopWindow(), enumWindowsProc, (LPARAM)&hWnd);
		return hWnd;
	}

	HWND getDesktopHandle ()
	{
		HWND hShellWnd = GetShellWindow();
		HWND hDefView = FindWindowEx(hShellWnd, NULL, _T("SHELLDLL_DefView"), NULL);
		HWND folderView = FindWindowEx(hDefView, NULL, _T("SysListView32"), NULL);
		return folderView;
	}

	bool isDesktopHandle (HWND hwnd)
	{
		// classic method
		if (HWND d = getDesktopHandle())
		{
			return hwnd == d;
		}

		// workaround if the above does not work (can hapen when progman crashes)
		HWND const hDefView = getDesktopParentHandle(); //FindWindowEx(shell_wnd, nullptr, L"SHELLDLL_DefView", nullptr);
		HWND const folderView = FindWindowEx(hDefView, NULL, L"SysListView32", L"FolderView");
		if (hwnd == folderView)
			return true;

		HWND const desktop_window = ::GetDesktopWindow();
		return hwnd == desktop_window;
	}

	void BlackBox::ToggleMenu (bbstring const & widget_name)
	{
		auto destroyWindgetIfInMargin = [this, &widget_name] (GuiWidget * & w, int margin)
		{
			RECT r;
			::GetWindowRect(w->m_gfxWindow->m_hwnd, &r);
			r.left += margin;
			r.top += margin;
			r.right -= margin;
			r.bottom -= margin;
			if (::PtInRect(&r, p))
			{
				m_gfx->DestroyWindow(widget_name.c_str());
				w = nullptr;
		}
		};

		POINT p;
		if (::GetCursorPos(&p))
		{
			GuiWidget * w = m_gfx->FindWidget(widget_name.c_str());
			HWND const clicked_window = ::WindowFromPoint(p);
			if (isDesktopHandle(clicked_window))
			{
				if (!w)
				{
					w = m_gfx->MkWidgetFromId(widget_name.c_str());
			}
			else
			{
					destroyWindgetIfInMargin(w, -5);
				}
			}
			else if (w && clicked_window == w->m_gfxWindow->m_hwnd)
			{
				destroyWindgetIfInMargin(w, 5);
			}
			else if (w && clicked_window != w->m_gfxWindow->m_hwnd)
			{
				destroyWindgetIfInMargin(w, -5);
			}

			if (w)
			{
				w->MoveWindow(p.x, p.y);
				m_tasks.Focus(w->m_gfxWindow->m_hwnd);
				setOnTop(w->m_gfxWindow->m_hwnd);
				w->Show(true);
			}
		}
	}

	void BlackBox::MakeSticky (HWND hwnd)
	{
	}

	void BlackBox::RemoveSticky (HWND hwnd)
	{
	}

	HWND BlackBox::GetHwnd ()
	{
		return m_hwnd;
	}

	void * BlackBox::GetSettingPtr (int sn_index)
	{
		if (m_style)
		{
			void * const ptr = m_style->GetStyleMemberPtr(sn_index);
			return ptr;
		}
		else
		{
			return m_defaultStyle->GetStyleMemberPtr(sn_index);
		}
	}

	bool BlackBox::GetConfigDir (wchar_t * dir, size_t dir_sz) const
	{
// 		wchar_t name[MAX_PATH];
// 		if (!m_cmdLine.ConfigDir().empty())
// 		{
// 			codecvt_utf8_utf16(m_cmdLine.ConfigDir(), dir, dir_sz);
// 			return true;
// 		}
// 		else if (getExeName(dir, MAX_PATH))
// 		{
// 			return true;
// 		}
		return false;
	}

	bool BlackBox::WorkSpacesSetCurrentVertexId (bbstring const & vertex_id)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "WorkSpacesSetCurrentVertexId: %ws", vertex_id.c_str());
		if (bbstring const * curr_vtx_id = m_wspaces.GetCurrentVertexId())
		{
			bbstring const curr_ws = *curr_vtx_id;
			if (m_wspaces.CanSetCurrentVertexId(vertex_id))
			{
				m_wspaces.SetCurrentVertexId(vertex_id);
				m_tasks.SwitchWorkSpace(curr_ws, vertex_id, false);
			}
		}
		return false;
	}

	bool BlackBox::WorkSpacesSwitchVertexViaEdge (bbstring const & edge_property)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "WorkSpacesSwitchVertexViaEdge edge=%ws", edge_property.c_str());
		bbstring new_vertex_id;
		if (FindTargetVertexViaEdge(edge_property, new_vertex_id))
			if (bbstring const * curr_vtx_id = m_wspaces.GetCurrentVertexId())
			{
				bbstring const curr_ws = *curr_vtx_id;
				m_wspaces.SetCurrentVertexId(new_vertex_id);
				m_tasks.SwitchWorkSpace(curr_ws, new_vertex_id, false);
				return true;
			}
		return false;
	}

	void BlackBox::MaximizeTopWindow (bool vertical)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "MaximizeTopWindow vertical=%i", vertical);
		if (HWND hwnd = FindTopLevelWindow())
			maximizeWindow(hwnd, vertical);
	}

	void BlackBox::SetTaskManIgnored (bbstring const & op)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "SetTaskManIgnored op=%ws", op.c_str());
		if (HWND hwnd = FindTopLevelWindow())
		{
			if (op == L"true")
				m_tasks.SetTaskManIgnored(hwnd);
			else if (op == L"false")
				m_tasks.UnsetTaskManIgnored(hwnd);
			else
			{
				m_tasks.ToggleTaskManIgnored(hwnd);
			}
		}
	}

	bool BlackBox::FindTargetVertexViaEdge (bbstring const & edge_property, bbstring & dst_vertex_id) const
	{
		if (m_wspaces.CanSwitchVertexViaEdge(edge_property, dst_vertex_id))
			return true;
		return false;
	}
	bool BlackBox::MoveWindowToVertex (HWND hwnd, bbstring const & vertex_id)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "MoveWindowToVertex edge=%ws", vertex_id.c_str());
		if (bbstring const * curr_vtx_id = m_wspaces.GetCurrentVertexId())
		{
			return m_tasks.MoveWindowToVertex(hwnd, vertex_id);
		}
		return false;
	}
	bool BlackBox::MoveTopWindowToVertexViaEdge (bbstring const & edge_property)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "MoveTopWindowToVertexViaEdge edge=%ws", edge_property.c_str());
		bbstring new_vertex_id;
		if (HWND hwnd = FindTopLevelWindow())
			if (FindTargetVertexViaEdge(edge_property, new_vertex_id))
				return m_tasks.MoveWindowToVertex(hwnd, new_vertex_id);
		return false;
	}

}

<commit_msg>* crlf<commit_after>#include "BlackBox.h"
#include <blackbox/common.h>
#include <bblib/utils_paths.h>
#include "utils_window.h"

namespace bb {

	void BlackBox::Quit (uint32_t arg)
	{
		m_quit = true;
	}

	void BlackBox::LoadPlugin (bbstring const & plugin_id)
	{
		m_plugins.LoadPlugin(plugin_id);
	}
	void BlackBox::UnloadPlugin (bbstring const & plugin_id)
	{
		m_plugins.UnloadPlugin(plugin_id);
	}
	bool BlackBox::IsPluginLoaded (bbstring const & plugin_id) const
	{
		return m_plugins.IsPluginLoaded(plugin_id);
	}

	void BlackBox::CreateWidgetFromId (bbstring const & widget_id)
	{
		m_gfx->MkWidgetFromId(widget_id.c_str());
	}

	void BlackBox::MoveOrDestroyOnToggle (bool is_new, bb::GuiWidget * w)
	{
		POINT p;
		if (::GetCursorPos(&p))
		{
			RECT r;
			::GetWindowRect(w->m_gfxWindow->m_hwnd, &r);
			if (::PtInRect(&r, p))
			{
				if (!is_new)
					m_gfx->DestroyWindow(w->GetId().c_str());
			}
			else
			{
				w->MoveWindow(p.x, p.y);
				m_tasks.Focus(w->m_gfxWindow->m_hwnd);
				w->Show(true);
			}
		}
	}

	void BlackBox::ToggleMenu (std::shared_ptr<bb::MenuConfig> menu_cfg)
	{
		bool new_menu = false;
		GuiWidget * w = m_gfx->FindWidget(menu_cfg->m_id.c_str());
		if (!w)
		{
			w = m_gfx->MkWidgetFromConfig(*menu_cfg);
			new_menu = true;
		}

		MoveOrDestroyOnToggle(new_menu, w);
	}

	BOOL CALLBACK enumWindowsProc (HWND hwnd, LPARAM lParam)
	{
		wchar_t buffer[128];
		int const written = ::GetClassName(hwnd, buffer, 128);
		if (written && wcscmp(buffer, L"SHELLDLL_DefView") == 0)
		{
			wchar_t buffer2[128];
			int const written2 = ::GetWindowText(hwnd, buffer2, 128);
			if (written2 == 0)
			{
				*(HWND*)lParam = hwnd;
				return FALSE;
			}
		}
		return TRUE;
	}
	HWND getDesktopParentHandle ()
	{
		HWND hWnd = NULL;
		EnumChildWindows(::GetDesktopWindow(), enumWindowsProc, (LPARAM)&hWnd);
		return hWnd;
	}

	HWND getDesktopHandle ()
	{
		HWND hShellWnd = GetShellWindow();
		HWND hDefView = FindWindowEx(hShellWnd, NULL, _T("SHELLDLL_DefView"), NULL);
		HWND folderView = FindWindowEx(hDefView, NULL, _T("SysListView32"), NULL);
		return folderView;
	}

	bool isDesktopHandle (HWND hwnd)
	{
		// classic method
		if (HWND d = getDesktopHandle())
		{
			return hwnd == d;
		}

		// workaround if the above does not work (can hapen when progman crashes)
		HWND const hDefView = getDesktopParentHandle(); //FindWindowEx(shell_wnd, nullptr, L"SHELLDLL_DefView", nullptr);
		HWND const folderView = FindWindowEx(hDefView, NULL, L"SysListView32", L"FolderView");
		if (hwnd == folderView)
			return true;

		HWND const desktop_window = ::GetDesktopWindow();
		return hwnd == desktop_window;
	}

	void BlackBox::ToggleMenu (bbstring const & widget_name)
	{
		auto destroyWindgetIfInMargin = [this, &widget_name] (GuiWidget * & w, int margin)
		{
			RECT r;
			::GetWindowRect(w->m_gfxWindow->m_hwnd, &r);
			r.left += margin;
			r.top += margin;
			r.right -= margin;
			r.bottom -= margin;
			if (::PtInRect(&r, p))
			{
				m_gfx->DestroyWindow(widget_name.c_str());
				w = nullptr;
		}
		};

		POINT p;
		if (::GetCursorPos(&p))
		{
			GuiWidget * w = m_gfx->FindWidget(widget_name.c_str());
			HWND const clicked_window = ::WindowFromPoint(p);
			if (isDesktopHandle(clicked_window))
			{
				if (!w)
				{
					w = m_gfx->MkWidgetFromId(widget_name.c_str());
			}
			else
			{
					destroyWindgetIfInMargin(w, -5);
				}
			}
			else if (w && clicked_window == w->m_gfxWindow->m_hwnd)
			{
				destroyWindgetIfInMargin(w, 5);
			}
			else if (w && clicked_window != w->m_gfxWindow->m_hwnd)
			{
				destroyWindgetIfInMargin(w, -5);
			}

			if (w)
			{
				w->MoveWindow(p.x, p.y);
				m_tasks.Focus(w->m_gfxWindow->m_hwnd);
				setOnTop(w->m_gfxWindow->m_hwnd);
				w->Show(true);
			}
		}
	}

	void BlackBox::MakeSticky (HWND hwnd)
	{
	}

	void BlackBox::RemoveSticky (HWND hwnd)
	{
	}

	HWND BlackBox::GetHwnd ()
	{
		return m_hwnd;
	}

	void * BlackBox::GetSettingPtr (int sn_index)
	{
		if (m_style)
		{
			void * const ptr = m_style->GetStyleMemberPtr(sn_index);
			return ptr;
		}
		else
		{
			return m_defaultStyle->GetStyleMemberPtr(sn_index);
		}
	}

	bool BlackBox::GetConfigDir (wchar_t * dir, size_t dir_sz) const
	{
// 		wchar_t name[MAX_PATH];
// 		if (!m_cmdLine.ConfigDir().empty())
// 		{
// 			codecvt_utf8_utf16(m_cmdLine.ConfigDir(), dir, dir_sz);
// 			return true;
// 		}
// 		else if (getExeName(dir, MAX_PATH))
// 		{
// 			return true;
// 		}
		return false;
	}

	bool BlackBox::WorkSpacesSetCurrentVertexId (bbstring const & vertex_id)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "WorkSpacesSetCurrentVertexId: %ws", vertex_id.c_str());
		if (bbstring const * curr_vtx_id = m_wspaces.GetCurrentVertexId())
		{
			bbstring const curr_ws = *curr_vtx_id;
			if (m_wspaces.CanSetCurrentVertexId(vertex_id))
			{
				m_wspaces.SetCurrentVertexId(vertex_id);
				m_tasks.SwitchWorkSpace(curr_ws, vertex_id, false);
			}
		}
		return false;
	}

	bool BlackBox::WorkSpacesSwitchVertexViaEdge (bbstring const & edge_property)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "WorkSpacesSwitchVertexViaEdge edge=%ws", edge_property.c_str());
		bbstring new_vertex_id;
		if (FindTargetVertexViaEdge(edge_property, new_vertex_id))
			if (bbstring const * curr_vtx_id = m_wspaces.GetCurrentVertexId())
			{
				bbstring const curr_ws = *curr_vtx_id;
				m_wspaces.SetCurrentVertexId(new_vertex_id);
				m_tasks.SwitchWorkSpace(curr_ws, new_vertex_id, false);
				return true;
			}
		return false;
	}

	void BlackBox::MaximizeTopWindow (bool vertical)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "MaximizeTopWindow vertical=%i", vertical);
		if (HWND hwnd = FindTopLevelWindow())
			maximizeWindow(hwnd, vertical);
	}

	void BlackBox::SetTaskManIgnored (bbstring const & op)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "SetTaskManIgnored op=%ws", op.c_str());
		if (HWND hwnd = FindTopLevelWindow())
		{
			if (op == L"true")
				m_tasks.SetTaskManIgnored(hwnd);
			else if (op == L"false")
				m_tasks.UnsetTaskManIgnored(hwnd);
			else
			{
				m_tasks.ToggleTaskManIgnored(hwnd);
			}
		}
	}

	bool BlackBox::FindTargetVertexViaEdge (bbstring const & edge_property, bbstring & dst_vertex_id) const
	{
		if (m_wspaces.CanSwitchVertexViaEdge(edge_property, dst_vertex_id))
			return true;
		return false;
	}
	bool BlackBox::MoveWindowToVertex (HWND hwnd, bbstring const & vertex_id)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "MoveWindowToVertex edge=%ws", vertex_id.c_str());
		if (bbstring const * curr_vtx_id = m_wspaces.GetCurrentVertexId())
		{
			return m_tasks.MoveWindowToVertex(hwnd, vertex_id);
		}
		return false;
	}
	bool BlackBox::MoveTopWindowToVertexViaEdge (bbstring const & edge_property)
	{
		TRACE_MSG(LL_DEBUG, CTX_BB | CTX_WSPACE | CTX_BIND, "MoveTopWindowToVertexViaEdge edge=%ws", edge_property.c_str());
		bbstring new_vertex_id;
		if (HWND hwnd = FindTopLevelWindow())
			if (FindTargetVertexViaEdge(edge_property, new_vertex_id))
				return m_tasks.MoveWindowToVertex(hwnd, new_vertex_id);
		return false;
	}

}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014, Julien Bernard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
#include <cstdio>

#include <game/base/Log.h>
#include <game/graphics/Group.h>

#include "local/Ball.h"
#include "local/Ground.h"
#include "local/Racket.h"
#include "local/Rules.h"

#include "config.h"

static sf::FloatRect computeViewport(unsigned width, unsigned height) {
  float w = static_cast<float>(width);
  float h = static_cast<float>(height);

  float r = w / h * Ground::HEIGHT / Ground::WIDTH;

  sf::FloatRect vp;

  if (width < 2 * height) {
    vp.left = 0.0f;
    vp.width = 1.0;

    vp.top = (1 - r) / 2;
    vp.height = r;
  } else {
    vp.top = 0.0f;
    vp.height = 1.0f;

    vp.left = (1 - 1 / r) / 2;
    vp.width = 1 / r;
  }

  return vp;
}

int main() {
  std::printf("Pong (version " GAME_VERSION ")\n");

  // initialize

  static constexpr unsigned INITIAL_WIDTH = 1024;
  static constexpr unsigned INITIAL_HEIGHT = 768;

  sf::RenderWindow window(sf::VideoMode(INITIAL_WIDTH, INITIAL_HEIGHT), "Pong (version " GAME_VERSION ")");
  window.setKeyRepeatEnabled(false);

  game::Log::setLevel(game::Log::PHYSICS, game::Log::DEBUG);

  // load resources

  // add entities
  game::Group group;
  Ground ground;
  Racket lft(Racket::Location::LEFT);
  Racket rgt(Racket::Location::RIGHT);
  Ball ball;

  Rules rules(lft, rgt, ball);

  group.addEntity(ground).addEntity(ball).addEntity(lft).addEntity(rgt).addEntity(rules);

  // main loop
  sf::View view;
  view.setCenter({ 0.0f, 0.0f });
  view.setSize({ 200.0f, 100.0f });

  view.setViewport(computeViewport(INITIAL_WIDTH, INITIAL_HEIGHT));

  sf::Clock clock;

  while (window.isOpen()) {
    // input
    sf::Event event;

    while (window.pollEvent(event)) {
      if (event.type == sf::Event::Closed) {
        window.close();
      } else if (event.type == sf::Event::KeyPressed) {

        switch (event.key.code) {
          case sf::Keyboard::Escape:
            window.close();
            break;

          case sf::Keyboard::S:
            lft.move(Racket::Move::UP);
            break;

          case sf::Keyboard::X:
            lft.move(Racket::Move::DOWN);
            break;

          case sf::Keyboard::Up:
            rgt.move(Racket::Move::UP);
            break;

          case sf::Keyboard::Down:
            rgt.move(Racket::Move::DOWN);
            break;

          default:
            break;
        }

      } else if(event.type == sf::Event::KeyReleased) {

        switch (event.key.code) {
          case sf::Keyboard::S:
            lft.move(Racket::Move::STOP);
            break;

          case sf::Keyboard::X:
            lft.move(Racket::Move::STOP);
            break;

          case sf::Keyboard::Up:
            rgt.move(Racket::Move::STOP);
            break;

          case sf::Keyboard::Down:
            rgt.move(Racket::Move::STOP);
            break;

          default:
            break;
        }

      } else if (event.type == sf::Event::Resized) {
        view.setViewport(computeViewport(event.size.width, event.size.height));
      }
    }

    // update
    sf::Time elapsed = clock.restart();
    group.update(elapsed.asSeconds());

    // render
    window.clear({ 0x30, 0x30, 0x30 });
    window.setView(view);
    group.render(window);
    window.display();
  }

  return 0;
}
<commit_msg>clean the code<commit_after>/*
 * Copyright (c) 2014, Julien Bernard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
#include <cstdio>

#include <game/base/Log.h>
#include <game/graphics/Group.h>

#include "local/Ball.h"
#include "local/Ground.h"
#include "local/Racket.h"
#include "local/Rules.h"

#include "config.h"

static sf::FloatRect computeViewport(unsigned width, unsigned height) {
  float w = static_cast<float>(width);
  float h = static_cast<float>(height);

  float r = w / h * Ground::HEIGHT / Ground::WIDTH;

  sf::FloatRect vp;

  if (width < 2 * height) {
    vp.left = 0.0f;
    vp.width = 1.0;

    vp.top = (1 - r) / 2;
    vp.height = r;
  } else {
    vp.top = 0.0f;
    vp.height = 1.0f;

    vp.left = (1 - 1 / r) / 2;
    vp.width = 1 / r;
  }

  return vp;
}

int main() {
  std::printf("Pong (version " GAME_VERSION ")\n");

  // initialize

  static constexpr unsigned INITIAL_WIDTH = 1024;
  static constexpr unsigned INITIAL_HEIGHT = 768;

  sf::RenderWindow window(sf::VideoMode(INITIAL_WIDTH, INITIAL_HEIGHT), "Pong (version " GAME_VERSION ")");
  window.setKeyRepeatEnabled(false);

  // add entities

  game::Group group;
  Ground ground;
  Racket lft(Racket::Location::LEFT);
  Racket rgt(Racket::Location::RIGHT);
  Ball ball;

  Rules rules(lft, rgt, ball);

  group.addEntity(ground).addEntity(ball).addEntity(lft).addEntity(rgt).addEntity(rules);

  // main loop

  sf::View view;
  view.setCenter({ 0.0f, 0.0f });
  view.setSize({ 200.0f, 100.0f });

  view.setViewport(computeViewport(INITIAL_WIDTH, INITIAL_HEIGHT));

  sf::Clock clock;

  while (window.isOpen()) {
    // input
    sf::Event event;

    while (window.pollEvent(event)) {
      if (event.type == sf::Event::Closed) {
        window.close();
      } else if (event.type == sf::Event::KeyPressed) {

        switch (event.key.code) {
          case sf::Keyboard::Escape:
            window.close();
            break;

          case sf::Keyboard::S:
            lft.move(Racket::Move::UP);
            break;

          case sf::Keyboard::X:
            lft.move(Racket::Move::DOWN);
            break;

          case sf::Keyboard::Up:
            rgt.move(Racket::Move::UP);
            break;

          case sf::Keyboard::Down:
            rgt.move(Racket::Move::DOWN);
            break;

          default:
            break;
        }

      } else if(event.type == sf::Event::KeyReleased) {

        switch (event.key.code) {
          case sf::Keyboard::S:
            lft.move(Racket::Move::STOP);
            break;

          case sf::Keyboard::X:
            lft.move(Racket::Move::STOP);
            break;

          case sf::Keyboard::Up:
            rgt.move(Racket::Move::STOP);
            break;

          case sf::Keyboard::Down:
            rgt.move(Racket::Move::STOP);
            break;

          default:
            break;
        }

      } else if (event.type == sf::Event::Resized) {
        view.setViewport(computeViewport(event.size.width, event.size.height));
      }
    }

    // update
    sf::Time elapsed = clock.restart();
    group.update(elapsed.asSeconds());

    // render
    window.clear({ 0x30, 0x30, 0x30 });
    window.setView(view);
    group.render(window);
    window.display();
  }

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <oleacc.h>

#include "base/utf_string_conversions.h"
#include "base/win/scoped_comptr.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bar_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/accessibility/accessibility_types.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/accessibility/native_view_accessibility_win.h"
#include "views/widget/widget.h"

namespace {

VARIANT id_self = {VT_I4, CHILDID_SELF};

// Dummy class to force creation of ATL module, needed by COM to instantiate
// NativeViewAccessibilityWin.
class TestAtlModule : public CAtlDllModuleT<TestAtlModule> {};
TestAtlModule test_atl_module_;

}  // namespace

class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
 public:
  BrowserViewsAccessibilityTest() {
    ::CoInitialize(NULL);
  }

  ~BrowserViewsAccessibilityTest() {
    ::CoUninitialize();
  }

  // Retrieves an instance of BrowserWindowTesting
  BrowserWindowTesting* GetBrowserWindowTesting() {
    BrowserWindow* browser_window = browser()->window();

    if (!browser_window)
      return NULL;

    return browser_window->GetBrowserWindowTesting();
  }

  // Retrieve an instance of BrowserView
  BrowserView* GetBrowserView() {
    return BrowserView::GetBrowserViewForBrowser(browser());
  }

  // Retrieves and initializes an instance of ToolbarView.
  ToolbarView* GetToolbarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetToolbarView();
  }

  // Retrieves and initializes an instance of BookmarkBarView.
  BookmarkBarView* GetBookmarkBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetBookmarkBarView();
  }

  // Retrieves and verifies the accessibility object for the given View.
  void TestViewAccessibilityObject(views::View* view, std::wstring name,
                                   int32 role) {
    ASSERT_TRUE(NULL != view);

    TestAccessibilityInfo(view->GetNativeViewAccessible(), name, role);
  }

  // Verifies MSAA Name and Role properties of the given IAccessible.
  void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
                             int32 role) {
    // Verify MSAA Name property.
    BSTR acc_name;

    HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
    ASSERT_EQ(S_OK, hr);
    EXPECT_STREQ(acc_name, name.c_str());

    // Verify MSAA Role property.
    VARIANT acc_role;
    ::VariantInit(&acc_role);

    hr = acc_obj->get_accRole(id_self, &acc_role);
    ASSERT_EQ(S_OK, hr);
    EXPECT_EQ(VT_I4, acc_role.vt);
    EXPECT_EQ(role, acc_role.lVal);

    ::VariantClear(&acc_role);
    ::SysFreeString(acc_name);
  }
};

// Retrieve accessibility object for main window and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestChromeWindowAccObj) {
  BrowserWindow* browser_window = browser()->window();
  ASSERT_TRUE(NULL != browser_window);

  HWND hwnd = browser_window->GetNativeHandle();
  ASSERT_TRUE(NULL != hwnd);

  // Get accessibility object.
  base::win::ScopedComPtr<IAccessible> acc_obj;
  HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
                                            reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
  std::wstring title = UTF16ToWide(l10n_util::GetStringFUTF16(
      IDS_BROWSER_WINDOW_TITLE_FORMAT,
      ASCIIToUTF16(chrome::kAboutBlankURL)));
  TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
  views::View* non_client_view =
  GetBrowserView()->GetWidget()->non_client_view();

  TestViewAccessibilityObject(non_client_view,
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)),
      ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBrowserRootViewAccObj) {
  views::View* browser_root_view = GetBrowserView()->frame()->GetRootView();

  TestViewAccessibilityObject(
      browser_root_view,
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)),
      ROLE_SYSTEM_APPLICATION);
}

// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
  // Verify root view MSAA name and role.
  TestViewAccessibilityObject(
      GetBrowserView(),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)),
      ROLE_SYSTEM_CLIENT);
}

// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
  // Verify toolbar MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView(),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_TOOLBAR)),
      ROLE_SYSTEM_TOOLBAR);
}

// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
  // Verify Back button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_BACK)),
      ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
  // Verify Forward button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_FORWARD)),
      ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
  // Verify Reload button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_RELOAD)),
      ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
  // Verify Home button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_HOME)),
      ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestStarButtonAccObj) {
  // Verify Star button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_STAR)),
      ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
  // Verify App menu button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_APP)),
      ROLE_SYSTEM_BUTTONMENU);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBookmarkBarViewAccObj) {
  TestViewAccessibilityObject(
      GetBookmarkBarView(),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_BOOKMARKS)),
      ROLE_SYSTEM_TOOLBAR);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestAboutChromeViewAccObj) {
  //  Firstly, test that the WindowDelegate got updated.
  views::Widget* about_chrome_window =
      GetBrowserView()->DoShowAboutChromeDialog();
  EXPECT_STREQ(
      about_chrome_window->widget_delegate()->GetWindowTitle().c_str(),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ABOUT_CHROME_TITLE)).c_str());
  EXPECT_EQ(about_chrome_window->widget_delegate()->GetAccessibleWindowRole(),
            ui::AccessibilityTypes::ROLE_DIALOG);

  // Also test the accessibility object directly.
  IAccessible* acc_obj = NULL;
  HRESULT hr =
    ::AccessibleObjectFromWindow(about_chrome_window->GetNativeWindow(),
                                 OBJID_CLIENT,
                                 IID_IAccessible,
                                 reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  TestAccessibilityInfo(
      acc_obj,
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ABOUT_CHROME_TITLE)),
      ROLE_SYSTEM_DIALOG);

  acc_obj->Release();
}
<commit_msg>Add more traces to the failing test.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <oleacc.h>

#include "base/utf_string_conversions.h"
#include "base/win/scoped_comptr.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bar_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/accessibility/accessibility_types.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/accessibility/native_view_accessibility_win.h"
#include "views/widget/widget.h"

namespace {

VARIANT id_self = {VT_I4, CHILDID_SELF};

// Dummy class to force creation of ATL module, needed by COM to instantiate
// NativeViewAccessibilityWin.
class TestAtlModule : public CAtlDllModuleT<TestAtlModule> {};
TestAtlModule test_atl_module_;

}  // namespace

class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
 public:
  BrowserViewsAccessibilityTest() {
    ::CoInitialize(NULL);
  }

  ~BrowserViewsAccessibilityTest() {
    ::CoUninitialize();
  }

  // Retrieves an instance of BrowserWindowTesting
  BrowserWindowTesting* GetBrowserWindowTesting() {
    BrowserWindow* browser_window = browser()->window();

    if (!browser_window)
      return NULL;

    return browser_window->GetBrowserWindowTesting();
  }

  // Retrieve an instance of BrowserView
  BrowserView* GetBrowserView() {
    return BrowserView::GetBrowserViewForBrowser(browser());
  }

  // Retrieves and initializes an instance of ToolbarView.
  ToolbarView* GetToolbarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetToolbarView();
  }

  // Retrieves and initializes an instance of BookmarkBarView.
  BookmarkBarView* GetBookmarkBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetBookmarkBarView();
  }

  // Retrieves and verifies the accessibility object for the given View.
  void TestViewAccessibilityObject(views::View* view, std::wstring name,
                                   int32 role) {
    ASSERT_TRUE(NULL != view);

    TestAccessibilityInfo(view->GetNativeViewAccessible(), name, role);
  }

  // Verifies MSAA Name and Role properties of the given IAccessible.
  void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
                             int32 role) {
    // Verify MSAA Name property.
    BSTR acc_name;

    HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
    ASSERT_EQ(S_OK, hr);
    EXPECT_STREQ(acc_name, name.c_str());

    // Verify MSAA Role property.
    VARIANT acc_role;
    ::VariantInit(&acc_role);

    hr = acc_obj->get_accRole(id_self, &acc_role);
    ASSERT_EQ(S_OK, hr);
    EXPECT_EQ(VT_I4, acc_role.vt);
    EXPECT_EQ(role, acc_role.lVal);

    ::VariantClear(&acc_role);
    ::SysFreeString(acc_name);
  }
};

// Retrieve accessibility object for main window and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestChromeWindowAccObj) {
  BrowserWindow* browser_window = browser()->window();
  ASSERT_TRUE(NULL != browser_window);

  HWND hwnd = browser_window->GetNativeHandle();
  ASSERT_TRUE(NULL != hwnd);

  // Get accessibility object.
  base::win::ScopedComPtr<IAccessible> acc_obj;
  HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
                                            reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
  std::wstring title = UTF16ToWide(l10n_util::GetStringFUTF16(
      IDS_BROWSER_WINDOW_TITLE_FORMAT,
      ASCIIToUTF16(chrome::kAboutBlankURL)));
  TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
  views::View* non_client_view =
  GetBrowserView()->GetWidget()->non_client_view();

  TestViewAccessibilityObject(non_client_view,
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)),
      ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBrowserRootViewAccObj) {
  views::View* browser_root_view = GetBrowserView()->frame()->GetRootView();

  TestViewAccessibilityObject(
      browser_root_view,
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)),
      ROLE_SYSTEM_APPLICATION);
}

// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
  // Verify root view MSAA name and role.
  TestViewAccessibilityObject(
      GetBrowserView(),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)),
      ROLE_SYSTEM_CLIENT);
}

// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
  // Verify toolbar MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView(),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_TOOLBAR)),
      ROLE_SYSTEM_TOOLBAR);
}

// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
  // Verify Back button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_BACK)),
      ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
  // Verify Forward button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_FORWARD)),
      ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
  // Verify Reload button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_RELOAD)),
      ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
  // Verify Home button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_HOME)),
      ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestStarButtonAccObj) {
  // Verify Star button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_STAR)),
      ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
  // Verify App menu button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_APP)),
      ROLE_SYSTEM_BUTTONMENU);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBookmarkBarViewAccObj) {
  TestViewAccessibilityObject(
      GetBookmarkBarView(),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ACCNAME_BOOKMARKS)),
      ROLE_SYSTEM_TOOLBAR);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FAILS_TestAboutChromeViewAccObj) {
  LOG(ERROR) << "Starting TestAboutChromeViewAccObj test\n";

  //  Firstly, test that the WindowDelegate got updated.
  views::Widget* about_chrome_window =
      GetBrowserView()->DoShowAboutChromeDialog();
  EXPECT_STREQ(
      about_chrome_window->widget_delegate()->GetWindowTitle().c_str(),
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ABOUT_CHROME_TITLE)).c_str());
  EXPECT_EQ(about_chrome_window->widget_delegate()->GetAccessibleWindowRole(),
            ui::AccessibilityTypes::ROLE_DIALOG);

  LOG(ERROR) << "Test object directly\n";

  // Also test the accessibility object directly.
  IAccessible* acc_obj = NULL;
  HRESULT hr =
    ::AccessibleObjectFromWindow(about_chrome_window->GetNativeWindow(),
                                 OBJID_CLIENT,
                                 IID_IAccessible,
                                 reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  LOG(ERROR) << "TestAccessibilityInfo\n";

  TestAccessibilityInfo(
      acc_obj,
      UTF16ToWide(l10n_util::GetStringUTF16(IDS_ABOUT_CHROME_TITLE)),
      ROLE_SYSTEM_DIALOG);

  acc_obj->Release();

  LOG(ERROR) << "Done\n";
}
<|endoftext|>