<commit_before>/*************************************************************************
 *
 *  $RCSfile: targetdragcontext.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2003-10-06 14:38:51 $
 *
 *  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 _TARGETDRAGCONTEXT_HXX_
#define _TARGETDRAGCONTEXT_HXX_

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDROPTARGETDRAGCONTEXT_HPP_
#include <com/sun/star/datatransfer/dnd/XDropTargetDragContext.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DATAFLAVOR_HPP_
#include <com/sun/star/datatransfer/DataFlavor.hpp>
#endif

#include "target.hxx"
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::dnd;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

class TargetDragContext: public WeakImplHelper1<XDropTargetDragContext>
{
    // some calls to the functions of XDropTargetDragContext are delegated
    // to non-interface functions of m_pDropTarget
    DropTarget* m_pDropTarget;

    TargetDragContext();
    TargetDragContext( const TargetDragContext&);
    TargetDragContext &operator= ( const TargetDragContext&);
public:
    TargetDragContext( DropTarget* pTarget);
    ~TargetDragContext();

    virtual void SAL_CALL acceptDrag( sal_Int8 dragOperation )
        throw( RuntimeException);
    virtual void SAL_CALL rejectDrag(  )
        throw( RuntimeException);
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.48); FILE MERGED 2005/09/05 18:48:20 rt 1.5.48.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: targetdragcontext.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:20:14 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _TARGETDRAGCONTEXT_HXX_
#define _TARGETDRAGCONTEXT_HXX_

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDROPTARGETDRAGCONTEXT_HPP_
#include <com/sun/star/datatransfer/dnd/XDropTargetDragContext.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DATAFLAVOR_HPP_
#include <com/sun/star/datatransfer/DataFlavor.hpp>
#endif

#include "target.hxx"
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::dnd;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

class TargetDragContext: public WeakImplHelper1<XDropTargetDragContext>
{
    // some calls to the functions of XDropTargetDragContext are delegated
    // to non-interface functions of m_pDropTarget
    DropTarget* m_pDropTarget;

    TargetDragContext();
    TargetDragContext( const TargetDragContext&);
    TargetDragContext &operator= ( const TargetDragContext&);
public:
    TargetDragContext( DropTarget* pTarget);
    ~TargetDragContext();

    virtual void SAL_CALL acceptDrag( sal_Int8 dragOperation )
        throw( RuntimeException);
    virtual void SAL_CALL rejectDrag(  )
        throw( RuntimeException);
};

#endif
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2016 dune-gdt developers and contributors. All rights reserved.
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// Authors:
//   Felix Schindler (2015 - 2016)

#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_BASE_HH
#define DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_BASE_HH

#include <dune/xt/common/memory.hh>

#include "interface.hh"

namespace Dune {
namespace GDT {
namespace LinearElliptic {

template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim>
class ProblemBase : public ProblemInterface<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim>
{
private:
  typedef ProblemInterface<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim> BaseType;

public:
  using typename BaseType::DiffusionFactorType;
  using typename BaseType::DiffusionTensorType;
  using typename BaseType::FunctionType;

  ProblemBase(const DiffusionFactorType& diff_fac, const DiffusionTensorType& diff_ten, const FunctionType& forc,
              const FunctionType& dir, const FunctionType& neum, XT::Common::Configuration grd_cfg,
              XT::Common::Configuration bnd_cfg)
    : diffusion_factor_(diff_fac)
    , diffusion_tensor_(diff_ten)
    , force_(forc)
    , dirichlet_(dir)
    , neumann_(neum)
    , grid_cfg_(grd_cfg)
    , boundary_info_cfg_(bnd_cfg)
  {
  }

  /**
   * \note Do not manually delete these pointers, they are managed automaticall from here on!
   */
  ProblemBase(const DiffusionFactorType* diff_fac, const DiffusionTensorType* diff_ten, const FunctionType* forc,
              const FunctionType* dir, const FunctionType* neum, XT::Common::Configuration grd_cfg,
              XT::Common::Configuration bnd_cfg)
    : diffusion_factor_(diff_fac)
    , diffusion_tensor_(diff_ten)
    , force_(forc)
    , dirichlet_(dir)
    , neumann_(neum)
    , grid_cfg_(grd_cfg)
    , boundary_info_cfg_(bnd_cfg)
  {
  }

  virtual const DiffusionFactorType& diffusion_factor() const override
  {
    return diffusion_factor_.access();
  }

  virtual const DiffusionTensorType& diffusion_tensor() const override
  {
    return diffusion_tensor_.access();
  }

  virtual const FunctionType& force() const override
  {
    return force_.access();
  }

  virtual const FunctionType& dirichlet() const override
  {
    return dirichlet_.access();
  }

  virtual const FunctionType& neumann() const override
  {
    return neumann_.access();
  }

  virtual const XT::Common::Configuration& grid_cfg() const override
  {
    return grid_cfg_;
  }

  virtual const XT::Common::Configuration& boundary_info_cfg() const override
  {
    return boundary_info_cfg_;
  }

protected:
  const XT::Common::ConstStorageProvider<DiffusionFactorType> diffusion_factor_;
  const XT::Common::ConstStorageProvider<DiffusionTensorType> diffusion_tensor_;
  const XT::Common::ConstStorageProvider<FunctionType> force_;
  const XT::Common::ConstStorageProvider<FunctionType> dirichlet_;
  const XT::Common::ConstStorageProvider<FunctionType> neumann_;
  const XT::Common::Configuration grid_cfg_;
  const XT::Common::Configuration boundary_info_cfg_;
}; // class ProblemBase

} // namespace LinearElliptic
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_BASE_HH
<commit_msg>[test] adjust for StorageProvider changes<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2016 dune-gdt developers and contributors. All rights reserved.
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// Authors:
//   Felix Schindler (2015 - 2016)

#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_BASE_HH
#define DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_BASE_HH

#include <dune/xt/common/memory.hh>

#include "interface.hh"

namespace Dune {
namespace GDT {
namespace LinearElliptic {

template <class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim>
class ProblemBase : public ProblemInterface<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim>
{
private:
  typedef ProblemInterface<EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim> BaseType;

public:
  using typename BaseType::DiffusionFactorType;
  using typename BaseType::DiffusionTensorType;
  using typename BaseType::FunctionType;

  ProblemBase(const DiffusionFactorType& diff_fac, const DiffusionTensorType& diff_ten, const FunctionType& forc,
              const FunctionType& dir, const FunctionType& neum, XT::Common::Configuration grd_cfg,
              XT::Common::Configuration bnd_cfg)
    : diffusion_factor_(diff_fac)
    , diffusion_tensor_(diff_ten)
    , force_(forc)
    , dirichlet_(dir)
    , neumann_(neum)
    , grid_cfg_(grd_cfg)
    , boundary_info_cfg_(bnd_cfg)
  {
  }

  /**
   * \note Do not manually delete these pointers, they are managed automaticall from here on!
   */
  ProblemBase(const DiffusionFactorType*&& diff_fac, const DiffusionTensorType*&& diff_ten, const FunctionType*&& forc,
              const FunctionType*&& dir, const FunctionType*&& neum, XT::Common::Configuration grd_cfg,
              XT::Common::Configuration bnd_cfg)
    : diffusion_factor_(std::move(diff_fac))
    , diffusion_tensor_(std::move(diff_ten))
    , force_(std::move(forc))
    , dirichlet_(std::move(dir))
    , neumann_(std::move(neum))
    , grid_cfg_(grd_cfg)
    , boundary_info_cfg_(bnd_cfg)
  {
  }

  virtual const DiffusionFactorType& diffusion_factor() const override
  {
    return diffusion_factor_.access();
  }

  virtual const DiffusionTensorType& diffusion_tensor() const override
  {
    return diffusion_tensor_.access();
  }

  virtual const FunctionType& force() const override
  {
    return force_.access();
  }

  virtual const FunctionType& dirichlet() const override
  {
    return dirichlet_.access();
  }

  virtual const FunctionType& neumann() const override
  {
    return neumann_.access();
  }

  virtual const XT::Common::Configuration& grid_cfg() const override
  {
    return grid_cfg_;
  }

  virtual const XT::Common::Configuration& boundary_info_cfg() const override
  {
    return boundary_info_cfg_;
  }

protected:
  const XT::Common::ConstStorageProvider<DiffusionFactorType> diffusion_factor_;
  const XT::Common::ConstStorageProvider<DiffusionTensorType> diffusion_tensor_;
  const XT::Common::ConstStorageProvider<FunctionType> force_;
  const XT::Common::ConstStorageProvider<FunctionType> dirichlet_;
  const XT::Common::ConstStorageProvider<FunctionType> neumann_;
  const XT::Common::Configuration grid_cfg_;
  const XT::Common::Configuration boundary_info_cfg_;
}; // class ProblemBase

} // namespace LinearElliptic
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_BASE_HH
<|endoftext|>


<commit_before>#include <iostream>
#include <immintrin.h>
#include <x86intrin.h>

using namespace std;

int main () {
  float src_a[8], dest[8];
  for (int i = 0; i < 8; ++i)
    src_a[i] = float(i);
  __m256 a,b,c;
  a = _mm256_loadu_ps(&src_a[0]);
  b = _mm256_set1_ps(100.0f);
  __m256 mask;
  c = a*b-a;
  mask = _mm256_cmp_ps(c,_mm256_set1_ps(500.0f) , _CMP_LT_OQ);
  c = _mm256_blendv_ps(c,-c,mask);
  c =  _mm256_set1_ps(1.0f) / c;
  _mm256_storeu_ps(&dest[0], c);
  for (int i = 0; i < 8; ++i)
    cout << dest[i] << endl;
  return 0;
}
<commit_msg>understood the avx comprehension.<commit_after>#include <iostream>
#include <immintrin.h>
#include <x86intrin.h>

using namespace std;

void inspect(__m256 a) {
  float dest[8];
  _mm256_storeu_ps(&dest[0], a);
  for (int i = 0; i < 8; ++i)
    cout << dest[i] << "\t";
  cout << endl;

}

int main () {
  float src_a[8], dest[8];
  for (int i = 0; i < 8; ++i)
    src_a[i] = float(i+1);
  __m256 a,b,c;
  a = _mm256_loadu_ps(&src_a[0]);
  b = _mm256_set1_ps(100.0f);
  c = a*b+2.0f*a;
  inspect(c);
  __m256 d = _mm256_permutevar8x32_ps(c, _mm256_set_epi32(0,7,6,5,4,3,2,1));
  inspect(d);
  __m256 e = _mm256_permutevar8x32_ps(c, _mm256_set_epi32(6,5,4,3,2,1,0,7));
  inspect(e);
  return 0;
}
<|endoftext|>


<commit_before>/*
 * LRUCache_test.cpp
 *
 *  Created on: Sep 21, 2013
 *      Author: dumoulma
 */

#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <string>
#include "LRUCache.h"
#include "ICurl.h"

using std::string;
using namespace testing;
using ::testing::Return;

class ICurlMock: public ICurl
{
public:
	MOCK_CONST_METHOD1(getFrom, string(const string &url));
};

class LRUCacheTest: public Test
{
public:
	LRUCacheTest() :
			cache(mock, 100)
	{
	}

protected:
	ICurlMock mock;
	LRUCache cache;
};

TEST_F(LRUCacheTest, newCacheHasSizeZero)
{
	EXPECT_EQ(0, cache.size());
}

TEST_F(LRUCacheTest, addAnewItemToCacheFetchesURLWithCurlAndAddsToCache)
{
	string url = "www.ulaval.ca";
	string expected = "www.ulaval.ca";
	EXPECT_CALL(mock, getFrom(A<const string&>())).Times(1).WillOnce(
			Return(expected));

	string actual = cache.getDocument(url);

	EXPECT_EQ(1, cache.getValueCount());
	EXPECT_EQ(expected.size(), cache.size());
	EXPECT_EQ(expected, actual);
}

TEST_F(LRUCacheTest, getDocumentSecondTimeShouldHitTheCache)
{
	string url = "www.ulaval.ca";
	string expected = "www.ulaval.ca";
	EXPECT_CALL(mock, getFrom(A<const string&>())).Times(1).WillOnce(
			Return(expected));

	cache.getDocument(url);
	string actual = cache.getDocument(url);

	EXPECT_EQ(1, cache.getValueCount());
	EXPECT_EQ(expected, actual);
	EXPECT_EQ(expected.size(), cache.size());
}

TEST_F(LRUCacheTest, twoNewDocumentsAreAddedToTheCache)
{
	string url1 = "www.ulaval.ca";
	string expected1 = "www.ulaval.ca";
	string url2 = "www.ift.ulaval.ca";
	string expected2 =
			"bienvenu au site du departement d'informatique";

	EXPECT_CALL(mock, getFrom(url1)).Times(1).WillOnce(Return(expected1));
	EXPECT_CALL(mock, getFrom(url2)).Times(1).WillOnce(Return(expected2));

	string actual1 = cache.getDocument(url1);
	string actual2 = cache.getDocument(url2);

	EXPECT_EQ(2, cache.getValueCount());
	EXPECT_EQ(expected1, actual1);
	EXPECT_EQ(expected2, actual2);
	EXPECT_EQ(expected1.size() + expected2.size(), cache.size());
}

TEST_F(LRUCacheTest, addElementToFullCacheMakesSpaceOK1)
{
	string url1 = "www.ulaval.ca";
	string expected1 = "www.ulaval.ca";
	string url2 = "www.ift.ulaval.ca";
	string expected2 =
			"bienvenu au site du departement d'informatique";
	string url3 = "www.gel-gif.ulaval.ca";
	string expected3 =
			"bienvenu au site du departement de genie electrique et genie informatique";

	EXPECT_CALL(mock, getFrom(url1)).Times(1).WillOnce(Return(expected1));
	EXPECT_CALL(mock, getFrom(url2)).Times(1).WillOnce(Return(expected2));
	EXPECT_CALL(mock, getFrom(url3)).Times(1).WillOnce(Return(expected3));

	string actual1 = cache.getDocument(url1);
	string actual2 = cache.getDocument(url2);
	string actual3 = cache.getDocument(url3);

	EXPECT_EQ(1, cache.getValueCount());
	EXPECT_EQ(expected3.size(), cache.size());
}

TEST_F(LRUCacheTest, addElementToFullCacheMakesSpaceOK2)
{
	string url1 = "www.ulaval.ca";
	string expected1 = "www.ulaval.ca";
	string url2 = "www.ift.ulaval.ca";
	string expected2 =
			"bienvenu au site du departement d'informatique";
	string url3 = "www.monblog.ca";
	string expected3 = "bienvenu a mon blug";

	EXPECT_CALL(mock, getFrom(url1)).Times(1).WillOnce(Return(expected1));
	EXPECT_CALL(mock, getFrom(url2)).Times(1).WillOnce(Return(expected2));
	EXPECT_CALL(mock, getFrom(url3)).Times(1).WillOnce(Return(expected3));

	string actual1 = cache.getDocument(url1);
	EXPECT_EQ(expected1.size(), cache.size());

	string actual2 = cache.getDocument(url2);
	EXPECT_EQ(expected1.size() + expected2.size(), cache.size());

	string actual3 = cache.getDocument(url3);
	EXPECT_EQ(2, cache.getValueCount());
	EXPECT_EQ(expected2.size() + expected3.size(), cache.size());
}

TEST_F(LRUCacheTest, givenACacheWith2elementsGettingTheOlderElementWillRefreshItsAge)
{
	string url1 = "www.gel-gif.ulaval.ca";
	string expected1(55, '1');
	string url2 = "www.ift.ulaval.ca";
	string expected2(40, '2');
	string url3 = "www.monblog.ca";
	string expected3(20, '3');

	EXPECT_CALL(mock, getFrom(url1)).Times(1).WillOnce(Return(expected1));
	EXPECT_CALL(mock, getFrom(url2)).Times(1).WillOnce(Return(expected2));
	EXPECT_CALL(mock, getFrom(url3)).Times(1).WillOnce(Return(expected3));

	cache.getDocument(url1);
	cache.getDocument(url2);
	cache.getDocument(url1);
	string actual3 = cache.getDocument(url3);

	EXPECT_EQ(2, cache.getValueCount());
	EXPECT_EQ(expected1.size() + expected3.size(), cache.size());
}

TEST_F(LRUCacheTest, gettingADocumentBiggerThanTheCacheDoesntAddIt)
{
	string url1 = "www.gel-gif.ulaval.ca";
	string expected1(101, '1');

	EXPECT_CALL(mock, getFrom(url1)).Times(1).WillOnce(Return(expected1));

	string actual = cache.getDocument(url1);

	EXPECT_EQ(expected1, actual);
	EXPECT_EQ(0, cache.getValueCount());
	EXPECT_EQ(0, cache.size());
}

int main(int argc, char** argv)
{
	// The following line must be executed to initialize Google Mock
	// (and Google Test) before running the tests.
	::testing::InitGoogleMock(&argc, argv);
	return RUN_ALL_TESTS();
}
<commit_msg>removed warning comparing signed with unsigned by casting to size_t<commit_after>/*
 * LRUCache_test.cpp
 *
 *  Created on: Sep 21, 2013
 *      Author: dumoulma
 */

#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <string>
#include "LRUCache.h"
#include "ICurl.h"

using std::string;
using namespace testing;
using ::testing::Return;

class ICurlMock: public ICurl
{
public:
	MOCK_CONST_METHOD1(getFrom, string(const string &url));
};

struct LRUCacheTest: public Test
{
	LRUCacheTest() :
			cache(mock, 100)
	{
	}

	ICurlMock mock;
	LRUCache cache;
};

TEST_F(LRUCacheTest, newCacheHasSizeZero)
{
	EXPECT_EQ((size_t) 0, cache.size());
}

TEST_F(LRUCacheTest, addAnewItemToCacheFetchesURLWithCurlAndAddsToCache)
{
	string url = "www.ulaval.ca";
	string expected = "www.ulaval.ca";
	EXPECT_CALL(mock, getFrom(A<const string&>())).Times(1).WillOnce(
			Return(expected));

	string actual = cache.getDocument(url);

	EXPECT_EQ((size_t) 1, cache.getValueCount());
	EXPECT_EQ(expected.size(), cache.size());
	EXPECT_EQ(expected, actual);
}

TEST_F(LRUCacheTest, getDocumentSecondTimeShouldHitTheCache)
{
	string url = "www.ulaval.ca";
	string expected = "www.ulaval.ca";
	EXPECT_CALL(mock, getFrom(A<const string&>())).Times(1).WillOnce(
			Return(expected));

	cache.getDocument(url);
	string actual = cache.getDocument(url);

	EXPECT_EQ((size_t) 1, cache.getValueCount());
	EXPECT_EQ(expected, actual);
	EXPECT_EQ(expected.size(), cache.size());
}

TEST_F(LRUCacheTest, twoNewDocumentsAreAddedToTheCache)
{
	string url1 = "www.ulaval.ca";
	string expected1 = "www.ulaval.ca";
	string url2 = "www.ift.ulaval.ca";
	string expected2 =
			"bienvenu au site du departement d'informatique";

	EXPECT_CALL(mock, getFrom(url1)).Times(1).WillOnce(Return(expected1));
	EXPECT_CALL(mock, getFrom(url2)).Times(1).WillOnce(Return(expected2));

	string actual1 = cache.getDocument(url1);
	string actual2 = cache.getDocument(url2);

	EXPECT_EQ(2, cache.getValueCount());
	EXPECT_EQ(expected1, actual1);
	EXPECT_EQ(expected2, actual2);
	EXPECT_EQ(expected1.size() + expected2.size(), cache.size());
}

TEST_F(LRUCacheTest, addElementToFullCacheMakesSpaceOK1)
{
	string url1 = "www.ulaval.ca";
	string expected1 = "www.ulaval.ca";
	string url2 = "www.ift.ulaval.ca";
	string expected2 =
			"bienvenu au site du departement d'informatique";
	string url3 = "www.gel-gif.ulaval.ca";
	string expected3 =
			"bienvenu au site du departement de genie electrique et genie informatique";

	EXPECT_CALL(mock, getFrom(url1)).Times(1).WillOnce(Return(expected1));
	EXPECT_CALL(mock, getFrom(url2)).Times(1).WillOnce(Return(expected2));
	EXPECT_CALL(mock, getFrom(url3)).Times(1).WillOnce(Return(expected3));

	string actual1 = cache.getDocument(url1);
	string actual2 = cache.getDocument(url2);
	string actual3 = cache.getDocument(url3);

	EXPECT_EQ(1, cache.getValueCount());
	EXPECT_EQ(expected3.size(), cache.size());
}

TEST_F(LRUCacheTest, addElementToFullCacheMakesSpaceOK2)
{
	string url1 = "www.ulaval.ca";
	string expected1 = "www.ulaval.ca";
	string url2 = "www.ift.ulaval.ca";
	string expected2 =
			"bienvenu au site du departement d'informatique";
	string url3 = "www.monblog.ca";
	string expected3 = "bienvenu a mon blug";

	EXPECT_CALL(mock, getFrom(url1)).Times(1).WillOnce(Return(expected1));
	EXPECT_CALL(mock, getFrom(url2)).Times(1).WillOnce(Return(expected2));
	EXPECT_CALL(mock, getFrom(url3)).Times(1).WillOnce(Return(expected3));

	string actual1 = cache.getDocument(url1);
	EXPECT_EQ(expected1.size(), cache.size());

	string actual2 = cache.getDocument(url2);
	EXPECT_EQ(expected1.size() + expected2.size(), cache.size());

	string actual3 = cache.getDocument(url3);
	EXPECT_EQ(2, cache.getValueCount());
	EXPECT_EQ(expected2.size() + expected3.size(), cache.size());
}

TEST_F(LRUCacheTest, givenACacheWith2elementsGettingTheOlderElementWillRefreshItsAge)
{
	string url1 = "www.gel-gif.ulaval.ca";
	string expected1(55, '1');
	string url2 = "www.ift.ulaval.ca";
	string expected2(40, '2');
	string url3 = "www.monblog.ca";
	string expected3(20, '3');

	EXPECT_CALL(mock, getFrom(url1)).Times(1).WillOnce(Return(expected1));
	EXPECT_CALL(mock, getFrom(url2)).Times(1).WillOnce(Return(expected2));
	EXPECT_CALL(mock, getFrom(url3)).Times(1).WillOnce(Return(expected3));

	cache.getDocument(url1);
	cache.getDocument(url2);
	cache.getDocument(url1);
	string actual3 = cache.getDocument(url3);

	EXPECT_EQ(2, cache.getValueCount());
	EXPECT_EQ(expected1.size() + expected3.size(), cache.size());
}

TEST_F(LRUCacheTest, gettingADocumentBiggerThanTheCacheDoesntAddIt)
{
	string url1 = "www.gel-gif.ulaval.ca";
	string expected1(101, '1');

	EXPECT_CALL(mock, getFrom(url1)).Times(1).WillOnce(Return(expected1));

	string actual = cache.getDocument(url1);

	EXPECT_EQ(expected1, actual);
	EXPECT_EQ(0, cache.getValueCount());
	EXPECT_EQ(0, cache.size());
}

int main(int argc, char** argv)
{
	// The following line must be executed to initialize Google Mock
	// (and Google Test) before running the tests.
	::testing::InitGoogleMock(&argc, argv);
	return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>//  (C) Copyright Gennadiy Rozental 2001-2010.
//  (C) Copyright Gennadiy Rozental & Ullrich Koethe 2001.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.

// Boost.Test
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
using namespace boost::unit_test;
using boost::test_tools::close_at_tolerance;
using boost::test_tools::percent_tolerance;

// BOOST
#include <boost/lexical_cast.hpp>

// STL
#include <functional>
#include <iostream>
#include <iomanip>
#include <memory>
#include <stdexcept>

//____________________________________________________________________________//

struct account {
    account()
    : m_amount(0.0)
    {}

    void deposit(double amount) { m_amount += amount; }
    void withdraw(double amount)
    {
        if(amount > m_amount)
        {
            throw std::logic_error("You don't have that much money!");
        }
        m_amount -= amount;
    }
    double balance() const { return m_amount; }

private:
    double m_amount;
};

//____________________________________________________________________________//

struct account_test {
    account_test( double init_value ) { m_account.deposit( init_value ); }

    account m_account;  // a very simple fixture

    void test_init()
    {
        // different kinds of non-critical tests
        // they report the error and continue

        // standard assertion
        // reports 'error in "account_test::test_init": test m_account.balance() >= 0.0 failed' on error
        BOOST_CHECK( m_account.balance() >= 0.0 );

        // customized assertion
        // reports 'error in "account_test::test_init": Initial balance should be more then 1, was actual_value' on error
        BOOST_CHECK_MESSAGE( m_account.balance() > 1.0,
                             "Initial balance should be more then 1, was " << m_account.balance() );

        // equality assertion (not very wise idea use equality check on floating point values)
        // reports 'error in "account_test::test_init": test m_account.balance() == 5.0 failed [actual_value != 5]' on error
        BOOST_CHECK_EQUAL( m_account.balance(), 5.0 );

        // closeness assertion for floating-point numbers (symbol (==) used to mark closeness, (!=) to mark non closeness )
        // reports 'error in "account_test::test_init": test m_account.balance() (==) 10.0 failed [actual_value (!=) 10 (1e-010)]' on error
        BOOST_CHECK_CLOSE( m_account.balance(), 10.0, /* tolerance */ 1e-10 );
    }

    void test_deposit()
    {
        // these 2 statements just to show that usage manipulators doesn't hurt Boost.Test output
        std::cout << "Current balance: " << std::hex << (int)m_account.balance() << std::endl;
        std::cerr << "Current balance: " << std::hex << (int)m_account.balance() << std::endl;

        float curr_ballance = (float)m_account.balance();
        float deposit_value;

        std::cout << "Enter deposit value:\n";
        std::cin  >> deposit_value;

        m_account.deposit( deposit_value );

        // correct result validation; could fail due to rounding errors; use BOOST_CHECK_CLOSE instead
        // reports "test m_account.balance() == curr_ballance + deposit_value failed" on error
        BOOST_CHECK( m_account.balance() == curr_ballance + deposit_value );

        // different kinds of critical tests

        // reports 'fatal error in "account_test::test_deposit": test m_account.balance() >= 100.0 failed' on error
        BOOST_REQUIRE( m_account.balance() >= 100.0 );

        // reports 'fatal error in "account_test::test_deposit": Balance should be more than 500.1, was actual_value' on error
        BOOST_REQUIRE_MESSAGE( m_account.balance() > 500.1,
                               "Balance should be more than 500.1, was " << m_account.balance());

        // reports 'fatal error in "account_test::test_deposit": test std::not_equal_to<double>()(m_account.balance(), 999.9) failed
        //          for (999.9, 999.9)' on error
        BOOST_REQUIRE_PREDICATE( std::not_equal_to<double>(), (m_account.balance())(999.9) );

        // reports 'fatal error in "account_test::test_deposit": test close_at_tolerance<double>( 1e-9 )( m_account.balance(), 605.5)
        //          failed for (actual_value, 605.5)
        BOOST_REQUIRE_PREDICATE( close_at_tolerance<double>( percent_tolerance( 1e-9 ) ),
                                 (m_account.balance())(605.5) );
    }

    void test_withdraw()
    {
        float curr_ballance = (float)m_account.balance();

        m_account.withdraw(2.5);

        // correct result validation; could fail due to rounding errors; use BOOST_CHECK_CLOSE instead
        // reports "test m_account.balance() == curr_ballance - 2.5 failed" on error
        BOOST_CHECK( m_account.balance() == curr_ballance - 2.5 );

        // reports 'error in "account_test::test_withdraw": exception std::runtime_error is expected' on error
        BOOST_CHECK_THROW( m_account.withdraw( m_account.balance() + 1 ), std::runtime_error );

    }
};

//____________________________________________________________________________//

struct account_test_suite : public test_suite {
    account_test_suite( double init_value ) : test_suite("account_test_suite") {
        // add member function test cases to a test suite
        boost::shared_ptr<account_test> instance( new account_test( init_value ) );

        test_case* init_test_case     = BOOST_CLASS_TEST_CASE( &account_test::test_init, instance );
        test_case* deposit_test_case  = BOOST_CLASS_TEST_CASE( &account_test::test_deposit, instance );
        test_case* withdraw_test_case = BOOST_CLASS_TEST_CASE( &account_test::test_withdraw, instance );

        deposit_test_case->depends_on( init_test_case );
        withdraw_test_case->depends_on( deposit_test_case );

        add( init_test_case, 1 );
        add( deposit_test_case, 1 );
        add( withdraw_test_case );
    }
};

//____________________________________________________________________________//

test_suite*
init_unit_test_suite( int argc, char * argv[] ) {
    framework::master_test_suite().p_name.value = "Unit test example 10";

    try {
        if( argc < 2 )
            throw std::logic_error( "Initial deposit expected" );

        framework::master_test_suite().add( new account_test_suite( boost::lexical_cast<double>( argv[1] ) ) );
    }
    catch( boost::bad_lexical_cast const& ) {
         throw std::logic_error( "Initial deposit value should match format of double" );
    }

    return 0;
}

//____________________________________________________________________________//

// EOF
<commit_msg>fpc related changes<commit_after>//  (C) Copyright Gennadiy Rozental 2001-2010.
//  (C) Copyright Gennadiy Rozental & Ullrich Koethe 2001.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.

// Boost.Test
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
using namespace boost::unit_test;
using boost::math::fpc::close_at_tolerance;
using boost::math::fpc::percent_tolerance;

// BOOST
#include <boost/lexical_cast.hpp>

// STL
#include <functional>
#include <iostream>
#include <iomanip>
#include <memory>
#include <stdexcept>

//____________________________________________________________________________//

struct account {
    account()
    : m_amount(0.0)
    {}

    void deposit(double amount) { m_amount += amount; }
    void withdraw(double amount)
    {
        if(amount > m_amount)
        {
            throw std::logic_error("You don't have that much money!");
        }
        m_amount -= amount;
    }
    double balance() const { return m_amount; }

private:
    double m_amount;
};

//____________________________________________________________________________//

struct account_test {
    account_test( double init_value ) { m_account.deposit( init_value ); }

    account m_account;  // a very simple fixture

    void test_init()
    {
        // different kinds of non-critical tests
        // they report the error and continue

        // standard assertion
        // reports 'error in "account_test::test_init": test m_account.balance() >= 0.0 failed' on error
        BOOST_CHECK( m_account.balance() >= 0.0 );

        // customized assertion
        // reports 'error in "account_test::test_init": Initial balance should be more then 1, was actual_value' on error
        BOOST_CHECK_MESSAGE( m_account.balance() > 1.0,
                             "Initial balance should be more then 1, was " << m_account.balance() );

        // equality assertion (not very wise idea use equality check on floating point values)
        // reports 'error in "account_test::test_init": test m_account.balance() == 5.0 failed [actual_value != 5]' on error
        BOOST_CHECK_EQUAL( m_account.balance(), 5.0 );

        // closeness assertion for floating-point numbers (symbol (==) used to mark closeness, (!=) to mark non closeness )
        // reports 'error in "account_test::test_init": test m_account.balance() (==) 10.0 failed [actual_value (!=) 10 (1e-010)]' on error
        BOOST_CHECK_CLOSE( m_account.balance(), 10.0, /* tolerance */ 1e-10 );
    }

    void test_deposit()
    {
        // these 2 statements just to show that usage manipulators doesn't hurt Boost.Test output
        std::cout << "Current balance: " << std::hex << (int)m_account.balance() << std::endl;
        std::cerr << "Current balance: " << std::hex << (int)m_account.balance() << std::endl;

        float curr_ballance = (float)m_account.balance();
        float deposit_value;

        std::cout << "Enter deposit value:\n";
        std::cin  >> deposit_value;

        m_account.deposit( deposit_value );

        // correct result validation; could fail due to rounding errors; use BOOST_CHECK_CLOSE instead
        // reports "test m_account.balance() == curr_ballance + deposit_value failed" on error
        BOOST_CHECK( m_account.balance() == curr_ballance + deposit_value );

        // different kinds of critical tests

        // reports 'fatal error in "account_test::test_deposit": test m_account.balance() >= 100.0 failed' on error
        BOOST_REQUIRE( m_account.balance() >= 100.0 );

        // reports 'fatal error in "account_test::test_deposit": Balance should be more than 500.1, was actual_value' on error
        BOOST_REQUIRE_MESSAGE( m_account.balance() > 500.1,
                               "Balance should be more than 500.1, was " << m_account.balance());

        // reports 'fatal error in "account_test::test_deposit": test std::not_equal_to<double>()(m_account.balance(), 999.9) failed
        //          for (999.9, 999.9)' on error
        BOOST_REQUIRE_PREDICATE( std::not_equal_to<double>(), (m_account.balance())(999.9) );

        // reports 'fatal error in "account_test::test_deposit": test close_at_tolerance<double>( 1e-9 )( m_account.balance(), 605.5)
        //          failed for (actual_value, 605.5)
        BOOST_REQUIRE_PREDICATE( close_at_tolerance<double>( percent_tolerance( 1e-9 ) ),
                                 (m_account.balance())(605.5) );
    }

    void test_withdraw()
    {
        float curr_ballance = (float)m_account.balance();

        m_account.withdraw(2.5);

        // correct result validation; could fail due to rounding errors; use BOOST_CHECK_CLOSE instead
        // reports "test m_account.balance() == curr_ballance - 2.5 failed" on error
        BOOST_CHECK( m_account.balance() == curr_ballance - 2.5 );

        // reports 'error in "account_test::test_withdraw": exception std::runtime_error is expected' on error
        BOOST_CHECK_THROW( m_account.withdraw( m_account.balance() + 1 ), std::runtime_error );

    }
};

//____________________________________________________________________________//

struct account_test_suite : public test_suite {
    account_test_suite( double init_value ) : test_suite("account_test_suite") {
        // add member function test cases to a test suite
        boost::shared_ptr<account_test> instance( new account_test( init_value ) );

        test_case* init_test_case     = BOOST_CLASS_TEST_CASE( &account_test::test_init, instance );
        test_case* deposit_test_case  = BOOST_CLASS_TEST_CASE( &account_test::test_deposit, instance );
        test_case* withdraw_test_case = BOOST_CLASS_TEST_CASE( &account_test::test_withdraw, instance );

        deposit_test_case->depends_on( init_test_case );
        withdraw_test_case->depends_on( deposit_test_case );

        add( init_test_case, 1 );
        add( deposit_test_case, 1 );
        add( withdraw_test_case );
    }
};

//____________________________________________________________________________//

test_suite*
init_unit_test_suite( int argc, char * argv[] ) {
    framework::master_test_suite().p_name.value = "Unit test example 10";

    try {
        if( argc < 2 )
            throw std::logic_error( "Initial deposit expected" );

        framework::master_test_suite().add( new account_test_suite( boost::lexical_cast<double>( argv[1] ) ) );
    }
    catch( boost::bad_lexical_cast const& ) {
         throw std::logic_error( "Initial deposit value should match format of double" );
    }

    return 0;
}

//____________________________________________________________________________//

// EOF
<|endoftext|>


<commit_before>#include <gsl/span>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "fs/ExperimentFile.hpp"
#include "mock/FsMock.hpp"
#include "mock/time.hpp"

using testing::NiceMock;
using testing::Return;
using testing::InSequence;
using testing::Eq;
using testing::_;

using namespace experiments::fs;
using namespace std::chrono_literals;
using namespace services::fs;

namespace
{
    class ExperimentFileTest : public testing::Test
    {
      public:
        ExperimentFileTest();

        const char* TestFileName = "/test";

      protected:
        NiceMock<FsMock> _fs;
        NiceMock<CurrentTimeMock> _time;
        std::array<uint8_t, 2 * ExperimentFile::PacketLength> _buffer;
    };

    ExperimentFileTest::ExperimentFileTest()
    {
        ON_CALL(this->_time, GetCurrentTime()).WillByDefault(Return(Some(65536ms)));
        _buffer.fill(0xFF);
        this->_fs.AddFile(TestFileName, _buffer);
    }

    TEST_F(ExperimentFileTest, EmptyFileWithTimestamp)
    {
        ExperimentFile file(&_time);
        uint8_t data = 7;
        file.Open(_fs, TestFileName, FileOpen::CreateAlways, FileAccess::WriteOnly);
        file.Write(ExperimentFile::PID::Reserved, gsl::make_span(&data, 1));
        file.Close();

        std::array<uint8_t, 2 * ExperimentFile::PacketLength> expected;
        expected.fill(0xFF);
        Writer w(expected);

        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);
        w.WriteByte(num(ExperimentFile::PID::Reserved));
        w.WriteByte(7);

        ASSERT_THAT(_buffer, Eq(expected));
    }

    TEST_F(ExperimentFileTest, EmptyFileWithoutTimestamp)
    {
        ExperimentFile file;
        uint8_t data = 7;
        file.Open(_fs, TestFileName, FileOpen::CreateAlways, FileAccess::WriteOnly);
        file.Write(ExperimentFile::PID::Reserved, gsl::make_span(&data, 1));
        file.Close();

        std::array<uint8_t, 2 * ExperimentFile::PacketLength> expected;
        expected.fill(0xFF);
        Writer w(expected);

        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Reserved));
        w.WriteByte(7);

        ASSERT_THAT(_buffer, Eq(expected));
    }

    TEST_F(ExperimentFileTest, WriteSmallDataPacketsAndCheckPacketPadding)
    {
        ExperimentFile file(&_time);
        file.Open(_fs, TestFileName, FileOpen::CreateAlways, FileAccess::WriteOnly);

        std::array<uint8_t, 9> data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        for (int i = 0; i < 21; ++i)
        {
            file.Write(ExperimentFile::PID::Reserved, data);
        }

        file.Close();

        std::array<uint8_t, 2 * ExperimentFile::PacketLength> expected;
        expected.fill(0xFF);
        Writer w(expected);

        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);
        for (int i = 0; i < 21; ++i)
        {
            w.WriteByte(num(ExperimentFile::PID::Reserved));
            w.WriteArray(data);
        }

        ASSERT_THAT(_buffer, Eq(expected));
    }

    TEST_F(ExperimentFileTest, WriteSmallDataPacketsAndCheckPacketSplitting)
    {
        ExperimentFile file(&_time);
        file.Open(_fs, TestFileName, FileOpen::CreateAlways, FileAccess::WriteOnly);

        std::array<uint8_t, 9> data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        for (int i = 0; i < 23; ++i)
        {
            file.Write(ExperimentFile::PID::Reserved, data);
        }

        file.Close();

        std::array<uint8_t, 2 * ExperimentFile::PacketLength> expected;
        expected.fill(0xFF);
        Writer w(expected);

        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);
        for (int i = 0; i < 22; ++i)
        {
            w.WriteByte(num(ExperimentFile::PID::Reserved));
            w.WriteArray(data);
        }
        for (int i = 0; i < 2; ++i)
        {
            w.WriteByte(0xFF);
        }

        // second packet
        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);
        w.WriteByte(num(ExperimentFile::PID::Reserved));
        w.WriteArray(data);

        ASSERT_THAT(_buffer, Eq(expected));
    }

    TEST_F(ExperimentFileTest, WriteBigDataAndCheckPacketSplitting)
    {
        ExperimentFile file(&_time);
        file.Open(_fs, TestFileName, FileOpen::CreateAlways, FileAccess::WriteOnly);

        std::array<uint8_t, 300> data;
        data.fill(0xBC);
        file.Write(ExperimentFile::PID::Reserved, data);

        file.Close();

        std::array<uint8_t, 2 * ExperimentFile::PacketLength> expected;
        expected.fill(0xFF);
        Writer w(expected);

        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);

        w.WriteByte(num(ExperimentFile::PID::Reserved));

        auto length = ExperimentFile::PacketLength - 3 - sizeof(uint64_t);

        for (uint32_t i = 0; i < length; ++i)
        {
            w.WriteByte(0xBC);
        }

        // second packet
        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);
        w.WriteByte(num(ExperimentFile::PID::Continuation));
        w.WriteByte(num(ExperimentFile::PID::Reserved));
        auto secondPacketLength = data.size() - length;
        for (uint32_t i = 0; i < secondPacketLength; ++i)
        {
            w.WriteByte(0xBC);
        }

        ASSERT_THAT(_buffer, Eq(expected));
    }
}
<commit_msg>[Experiment - LEOP] Fixed unit test.<commit_after>#include <gsl/span>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "fs/ExperimentFile.hpp"
#include "mock/FsMock.hpp"
#include "mock/time.hpp"

using testing::NiceMock;
using testing::Return;
using testing::InSequence;
using testing::Eq;
using testing::_;

using namespace experiments::fs;
using namespace std::chrono_literals;
using namespace services::fs;

namespace
{
    class ExperimentFileTest : public testing::Test
    {
      public:
        ExperimentFileTest();

        const char* TestFileName = "/test";

      protected:
        NiceMock<FsMock> _fs;
        NiceMock<CurrentTimeMock> _time;
        std::array<uint8_t, 2 * ExperimentFile::PacketLength> _buffer;
    };

    ExperimentFileTest::ExperimentFileTest()
    {
        ON_CALL(this->_time, GetCurrentTime()).WillByDefault(Return(Some(65536ms)));
        _buffer.fill(0xFF);
        this->_fs.AddFile(TestFileName, _buffer);
    }

    TEST_F(ExperimentFileTest, EmptyFileWithTimestamp)
    {
        ExperimentFile file(&_time);
        uint8_t data = 7;
        file.Open(_fs, TestFileName, FileOpen::CreateAlways, FileAccess::WriteOnly);
        file.Write(ExperimentFile::PID::Reserved, gsl::make_span(&data, 1));
        file.Close();

        std::array<uint8_t, 2 * ExperimentFile::PacketLength> expected;
        expected.fill(0xFF);
        Writer w(expected);

        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);
        w.WriteByte(num(ExperimentFile::PID::Reserved));
        w.WriteByte(7);

        ASSERT_THAT(_buffer, Eq(expected));
    }

    TEST_F(ExperimentFileTest, EmptyFileWithoutTimestamp)
    {
        ExperimentFile file;
        uint8_t data = 7;
        file.Open(_fs, TestFileName, FileOpen::CreateAlways, FileAccess::WriteOnly);
        file.Write(ExperimentFile::PID::Reserved, gsl::make_span(&data, 1));
        file.Close();

        std::array<uint8_t, 2 * ExperimentFile::PacketLength> expected;
        expected.fill(0xFF);
        Writer w(expected);

        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Reserved));
        w.WriteByte(7);

        ASSERT_THAT(_buffer, Eq(expected));
    }

    TEST_F(ExperimentFileTest, WriteSmallDataPacketsAndCheckPacketPadding)
    {
        ExperimentFile file(&_time);
        file.Open(_fs, TestFileName, FileOpen::CreateAlways, FileAccess::WriteOnly);

        std::array<uint8_t, 9> data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        for (int i = 0; i < 21; ++i)
        {
            file.Write(ExperimentFile::PID::Reserved, data);
        }

        file.Close();

        std::array<uint8_t, 2 * ExperimentFile::PacketLength> expected;
        expected.fill(0xFF);
        Writer w(expected);

        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);
        for (int i = 0; i < 21; ++i)
        {
            w.WriteByte(num(ExperimentFile::PID::Reserved));
            w.WriteArray(data);
        }

        ASSERT_THAT(_buffer, Eq(expected));
    }

    TEST_F(ExperimentFileTest, WriteSmallDataPacketsAndCheckPacketSplitting)
    {
        ExperimentFile file(&_time);
        file.Open(_fs, TestFileName, FileOpen::CreateAlways, FileAccess::WriteOnly);

        std::array<uint8_t, 9> data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        for (int i = 0; i < 23; ++i)
        {
            file.Write(ExperimentFile::PID::Reserved, data);
        }

        file.Close();

        std::array<uint8_t, 2 * ExperimentFile::PacketLength> expected;
        expected.fill(0xFF);
        Writer w(expected);

        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);
        for (int i = 0; i < 22; ++i)
        {
            w.WriteByte(num(ExperimentFile::PID::Reserved));
            w.WriteArray(data);
        }

        w.WriteByte(0xFF);

        // second packet
        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);
        w.WriteByte(num(ExperimentFile::PID::Reserved));
        w.WriteArray(data);

        ASSERT_THAT(_buffer, Eq(expected));
    }

    TEST_F(ExperimentFileTest, WriteBigDataAndCheckPacketSplitting)
    {
        ExperimentFile file(&_time);
        file.Open(_fs, TestFileName, FileOpen::CreateAlways, FileAccess::WriteOnly);

        std::array<uint8_t, 300> data;
        data.fill(0xBC);
        file.Write(ExperimentFile::PID::Reserved, data);

        file.Close();

        std::array<uint8_t, 2 * ExperimentFile::PacketLength> expected;
        expected.fill(0xFF);
        Writer w(expected);

        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);

        w.WriteByte(num(ExperimentFile::PID::Reserved));

        auto length = ExperimentFile::PacketLength - 3 - sizeof(uint64_t);

        for (uint32_t i = 0; i < length; ++i)
        {
            w.WriteByte(0xBC);
        }

        // second packet
        w.WriteByte(num(ExperimentFile::PID::Synchronization));
        w.WriteByte(num(ExperimentFile::PID::Timestamp));
        w.WriteQuadWordLE(65536);
        w.WriteByte(num(ExperimentFile::PID::Continuation));
        w.WriteByte(num(ExperimentFile::PID::Reserved));
        auto secondPacketLength = data.size() - length;
        for (uint32_t i = 0; i < secondPacketLength; ++i)
        {
            w.WriteByte(0xBC);
        }

        ASSERT_THAT(_buffer, Eq(expected));
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: statusbarwrapper.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2005-03-01 19:44:04 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <uielement/statusbarwrapper.hxx>

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
#ifndef __FRAMEWORK_HELPER_ACTIONTRIGGERHELPER_HXX_
#include <helper/actiontriggerhelper.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_
#include <uielement/constitemcontainer.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_
#include <uielement/rootitemcontainer.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_STATUSBAR_HXX_
#include <uielement/statusbar.hxx>
#endif
#include <helpid.hrc>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XSYSTEMDEPENDENTMENUPEER_HPP_
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XMENUBAR_HPP_
#include <com/sun/star/awt/XMenuBar.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_
#include <com/sun/star/ui/UIElementType.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/unohlp.hxx>
#endif

#include <tools/solar.h>
#include <vcl/svapp.hxx>
#include <rtl/logfile.hxx>

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::awt;
using namespace ::com::sun::star::ui;

namespace framework
{

StatusBarWrapper::StatusBarWrapper(
    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager
    )
:
    m_xServiceFactory( xServiceManager ),
    UIConfigElementWrapperBase( UIElementType::STATUSBAR )
{
}

StatusBarWrapper::~StatusBarWrapper()
{
}

const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& StatusBarWrapper::getServiceFactory()
{
    ResetableGuard aLock( m_aLock );
    if ( m_bDisposed )
        throw DisposedException();

    return m_xServiceFactory;
}

void SAL_CALL StatusBarWrapper::dispose() throw (::com::sun::star::uno::RuntimeException)
{
    Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );

    com::sun::star::lang::EventObject aEvent( xThis );
    m_aListenerContainer.disposeAndClear( aEvent );

    ResetableGuard aLock( m_aLock );
    if ( !m_bDisposed )
    {
        if ( m_xStatusBarManager.is() )
            m_xStatusBarManager->dispose();
        m_xStatusBarManager.clear();
        m_xConfigSource.clear();
        m_xConfigData.clear();
        m_xServiceFactory.clear();

        m_bDisposed = sal_True;
    }
    else
        throw DisposedException();
}

// XInitialization
void SAL_CALL StatusBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( !m_bInitialized )
    {
        UIConfigElementWrapperBase::initialize( aArguments );

        Reference< XFrame > xFrame( m_xWeakFrame );
        if ( xFrame.is() && m_xConfigSource.is() )
        {
            // Create VCL based toolbar which will be filled with settings data
            StatusBar*        pStatusBar( 0 );
            StatusBarManager* pStatusBarManager( 0 );
            {
                vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
                Window* pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
                if ( pWindow )
                {
                    ULONG nStyles = WinBits( WB_LEFT | WB_3DLOOK );

                    pStatusBar = new FrameworkStatusBar( pWindow, nStyles );
                    pStatusBarManager = new StatusBarManager( m_xServiceFactory, xFrame, m_aResourceURL, pStatusBar );
                    ((FrameworkStatusBar*)pStatusBar)->SetStatusBarManager( pStatusBarManager );
                    m_xStatusBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pStatusBarManager ), UNO_QUERY );
                    pStatusBar->SetUniqueId( HID_STATUSBAR );
                }
            }

            try
            {
                m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
                if ( m_xConfigData.is() && pStatusBar && pStatusBarManager )
                {
                    // Fill statusbar with container contents
                    pStatusBarManager->FillStatusBar( m_xConfigData );
                }
            }
            catch ( NoSuchElementException& )
            {
            }
        }
    }
}

// XUIElementSettings
void SAL_CALL StatusBarWrapper::updateSettings() throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( m_bPersistent &&
         m_xConfigSource.is() &&
         m_xStatusBarManager.is() )
    {
        try
        {
            StatusBarManager* pStatusBarManager = static_cast< StatusBarManager *>( m_xStatusBarManager.get() );

            m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
            if ( m_xConfigData.is() )
                pStatusBarManager->FillStatusBar( m_xConfigData );
        }
        catch ( NoSuchElementException& )
        {
        }
    }
}

void SAL_CALL StatusBarWrapper::setSettings( const Reference< XIndexAccess >& xSettings ) throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( xSettings.is() )
    {
        // Create a copy of the data if the container is not const
        Reference< XIndexReplace > xReplace( xSettings, UNO_QUERY );
        if ( xReplace.is() )
            m_xConfigData = Reference< XIndexAccess >( static_cast< OWeakObject * >( new ConstItemContainer( xSettings ) ), UNO_QUERY );
        else
            m_xConfigData = xSettings;

        if ( m_xConfigSource.is() && m_bPersistent )
        {
            OUString aResourceURL( m_aResourceURL );
            Reference< XUIConfigurationManager > xUICfgMgr( m_xConfigSource );

            aLock.unlock();

            try
            {
                xUICfgMgr->replaceSettings( aResourceURL, m_xConfigData );
            }
            catch( NoSuchElementException& )
            {
            }
        }
    }
}

Reference< XIndexAccess > SAL_CALL StatusBarWrapper::getSettings( sal_Bool bWriteable ) throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( bWriteable )
        return Reference< XIndexAccess >( static_cast< OWeakObject * >( new RootItemContainer( m_xConfigData ) ), UNO_QUERY );
    else
        return m_xConfigData;
}

Reference< XInterface > SAL_CALL StatusBarWrapper::getRealInterface() throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_xStatusBarManager.is() )
    {
        StatusBarManager* pStatusBarManager = static_cast< StatusBarManager *>( m_xStatusBarManager.get() );
        if ( pStatusBarManager )
        {
            Window* pWindow = (Window *)pStatusBarManager->GetStatusBar();
            if ( pWindow )
                return Reference< XInterface >( VCLUnoHelper::GetInterface( pWindow ), UNO_QUERY );
        }
    }

    return Reference< XInterface >();
}

} // namespace framework
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.128); FILE MERGED 2005/09/05 13:07:14 rt 1.3.128.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: statusbarwrapper.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 01:58:12 $
 *
 *  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
 *
 ************************************************************************/

#include <uielement/statusbarwrapper.hxx>

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
#ifndef __FRAMEWORK_HELPER_ACTIONTRIGGERHELPER_HXX_
#include <helper/actiontriggerhelper.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_
#include <uielement/constitemcontainer.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_
#include <uielement/rootitemcontainer.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_STATUSBAR_HXX_
#include <uielement/statusbar.hxx>
#endif
#include <helpid.hrc>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XSYSTEMDEPENDENTMENUPEER_HPP_
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XMENUBAR_HPP_
#include <com/sun/star/awt/XMenuBar.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_
#include <com/sun/star/ui/UIElementType.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/unohlp.hxx>
#endif

#include <tools/solar.h>
#include <vcl/svapp.hxx>
#include <rtl/logfile.hxx>

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::awt;
using namespace ::com::sun::star::ui;

namespace framework
{

StatusBarWrapper::StatusBarWrapper(
    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager
    )
:
    m_xServiceFactory( xServiceManager ),
    UIConfigElementWrapperBase( UIElementType::STATUSBAR )
{
}

StatusBarWrapper::~StatusBarWrapper()
{
}

const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& StatusBarWrapper::getServiceFactory()
{
    ResetableGuard aLock( m_aLock );
    if ( m_bDisposed )
        throw DisposedException();

    return m_xServiceFactory;
}

void SAL_CALL StatusBarWrapper::dispose() throw (::com::sun::star::uno::RuntimeException)
{
    Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );

    com::sun::star::lang::EventObject aEvent( xThis );
    m_aListenerContainer.disposeAndClear( aEvent );

    ResetableGuard aLock( m_aLock );
    if ( !m_bDisposed )
    {
        if ( m_xStatusBarManager.is() )
            m_xStatusBarManager->dispose();
        m_xStatusBarManager.clear();
        m_xConfigSource.clear();
        m_xConfigData.clear();
        m_xServiceFactory.clear();

        m_bDisposed = sal_True;
    }
    else
        throw DisposedException();
}

// XInitialization
void SAL_CALL StatusBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( !m_bInitialized )
    {
        UIConfigElementWrapperBase::initialize( aArguments );

        Reference< XFrame > xFrame( m_xWeakFrame );
        if ( xFrame.is() && m_xConfigSource.is() )
        {
            // Create VCL based toolbar which will be filled with settings data
            StatusBar*        pStatusBar( 0 );
            StatusBarManager* pStatusBarManager( 0 );
            {
                vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
                Window* pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
                if ( pWindow )
                {
                    ULONG nStyles = WinBits( WB_LEFT | WB_3DLOOK );

                    pStatusBar = new FrameworkStatusBar( pWindow, nStyles );
                    pStatusBarManager = new StatusBarManager( m_xServiceFactory, xFrame, m_aResourceURL, pStatusBar );
                    ((FrameworkStatusBar*)pStatusBar)->SetStatusBarManager( pStatusBarManager );
                    m_xStatusBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pStatusBarManager ), UNO_QUERY );
                    pStatusBar->SetUniqueId( HID_STATUSBAR );
                }
            }

            try
            {
                m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
                if ( m_xConfigData.is() && pStatusBar && pStatusBarManager )
                {
                    // Fill statusbar with container contents
                    pStatusBarManager->FillStatusBar( m_xConfigData );
                }
            }
            catch ( NoSuchElementException& )
            {
            }
        }
    }
}

// XUIElementSettings
void SAL_CALL StatusBarWrapper::updateSettings() throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( m_bPersistent &&
         m_xConfigSource.is() &&
         m_xStatusBarManager.is() )
    {
        try
        {
            StatusBarManager* pStatusBarManager = static_cast< StatusBarManager *>( m_xStatusBarManager.get() );

            m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
            if ( m_xConfigData.is() )
                pStatusBarManager->FillStatusBar( m_xConfigData );
        }
        catch ( NoSuchElementException& )
        {
        }
    }
}

void SAL_CALL StatusBarWrapper::setSettings( const Reference< XIndexAccess >& xSettings ) throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( xSettings.is() )
    {
        // Create a copy of the data if the container is not const
        Reference< XIndexReplace > xReplace( xSettings, UNO_QUERY );
        if ( xReplace.is() )
            m_xConfigData = Reference< XIndexAccess >( static_cast< OWeakObject * >( new ConstItemContainer( xSettings ) ), UNO_QUERY );
        else
            m_xConfigData = xSettings;

        if ( m_xConfigSource.is() && m_bPersistent )
        {
            OUString aResourceURL( m_aResourceURL );
            Reference< XUIConfigurationManager > xUICfgMgr( m_xConfigSource );

            aLock.unlock();

            try
            {
                xUICfgMgr->replaceSettings( aResourceURL, m_xConfigData );
            }
            catch( NoSuchElementException& )
            {
            }
        }
    }
}

Reference< XIndexAccess > SAL_CALL StatusBarWrapper::getSettings( sal_Bool bWriteable ) throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( bWriteable )
        return Reference< XIndexAccess >( static_cast< OWeakObject * >( new RootItemContainer( m_xConfigData ) ), UNO_QUERY );
    else
        return m_xConfigData;
}

Reference< XInterface > SAL_CALL StatusBarWrapper::getRealInterface() throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_xStatusBarManager.is() )
    {
        StatusBarManager* pStatusBarManager = static_cast< StatusBarManager *>( m_xStatusBarManager.get() );
        if ( pStatusBarManager )
        {
            Window* pWindow = (Window *)pStatusBarManager->GetStatusBar();
            if ( pWindow )
                return Reference< XInterface >( VCLUnoHelper::GetInterface( pWindow ), UNO_QUERY );
        }
    }

    return Reference< XInterface >();
}

} // namespace framework
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2018-2019 Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
 */
#if !DEVICE_WATCHDOG
#error [NOT_SUPPORTED] Watchdog not supported for this target
#else

#include "greentea-client/test_env.h"
#include "hal/watchdog_api.h"
#include "unity/unity.h"
#include "us_ticker_api.h"
#include "utest/utest.h"
#include "watchdog_timing_tests.h"
#include "mbed.h"

#define TIMEOUT_LOWER_LIMIT_MS 1000ULL

// A window to allow to process watchdog kick before timeout occurs.
#define TIME_WINDOW_MS 2UL

#define MSG_VALUE_DUMMY "0"
#define CASE_DATA_INVALID 0xffffffffUL
#define CASE_DATA_PHASE2_OK 0xfffffffeUL

#define MSG_VALUE_LEN 24
#define MSG_KEY_LEN 24

#define MSG_KEY_DEVICE_READY "ready"
#define MSG_KEY_START_CASE "start_case"
#define MSG_KEY_HEARTBEAT "hb"
#define MSG_KEY_DEVICE_RESET "dev_reset"

using utest::v1::Case;
using utest::v1::Specification;
using utest::v1::Harness;

struct testcase_data {
    int index;
    int start_index;
    uint32_t received_data;
};

testcase_data current_case;

bool send_reset_notification(testcase_data *tcdata, uint32_t delay_ms)
{
    char msg_value[12];
    int str_len = snprintf(msg_value, sizeof msg_value, "%02x,%08lx", tcdata->start_index + tcdata->index, delay_ms);
    if (str_len != (sizeof msg_value) - 1) {
        utest_printf("Failed to compose a value string to be sent to host.");
        return false;
    }
    greentea_send_kv(MSG_KEY_DEVICE_RESET, msg_value);
    return true;
}

template<uint32_t timeout_ms>
void test_timing()
{
    watchdog_features_t features = hal_watchdog_get_platform_features();
    if (timeout_ms > features.max_timeout) {
        TEST_IGNORE_MESSAGE("Requested timeout value not supported for this target -- ignoring test case.");
        return;
    }

    // Phase 2. -- verify the test results.
    // Verify the heartbeat time span sent by host is within given range:
    // 1. The watchdog should trigger at, or after the timeout value.
    // 2. The watchdog should trigger before twice the timeout value.
    if (current_case.received_data != CASE_DATA_INVALID) {
        // Provided the watchdog works as expected, the last timestamp received
        // by the host will always be before the expected reset time. Because
        // of that, the constraint no 1. is not verified.
        TEST_ASSERT(current_case.received_data > 0);
        TEST_ASSERT(current_case.received_data < 2 * timeout_ms);
        current_case.received_data = CASE_DATA_INVALID;
        return;
    }

    // Phase 1. -- run the test code.
    // Send heartbeat messages to host until the watchdeg resets the device.
    const ticker_data_t *const us_ticker = get_us_ticker_data();
    us_timestamp_t current_ts, next_ts, expected_reset_ts, divider, ts_increment;
    char msg_value[12];

    watchdog_config_t config = { timeout_ms };
    TEST_ASSERT_EQUAL(WATCHDOG_STATUS_OK, hal_watchdog_init(&config));
    next_ts = ticker_read_us(us_ticker);
    expected_reset_ts = next_ts + 1000ULL * timeout_ms;

    divider = 0x2ULL;
    while (1) {
        current_ts = ticker_read_us(us_ticker);
        if (current_ts < next_ts) {
            continue;
        }

        int str_len = snprintf(msg_value, sizeof msg_value, "%02x,%08lx", current_case.start_index + current_case.index,
                               (uint32_t) current_ts);
        if (str_len != (sizeof msg_value) - 1) {
            utest_printf("Failed to compose a value string to be sent to host.");
            return;
        }
        greentea_send_kv(MSG_KEY_HEARTBEAT, msg_value);

        // The closer to expected reset, the smaller heartbeat time difference.
        // This should reduce measurement error present for heartbeat with
        // equal periods.
        ts_increment = (1000ULL * timeout_ms / divider);
        next_ts += ts_increment;

        if (current_ts <= expected_reset_ts) {
            divider <<= 1;
        } else if (divider > 0x2ULL) {
            divider >>= 1;
        }
    }
}

void test_timeout_lower_limit()
{
    watchdog_features_t features = hal_watchdog_get_platform_features();
    if (TIMEOUT_LOWER_LIMIT_MS > features.max_timeout) {
        TEST_IGNORE_MESSAGE("Requested timeout value not supported for this target -- ignoring test case.");
        return;
    }

    // Phase 2. -- verify the test results.
    if (current_case.received_data != CASE_DATA_INVALID) {
        TEST_ASSERT_EQUAL(CASE_DATA_PHASE2_OK, current_case.received_data);
        current_case.received_data = CASE_DATA_INVALID;
        return;
    }

    // Phase 1. -- run the test code.
    watchdog_config_t config = { TIMEOUT_LOWER_LIMIT_MS };
    uint32_t sleep_time_ms = (TIMEOUT_LOWER_LIMIT_MS * features.clock_typical_frequency / features.clock_max_frequency) - TIME_WINDOW_MS;
    TEST_ASSERT_EQUAL(WATCHDOG_STATUS_OK, hal_watchdog_init(&config));

    // Kick watchdog before timeout.
    // Watchdog should not trigger before timeout * clock accuracy.
    // If device restarts while waiting for the kick, test fails.

    ThisThread::sleep_for(sleep_time_ms);
    hal_watchdog_kick();

    if (send_reset_notification(&current_case, 2 * TIMEOUT_LOWER_LIMIT_MS) == false) {
        TEST_ASSERT_MESSAGE(0, "Dev-host communication error.");
        return;
    }
    hal_watchdog_kick();

    // Watchdog should fire before twice the timeout value.
    ThisThread::sleep_for(2 * TIMEOUT_LOWER_LIMIT_MS);

    // Watchdog reset should have occurred during that wait() above;

    hal_watchdog_kick();  // Just to buy some time for testsuite failure handling.
    TEST_ASSERT_MESSAGE(0, "Watchdog did not reset the device as expected.");
}

utest::v1::status_t case_setup(const Case *const source, const size_t index_of_case)
{
    current_case.index = index_of_case;
    return utest::v1::greentea_case_setup_handler(source, index_of_case);
}

int testsuite_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(90, "watchdog_reset");
    utest::v1::status_t status = utest::v1::greentea_test_setup_handler(number_of_cases);
    if (status != utest::v1::STATUS_CONTINUE) {
        return status;
    }

    char key[MSG_KEY_LEN + 1] = { };
    char value[MSG_VALUE_LEN + 1] = { };

    greentea_send_kv(MSG_KEY_DEVICE_READY, MSG_VALUE_DUMMY);
    greentea_parse_kv(key, value, MSG_KEY_LEN, MSG_VALUE_LEN);

    if (strcmp(key, MSG_KEY_START_CASE) != 0) {
        utest_printf("Invalid message key.\n");
        return utest::v1::STATUS_ABORT;
    }

    int num_args = sscanf(value, "%02x,%08lx", &(current_case.start_index), &(current_case.received_data));
    if (num_args == 0 || num_args == EOF) {
        utest_printf("Invalid data received from host\n");
        return utest::v1::STATUS_ABORT;
    }

    utest_printf("This test suite is composed of %i test cases. Starting at index %i.\n", number_of_cases,
                 current_case.start_index);
    return current_case.start_index;
}

Case cases[] = {
    Case("Timing, 200 ms", case_setup, test_timing<200UL>),
    Case("Timing, 500 ms", case_setup, test_timing<500UL>),
    Case("Timing, 1000 ms", case_setup, test_timing<1000UL>),
    Case("Timing, 3000 ms", case_setup, test_timing<3000UL>),
    Case("timeout accuracy", case_setup, test_timeout_lower_limit)
};

Specification specification((utest::v1::test_setup_handler_t) testsuite_setup, cases);

int main()
{
    // Harness will start with a test case index provided by host script.
    return !Harness::run(specification);
}

#endif // !DEVICE_WATCHDOG
<commit_msg>Prevent sleep during watchdog lower limit test<commit_after>/*
 * Copyright (c) 2018-2019 Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
 */
#if !DEVICE_WATCHDOG
#error [NOT_SUPPORTED] Watchdog not supported for this target
#else

#include "greentea-client/test_env.h"
#include "hal/watchdog_api.h"
#include "unity/unity.h"
#include "us_ticker_api.h"
#include "utest/utest.h"
#include "watchdog_timing_tests.h"
#include "mbed.h"

#define TIMEOUT_LOWER_LIMIT_MS 1000ULL

// A window to allow to process watchdog kick before timeout occurs.
#define TIME_WINDOW_MS 2UL

#define MSG_VALUE_DUMMY "0"
#define CASE_DATA_INVALID 0xffffffffUL
#define CASE_DATA_PHASE2_OK 0xfffffffeUL

#define MSG_VALUE_LEN 24
#define MSG_KEY_LEN 24

#define MSG_KEY_DEVICE_READY "ready"
#define MSG_KEY_START_CASE "start_case"
#define MSG_KEY_HEARTBEAT "hb"
#define MSG_KEY_DEVICE_RESET "dev_reset"

using utest::v1::Case;
using utest::v1::Specification;
using utest::v1::Harness;

struct testcase_data {
    int index;
    int start_index;
    uint32_t received_data;
};

testcase_data current_case;

bool send_reset_notification(testcase_data *tcdata, uint32_t delay_ms)
{
    char msg_value[12];
    int str_len = snprintf(msg_value, sizeof msg_value, "%02x,%08lx", tcdata->start_index + tcdata->index, delay_ms);
    if (str_len != (sizeof msg_value) - 1) {
        utest_printf("Failed to compose a value string to be sent to host.");
        return false;
    }
    greentea_send_kv(MSG_KEY_DEVICE_RESET, msg_value);
    return true;
}

template<uint32_t timeout_ms>
void test_timing()
{
    watchdog_features_t features = hal_watchdog_get_platform_features();
    if (timeout_ms > features.max_timeout) {
        TEST_IGNORE_MESSAGE("Requested timeout value not supported for this target -- ignoring test case.");
        return;
    }

    // Phase 2. -- verify the test results.
    // Verify the heartbeat time span sent by host is within given range:
    // 1. The watchdog should trigger at, or after the timeout value.
    // 2. The watchdog should trigger before twice the timeout value.
    if (current_case.received_data != CASE_DATA_INVALID) {
        // Provided the watchdog works as expected, the last timestamp received
        // by the host will always be before the expected reset time. Because
        // of that, the constraint no 1. is not verified.
        TEST_ASSERT(current_case.received_data > 0);
        TEST_ASSERT(current_case.received_data < 2 * timeout_ms);
        current_case.received_data = CASE_DATA_INVALID;
        return;
    }

    // Phase 1. -- run the test code.
    // Send heartbeat messages to host until the watchdeg resets the device.
    const ticker_data_t *const us_ticker = get_us_ticker_data();
    us_timestamp_t current_ts, next_ts, expected_reset_ts, divider, ts_increment;
    char msg_value[12];

    watchdog_config_t config = { timeout_ms };
    TEST_ASSERT_EQUAL(WATCHDOG_STATUS_OK, hal_watchdog_init(&config));
    next_ts = ticker_read_us(us_ticker);
    expected_reset_ts = next_ts + 1000ULL * timeout_ms;

    divider = 0x2ULL;
    while (1) {
        current_ts = ticker_read_us(us_ticker);
        if (current_ts < next_ts) {
            continue;
        }

        int str_len = snprintf(msg_value, sizeof msg_value, "%02x,%08lx", current_case.start_index + current_case.index,
                               (uint32_t) current_ts);
        if (str_len != (sizeof msg_value) - 1) {
            utest_printf("Failed to compose a value string to be sent to host.");
            return;
        }
        greentea_send_kv(MSG_KEY_HEARTBEAT, msg_value);

        // The closer to expected reset, the smaller heartbeat time difference.
        // This should reduce measurement error present for heartbeat with
        // equal periods.
        ts_increment = (1000ULL * timeout_ms / divider);
        next_ts += ts_increment;

        if (current_ts <= expected_reset_ts) {
            divider <<= 1;
        } else if (divider > 0x2ULL) {
            divider >>= 1;
        }
    }
}

void test_timeout_lower_limit()
{
    watchdog_features_t features = hal_watchdog_get_platform_features();
    if (TIMEOUT_LOWER_LIMIT_MS > features.max_timeout) {
        TEST_IGNORE_MESSAGE("Requested timeout value not supported for this target -- ignoring test case.");
        return;
    }

    // Phase 2. -- verify the test results.
    if (current_case.received_data != CASE_DATA_INVALID) {
        TEST_ASSERT_EQUAL(CASE_DATA_PHASE2_OK, current_case.received_data);
        current_case.received_data = CASE_DATA_INVALID;
        return;
    }

    // Phase 1. -- run the test code.
    watchdog_config_t config = { TIMEOUT_LOWER_LIMIT_MS };
    uint32_t sleep_time_ms = (TIMEOUT_LOWER_LIMIT_MS * features.clock_typical_frequency / features.clock_max_frequency) - TIME_WINDOW_MS;
    TEST_ASSERT_EQUAL(WATCHDOG_STATUS_OK, hal_watchdog_init(&config));

    // Kick watchdog before timeout.
    // Watchdog should not trigger before timeout * clock accuracy.
    // If device restarts while waiting for the kick, test fails.

    wait_us(sleep_time_ms * 1000);
    hal_watchdog_kick();

    if (send_reset_notification(&current_case, 2 * TIMEOUT_LOWER_LIMIT_MS) == false) {
        TEST_ASSERT_MESSAGE(0, "Dev-host communication error.");
        return;
    }
    hal_watchdog_kick();

    // Watchdog should fire before twice the timeout value.
    wait_us(2 * TIMEOUT_LOWER_LIMIT_MS * 1000);

    // Watchdog reset should have occurred during that wait() above;

    hal_watchdog_kick();  // Just to buy some time for testsuite failure handling.
    TEST_ASSERT_MESSAGE(0, "Watchdog did not reset the device as expected.");
}

utest::v1::status_t case_setup(const Case *const source, const size_t index_of_case)
{
    current_case.index = index_of_case;
    return utest::v1::greentea_case_setup_handler(source, index_of_case);
}

int testsuite_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(90, "watchdog_reset");
    utest::v1::status_t status = utest::v1::greentea_test_setup_handler(number_of_cases);
    if (status != utest::v1::STATUS_CONTINUE) {
        return status;
    }

    char key[MSG_KEY_LEN + 1] = { };
    char value[MSG_VALUE_LEN + 1] = { };

    greentea_send_kv(MSG_KEY_DEVICE_READY, MSG_VALUE_DUMMY);
    greentea_parse_kv(key, value, MSG_KEY_LEN, MSG_VALUE_LEN);

    if (strcmp(key, MSG_KEY_START_CASE) != 0) {
        utest_printf("Invalid message key.\n");
        return utest::v1::STATUS_ABORT;
    }

    int num_args = sscanf(value, "%02x,%08lx", &(current_case.start_index), &(current_case.received_data));
    if (num_args == 0 || num_args == EOF) {
        utest_printf("Invalid data received from host\n");
        return utest::v1::STATUS_ABORT;
    }

    utest_printf("This test suite is composed of %i test cases. Starting at index %i.\n", number_of_cases,
                 current_case.start_index);
    return current_case.start_index;
}

Case cases[] = {
    Case("Timing, 200 ms", case_setup, test_timing<200UL>),
    Case("Timing, 500 ms", case_setup, test_timing<500UL>),
    Case("Timing, 1000 ms", case_setup, test_timing<1000UL>),
    Case("Timing, 3000 ms", case_setup, test_timing<3000UL>),
    Case("timeout accuracy", case_setup, test_timeout_lower_limit)
};

Specification specification((utest::v1::test_setup_handler_t) testsuite_setup, cases);

int main()
{
    // Harness will start with a test case index provided by host script.
    return !Harness::run(specification);
}

#endif // !DEVICE_WATCHDOG
<|endoftext|>


<commit_before>/**
* @file GameSymbols.cpp
*
* @author Heinrich Mellmann
* Implementation of class GameSymbols
*/

#include "GameSymbols.h"

using namespace naoth;
using namespace std;

void GameSymbols::registerSymbols(xabsl::Engine& engine)
{
  // enum type for team color
  for(int i = 0; i < GameData::numOfTeamColor; i++)
  {
    string str("game.team_color");
    str.append(GameData::teamColorToString((GameData::TeamColor)i));
    engine.registerEnumElement("game.team_color", str.c_str(), i);
  }//end for

  engine.registerEnumeratedInputSymbol("game.own_team_color", "game.team_color", &getOwnTeamColor);
  engine.registerEnumeratedInputSymbol("game.opponent_team_color", "game.team_color", &getOpponentTeamColor);

  // enum type for game state (spl)
  for(int i = 0; i < GameData::numOfGameState; i++)
  {
    string str("game.state.");
    if(i == (int)GameData::initial)
    {
      str.append("_");
      str.append(GameData::gameStateToString((GameData::GameState)i));
      str.append("_");
    } else {
      str.append(GameData::gameStateToString((GameData::GameState)i));
    }
    engine.registerEnumElement("game.state", str.c_str(), i);
  }//end for

  // current game state
  // (int*)&getPlayerInfo().gameData.gameState
  engine.registerEnumeratedInputSymbol("game.state", "game.state", &getGameState);

  // enum type for play mode (simulation)
  for(int i = 0; i < GameData::numOfPlayMode; i++)
  {
    string str("game.playmode.");
    //str.append(playerInfo.getPlayModeName((GameData::PlayMode)i));
    str.append(GameData::playModeToString((GameData::PlayMode)i));
    engine.registerEnumElement("game.playmode", str.c_str(), i);
  }//end for

  // register the play mode
  // (int*)&playerInfo.playMode
  engine.registerEnumeratedInputSymbol("game.playmode", "game.playmode", &getPlayMode);

  engine.registerDecimalInputSymbol("game.player_number", &getPlayerNumber);
  engine.registerDecimalInputSymbol("game.msecsRemaining", &getMsecsRemaining);
  engine.registerBooleanInputSymbol("game.own_kickoff", &getOwnKickOff);

}//end registerSymbols

GameSymbols* GameSymbols::theInstance = NULL;

bool GameSymbols::getOwnKickOff()
{
  return theInstance->getPlayerInfo().gameData.playMode == GameData::kick_off_own
      || theInstance->getPlayerInfo().gameData.playMode == GameData::penalty_kick_own;
}

double GameSymbols::getPlayerNumber() {
  return theInstance->getPlayerInfo().gameData.playerNumber;
}

double GameSymbols::getMsecsRemaining() {
  return theInstance->getPlayerInfo().gameData.msecsRemaining;
}

int GameSymbols::getGameState() {
  return theInstance->getPlayerInfo().gameData.gameState;
}

int GameSymbols::getPlayMode() {
  return theInstance->getPlayerInfo().gameData.playMode;
}

int GameSymbols::getOwnTeamColor() {
  return theInstance->getPlayerInfo().gameData.teamColor;
}

int GameSymbols::getOpponentTeamColor() {
  return !(theInstance->getPlayerInfo().gameData.teamColor);
}
<commit_msg>cleanup + test push<commit_after>/**
* @file GameSymbols.cpp
*
* @author Heinrich Mellmann
* Implementation of class GameSymbols
*/

#include "GameSymbols.h"

using namespace naoth;
using namespace std;

void GameSymbols::registerSymbols(xabsl::Engine& engine)
{
  // enum type for team color
  for(int i = 0; i < GameData::numOfTeamColor; i++)
  {
    string str("game.team_color");
    str.append(GameData::teamColorToString((GameData::TeamColor)i));
    engine.registerEnumElement("game.team_color", str.c_str(), i);
  }

  engine.registerEnumeratedInputSymbol("game.own_team_color", "game.team_color", &getOwnTeamColor);
  engine.registerEnumeratedInputSymbol("game.opponent_team_color", "game.team_color", &getOpponentTeamColor);

  // enum type for game state (spl)
  for(int i = 0; i < GameData::numOfGameState; i++)
  {
    string str("game.state.");
    if(i == (int)GameData::initial)
    {
      str.append("_");
      str.append(GameData::gameStateToString((GameData::GameState)i));
      str.append("_");
    } else {
      str.append(GameData::gameStateToString((GameData::GameState)i));
    }
    engine.registerEnumElement("game.state", str.c_str(), i);
  }//end for

  // current game state
  // (int*)&getPlayerInfo().gameData.gameState
  engine.registerEnumeratedInputSymbol("game.state", "game.state", &getGameState);

  // enum type for play mode (simulation)
  for(int i = 0; i < GameData::numOfPlayMode; i++)
  {
    string str("game.playmode.");
    //str.append(playerInfo.getPlayModeName((GameData::PlayMode)i));
    str.append(GameData::playModeToString((GameData::PlayMode)i));
    engine.registerEnumElement("game.playmode", str.c_str(), i);
  }

  // register the play mode
  // (int*)&playerInfo.playMode
  engine.registerEnumeratedInputSymbol("game.playmode", "game.playmode", &getPlayMode);

  engine.registerDecimalInputSymbol("game.player_number", &getPlayerNumber);
  engine.registerDecimalInputSymbol("game.msecsRemaining", &getMsecsRemaining);
  engine.registerBooleanInputSymbol("game.own_kickoff", &getOwnKickOff);

}//end registerSymbols

GameSymbols* GameSymbols::theInstance = NULL;

bool GameSymbols::getOwnKickOff()
{
  return theInstance->getPlayerInfo().gameData.playMode == GameData::kick_off_own
      || theInstance->getPlayerInfo().gameData.playMode == GameData::penalty_kick_own;
}

double GameSymbols::getPlayerNumber() {
  return theInstance->getPlayerInfo().gameData.playerNumber;
}

double GameSymbols::getMsecsRemaining() {
  return theInstance->getPlayerInfo().gameData.msecsRemaining;
}

int GameSymbols::getGameState() {
  return theInstance->getPlayerInfo().gameData.gameState;
}

int GameSymbols::getPlayMode() {
  return theInstance->getPlayerInfo().gameData.playMode;
}

int GameSymbols::getOwnTeamColor() {
  return theInstance->getPlayerInfo().gameData.teamColor;
}

int GameSymbols::getOpponentTeamColor() {
  return !(theInstance->getPlayerInfo().gameData.teamColor);
}
<|endoftext|>


<commit_before>//
// Name:		BuildingDlg.cpp
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "BuildingDlg.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtlib/vtlib.h"
#include "vtlib/core/Terrain.h"
#include "BuildingDlg3d.h"
#include "../Enviro.h"	// for GetCurrentTerrain
#include "vtlib/core/Building3d.h"

extern void EnableContinuousRendering(bool bTrue);

// WDR: class implementations

//----------------------------------------------------------------------------
// BuildingDlg3d
//----------------------------------------------------------------------------

BuildingDlg3d::BuildingDlg3d( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	BuildingDlg( parent, id, title, position, size, style )
{
}

void BuildingDlg3d::Setup(vtBuilding3d *bld3d)
{
	vtTerrain *pTerr = GetCurrentTerrain();
	m_pStructure3d = bld3d;
	m_pSA = &pTerr->GetStructures();
	m_pBuilding = bld3d;
}

void BuildingDlg3d::OnOK( wxCommandEvent &event )
{
	BuildingDlg::OnOK(event);

	vtTerrain *pTerr = GetCurrentTerrain();
	pTerr->GetStructures().ConstructStructure(m_pStructure3d);
}

void BuildingDlg3d::EnableRendering(bool bEnable)
{
	EnableContinuousRendering(bEnable);
}

void BuildingDlg3d::Modified()
{
	vtTerrain *pTerr = GetCurrentTerrain();
	pTerr->GetStructures().ConstructStructure(m_pStructure3d);
}
<commit_msg>fixed gcc #pragma<commit_after>//
// Name:		BuildingDlg3d.cpp
//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
	#pragma implementation "BuildingDlg3d.cpp"
#endif

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtlib/vtlib.h"
#include "vtlib/core/Terrain.h"
#include "BuildingDlg3d.h"
#include "../Enviro.h"	// for GetCurrentTerrain
#include "vtlib/core/Building3d.h"

extern void EnableContinuousRendering(bool bTrue);

// WDR: class implementations

//----------------------------------------------------------------------------
// BuildingDlg3d
//----------------------------------------------------------------------------

BuildingDlg3d::BuildingDlg3d( wxWindow *parent, wxWindowID id, const wxString &title,
	const wxPoint &position, const wxSize& size, long style ) :
	BuildingDlg( parent, id, title, position, size, style )
{
}

void BuildingDlg3d::Setup(vtBuilding3d *bld3d)
{
	vtTerrain *pTerr = GetCurrentTerrain();
	m_pStructure3d = bld3d;
	m_pSA = &pTerr->GetStructures();
	m_pBuilding = bld3d;
}

void BuildingDlg3d::OnOK( wxCommandEvent &event )
{
	BuildingDlg::OnOK(event);

	vtTerrain *pTerr = GetCurrentTerrain();
	pTerr->GetStructures().ConstructStructure(m_pStructure3d);
}

void BuildingDlg3d::EnableRendering(bool bEnable)
{
	EnableContinuousRendering(bEnable);
}

void BuildingDlg3d::Modified()
{
	vtTerrain *pTerr = GetCurrentTerrain();
	pTerr->GetStructures().ConstructStructure(m_pStructure3d);
}
<|endoftext|>