<commit_before>#include <config.h>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/stuff/fem/functions/integrals.hh>
#include <dune/stuff/common/profiler.hh>
#include <sstream>

#include "dune/multiscale/msfem/msfem_traits.hh"
#include "coarse_scale_operator.hh"

namespace Dune {
namespace Multiscale {
namespace MsFEM {

CoarseScaleOperator::CoarseScaleOperator(const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace,
                                         LocalGridList& subgrid_list, const CommonTraits::DiffusionType& diffusion_op)
  : coarseDiscreteFunctionSpace_(coarseDiscreteFunctionSpace)
  , subgrid_list_(subgrid_list)
  , diffusion_operator_(diffusion_op)
  , petrovGalerkin_(false)
  , global_matrix_("MsFEM stiffness matrix", coarseDiscreteFunctionSpace_, coarseDiscreteFunctionSpace_)
  , cached_(false) {
  // the local problem:
  // Let 'T' denote a coarse grid element and
  // let 'U(T)' denote the environment of 'T' that corresponds with the subgrid.

  // if Petrov-Galerkin-MsFEM
  if (petrovGalerkin_)
    DSC_LOG_DEBUG << "Assembling Petrov-Galerkin-MsFEM Matrix." << std::endl;
  else // if classical (symmetric) MsFEM
    DSC_LOG_DEBUG << "Assembling MsFEM Matrix." << std::endl;

  //!TODO diagonal stencil reicht
  global_matrix_.reserve(DSFe::diagonalAndNeighborStencil(global_matrix_));
  global_matrix_.clear();

  Fem::DomainDecomposedIteratorStorage<CommonTraits::GridPartType> threadIterators(
      coarseDiscreteFunctionSpace_.gridPart());

  const bool is_simplex_grid = DSG::is_simplex_grid(coarseDiscreteFunctionSpace_);

#ifdef _OPENMP
#pragma omp parallel
#endif
  {
    for (const auto& coarse_grid_entity : threadIterators) {
      int cacheCounter = 0;
      const auto& coarse_grid_geometry = coarse_grid_entity.geometry();
      assert(coarse_grid_entity.partitionType() == InteriorEntity);

      DSFe::LocalMatrixProxy<MatrixType> local_matrix(global_matrix_, coarse_grid_entity, coarse_grid_entity);

      const auto& coarse_grid_baseSet = local_matrix.domainBasisFunctionSet();
      const auto numMacroBaseFunctions = coarse_grid_baseSet.size();

      Multiscale::MsFEM::LocalSolutionManager localSolutionManager(coarseDiscreteFunctionSpace_,
                                                                   coarse_grid_entity,
                                                                   subgrid_list_);
      localSolutionManager.load();
      const auto& localSolutions = localSolutionManager.getLocalSolutions();
      assert(localSolutions.size() > 0);

      for (const auto& localGridEntity : localSolutionManager.space()) {
        // ignore overlay elements
        if (subgrid_list_.covers(coarse_grid_entity, localGridEntity)) {
          const auto& local_grid_geometry = localGridEntity.geometry();

          // higher order quadrature, since A^{\epsilon} is highly variable
          const auto localQuadrature = DSFe::make_quadrature(localGridEntity, localSolutionManager.space());
          const auto numQuadraturePoints = localQuadrature.nop();

          // number of local solutions without the boundary correctors. Those are only needed for the right hand side
          const auto numLocalSolutions = localSolutions.size() - localSolutionManager.numBoundaryCorrectors();
          // evaluate the jacobians of all local solutions in all quadrature points
          std::vector<std::vector<JacobianRangeType>> allLocalSolutionEvaluations(
              numLocalSolutions, std::vector<JacobianRangeType>(localQuadrature.nop(), JacobianRangeType(0.0)));
          for (auto lsNum : DSC::valueRange(numLocalSolutions)) {
            auto& sll = localSolutions[lsNum];
            assert(sll.get());
            assert(sll->dofsValid());
            assert(localSolutionManager.space().indexSet().contains(localGridEntity));
            auto localFunction = sll->localFunction(localGridEntity);
            localFunction.evaluateQuadrature(localQuadrature, allLocalSolutionEvaluations[lsNum]);
          }

          for (size_t localQuadraturePoint = 0; localQuadraturePoint < numQuadraturePoints; ++localQuadraturePoint) {
            // local (barycentric) coordinates (with respect to entity)
            const auto& local_subgrid_point = localQuadrature.point(localQuadraturePoint);

            auto global_point_in_U_T = local_grid_geometry.global(local_subgrid_point);
            const double weight_local_quadrature = localQuadrature.weight(localQuadraturePoint) *
                                                   local_grid_geometry.integrationElement(local_subgrid_point);

            // evaluate the jacobian of the coarse grid base set
            const auto& local_coarse_point = coarse_grid_geometry.local(global_point_in_U_T);
            if (!cached_) {
              coarseBaseJacs_.push_back(std::vector<JacobianRangeType>(numMacroBaseFunctions, 0.0));
              coarse_grid_baseSet.jacobianAll(local_coarse_point, coarseBaseJacs_[cacheCounter]);
            }

            for (unsigned int i = 0; i < numMacroBaseFunctions; ++i) {
              for (unsigned int j = 0; j < numMacroBaseFunctions; ++j) {
                RangeType local_integral(0.0);

                // Compute the gradients of the i'th and j'th local problem solutions
                JacobianRangeType gradLocProbSoli(0.0), gradLocProbSolj(0.0);
                if (is_simplex_grid) {
                  assert(allLocalSolutionEvaluations.size() == CommonTraits::GridType::dimension);
                  // ∇ Phi_H + ∇ Q( Phi_H ) = ∇ Phi_H + ∂_x1 Phi_H ∇Q( e_1 ) + ∂_x2 Phi_H ∇Q( e_2 )
                  for (int k = 0; k < CommonTraits::GridType::dimension; ++k) {
                    gradLocProbSoli.axpy(coarseBaseJacs_[cacheCounter][i][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
                    gradLocProbSolj.axpy(coarseBaseJacs_[cacheCounter][j][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
                  }
                } else {
                  assert(allLocalSolutionEvaluations.size() == numMacroBaseFunctions);
                  gradLocProbSoli = allLocalSolutionEvaluations[i][localQuadraturePoint];
                  gradLocProbSolj = allLocalSolutionEvaluations[j][localQuadraturePoint];
                }

                JacobianRangeType reconstructionGradPhii(coarseBaseJacs_[cacheCounter][i]);
                reconstructionGradPhii += gradLocProbSoli;
                JacobianRangeType reconstructionGradPhij(coarseBaseJacs_[cacheCounter][j]);
                reconstructionGradPhij += gradLocProbSolj;
                JacobianRangeType diffusive_flux(0.0);
                diffusion_operator_.diffusiveFlux(global_point_in_U_T, reconstructionGradPhii, diffusive_flux);
                if (petrovGalerkin_)
                  local_integral += weight_local_quadrature * (diffusive_flux[0] * coarseBaseJacs_[cacheCounter][j][0]);
                else
                  local_integral += weight_local_quadrature * (diffusive_flux[0] * reconstructionGradPhij[0]);

                // add entries
                local_matrix.add(j, i, local_integral);
              }
            }

            ++cacheCounter;
          }
        }
      }
      // cache was filled;
      cached_ = true;
    } // for
  }   // omp region

  // set unit rows for dirichlet dofs
  Dune::Multiscale::getConstraintsCoarse(coarseDiscreteFunctionSpace_).applyToOperator(global_matrix_);
  global_matrix_.communicate();
}

void CoarseScaleOperator::apply_inverse(const CoarseScaleOperator::CoarseDiscreteFunction& rhs,
                                        CoarseScaleOperator::CoarseDiscreteFunction& solution) {
  BOOST_ASSERT_MSG(rhs.dofsValid(), "Coarse scale RHS DOFs need to be valid!");
  DSC_PROFILER.startTiming("msfem.solveCoarse");
  const typename BackendChooser<CoarseDiscreteFunctionSpace>::InverseOperatorType inverse(
      global_matrix_, 1e-8, 1e-8, DSC_CONFIG_GET("msfem.solver.iterations", rhs.size()),
      DSC_CONFIG_GET("msfem.solver.verbose", false), "bcgs",
      DSC_CONFIG_GET("msfem.solver.preconditioner_type", std::string("sor")));
  inverse(rhs, solution);
  if (!solution.dofsValid())
    DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!");
  DSC_PROFILER.stopTiming("msfem.solveCoarse");
  DSC_LOG_DEBUG << "Time to solve coarse MsFEM problem: " << DSC_PROFILER.getTiming("msfem.solveCoarse") << "ms."
               << std::endl;
} // constructor

} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<commit_msg>Doc cleanup<commit_after>#include <config.h>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/stuff/fem/functions/integrals.hh>
#include <dune/stuff/common/profiler.hh>
#include <sstream>

#include "dune/multiscale/msfem/msfem_traits.hh"
#include "coarse_scale_operator.hh"

namespace Dune {
namespace Multiscale {
namespace MsFEM {

CoarseScaleOperator::CoarseScaleOperator(const CoarseDiscreteFunctionSpace& coarseDiscreteFunctionSpace,
                                         LocalGridList& subgrid_list, const CommonTraits::DiffusionType& diffusion_op)
  : coarseDiscreteFunctionSpace_(coarseDiscreteFunctionSpace)
  , subgrid_list_(subgrid_list)
  , diffusion_operator_(diffusion_op)
  , petrovGalerkin_(false)
  , global_matrix_("MsFEM stiffness matrix", coarseDiscreteFunctionSpace_, coarseDiscreteFunctionSpace_)
  , cached_(false) {

  //!TODO diagonal stencil reicht
  global_matrix_.reserve(DSFe::diagonalAndNeighborStencil(global_matrix_));
  global_matrix_.clear();

  Fem::DomainDecomposedIteratorStorage<CommonTraits::GridPartType> threadIterators(
      coarseDiscreteFunctionSpace_.gridPart());

  const bool is_simplex_grid = DSG::is_simplex_grid(coarseDiscreteFunctionSpace_);

#ifdef _OPENMP
#pragma omp parallel
#endif
  {
    for (const auto& coarse_grid_entity : threadIterators) {
      int cacheCounter = 0;
      const auto& coarse_grid_geometry = coarse_grid_entity.geometry();
      assert(coarse_grid_entity.partitionType() == InteriorEntity);

      DSFe::LocalMatrixProxy<MatrixType> local_matrix(global_matrix_, coarse_grid_entity, coarse_grid_entity);

      const auto& coarse_grid_baseSet = local_matrix.domainBasisFunctionSet();
      const auto numMacroBaseFunctions = coarse_grid_baseSet.size();

      Multiscale::MsFEM::LocalSolutionManager localSolutionManager(coarseDiscreteFunctionSpace_,
                                                                   coarse_grid_entity,
                                                                   subgrid_list_);
      localSolutionManager.load();
      const auto& localSolutions = localSolutionManager.getLocalSolutions();
      assert(localSolutions.size() > 0);

      for (const auto& localGridEntity : localSolutionManager.space()) {
        // ignore overlay elements
        if (subgrid_list_.covers(coarse_grid_entity, localGridEntity)) {
          const auto& local_grid_geometry = localGridEntity.geometry();

          // higher order quadrature, since A^{\epsilon} is highly variable
          const auto localQuadrature = DSFe::make_quadrature(localGridEntity, localSolutionManager.space());
          const auto numQuadraturePoints = localQuadrature.nop();

          // number of local solutions without the boundary correctors. Those are only needed for the right hand side
          const auto numLocalSolutions = localSolutions.size() - localSolutionManager.numBoundaryCorrectors();
          // evaluate the jacobians of all local solutions in all quadrature points
          std::vector<std::vector<JacobianRangeType>> allLocalSolutionEvaluations(
              numLocalSolutions, std::vector<JacobianRangeType>(localQuadrature.nop(), JacobianRangeType(0.0)));
          for (auto lsNum : DSC::valueRange(numLocalSolutions)) {
            auto& sll = localSolutions[lsNum];
            assert(sll.get());
            assert(sll->dofsValid());
            assert(localSolutionManager.space().indexSet().contains(localGridEntity));
            auto localFunction = sll->localFunction(localGridEntity);
            localFunction.evaluateQuadrature(localQuadrature, allLocalSolutionEvaluations[lsNum]);
          }

          for (size_t localQuadraturePoint = 0; localQuadraturePoint < numQuadraturePoints; ++localQuadraturePoint) {
            // local (barycentric) coordinates (with respect to entity)
            const auto& local_subgrid_point = localQuadrature.point(localQuadraturePoint);

            auto global_point_in_U_T = local_grid_geometry.global(local_subgrid_point);
            const double weight_local_quadrature = localQuadrature.weight(localQuadraturePoint) *
                                                   local_grid_geometry.integrationElement(local_subgrid_point);

            // evaluate the jacobian of the coarse grid base set
            const auto& local_coarse_point = coarse_grid_geometry.local(global_point_in_U_T);
            if (!cached_) {
              coarseBaseJacs_.push_back(std::vector<JacobianRangeType>(numMacroBaseFunctions, 0.0));
              coarse_grid_baseSet.jacobianAll(local_coarse_point, coarseBaseJacs_[cacheCounter]);
            }

            for (unsigned int i = 0; i < numMacroBaseFunctions; ++i) {
              for (unsigned int j = 0; j < numMacroBaseFunctions; ++j) {
                RangeType local_integral(0.0);

                // Compute the gradients of the i'th and j'th local problem solutions
                JacobianRangeType gradLocProbSoli(0.0), gradLocProbSolj(0.0);
                if (is_simplex_grid) {
                  assert(allLocalSolutionEvaluations.size() == CommonTraits::GridType::dimension);
                  // ∇ Phi_H + ∇ Q( Phi_H ) = ∇ Phi_H + ∂_x1 Phi_H ∇Q( e_1 ) + ∂_x2 Phi_H ∇Q( e_2 )
                  for (int k = 0; k < CommonTraits::GridType::dimension; ++k) {
                    gradLocProbSoli.axpy(coarseBaseJacs_[cacheCounter][i][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
                    gradLocProbSolj.axpy(coarseBaseJacs_[cacheCounter][j][0][k], allLocalSolutionEvaluations[k][localQuadraturePoint]);
                  }
                } else {
                  assert(allLocalSolutionEvaluations.size() == numMacroBaseFunctions);
                  gradLocProbSoli = allLocalSolutionEvaluations[i][localQuadraturePoint];
                  gradLocProbSolj = allLocalSolutionEvaluations[j][localQuadraturePoint];
                }

                JacobianRangeType reconstructionGradPhii(coarseBaseJacs_[cacheCounter][i]);
                reconstructionGradPhii += gradLocProbSoli;
                JacobianRangeType reconstructionGradPhij(coarseBaseJacs_[cacheCounter][j]);
                reconstructionGradPhij += gradLocProbSolj;
                JacobianRangeType diffusive_flux(0.0);
                diffusion_operator_.diffusiveFlux(global_point_in_U_T, reconstructionGradPhii, diffusive_flux);
                if (petrovGalerkin_)
                  local_integral += weight_local_quadrature * (diffusive_flux[0] * coarseBaseJacs_[cacheCounter][j][0]);
                else
                  local_integral += weight_local_quadrature * (diffusive_flux[0] * reconstructionGradPhij[0]);

                // add entries
                local_matrix.add(j, i, local_integral);
              }
            }

            ++cacheCounter;
          }
        }
      }
      // cache was filled;
      cached_ = true;
    } // for
  }   // omp region

  // set unit rows for dirichlet dofs
  Dune::Multiscale::getConstraintsCoarse(coarseDiscreteFunctionSpace_).applyToOperator(global_matrix_);
  global_matrix_.communicate();
}

void CoarseScaleOperator::apply_inverse(const CoarseScaleOperator::CoarseDiscreteFunction& rhs,
                                        CoarseScaleOperator::CoarseDiscreteFunction& solution) {
  BOOST_ASSERT_MSG(rhs.dofsValid(), "Coarse scale RHS DOFs need to be valid!");
  DSC_PROFILER.startTiming("msfem.solveCoarse");
  const typename BackendChooser<CoarseDiscreteFunctionSpace>::InverseOperatorType inverse(
      global_matrix_, 1e-8, 1e-8, DSC_CONFIG_GET("msfem.solver.iterations", rhs.size()),
      DSC_CONFIG_GET("msfem.solver.verbose", false), "bcgs",
      DSC_CONFIG_GET("msfem.solver.preconditioner_type", std::string("sor")));
  inverse(rhs, solution);
  if (!solution.dofsValid())
    DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!");
  DSC_PROFILER.stopTiming("msfem.solveCoarse");
  DSC_LOG_DEBUG << "Time to solve coarse MsFEM problem: " << DSC_PROFILER.getTiming("msfem.solveCoarse") << "ms."
               << std::endl;
} // constructor

} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: resourceprovider.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2003-10-06 15:58:12 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif

#include <svtools/svtools.hrc>

//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------

using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;

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

#define RES_NAME svt

#define FOLDERPICKER_TITLE            500
#define FOLDER_PICKER_DEF_DESCRIPTION 501

//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------

struct _Entry
{
    sal_Int32 ctrlId;
    sal_Int16 resId;
};

_Entry CtrlIdToResIdTable[] = {
    { CHECKBOX_AUTOEXTENSION,                   STR_SVT_FILEPICKER_AUTO_EXTENSION },
    { CHECKBOX_PASSWORD,                        STR_SVT_FILEPICKER_PASSWORD },
    { CHECKBOX_FILTEROPTIONS,                   STR_SVT_FILEPICKER_FILTER_OPTIONS },
    { CHECKBOX_READONLY,                        STR_SVT_FILEPICKER_READONLY },
    { CHECKBOX_LINK,                            STR_SVT_FILEPICKER_INSERT_AS_LINK },
    { CHECKBOX_PREVIEW,                         STR_SVT_FILEPICKER_SHOW_PREVIEW },
    { PUSHBUTTON_PLAY,                          STR_SVT_FILEPICKER_PLAY },
    { LISTBOX_VERSION_LABEL,                    STR_SVT_FILEPICKER_VERSION },
    { LISTBOX_TEMPLATE_LABEL,                   STR_SVT_FILEPICKER_TEMPLATES },
    { LISTBOX_IMAGE_TEMPLATE_LABEL,             STR_SVT_FILEPICKER_IMAGE_TEMPLATE },
    { CHECKBOX_SELECTION,                       STR_SVT_FILEPICKER_SELECTION },
    { FOLDERPICKER_TITLE,                       STR_SVT_FOLDERPICKER_DEFAULT_TITLE },
    { FOLDER_PICKER_DEF_DESCRIPTION,            STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION }
};

const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );

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

sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
    sal_Int16 aResId = -1;

    for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
    {
        if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
        {
            aResId = CtrlIdToResIdTable[i].resId;
            break;
        }
    }

    return aResId;
}

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

class CResourceProvider_Impl
{
public:

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

    CResourceProvider_Impl( )
    {
        m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
    }

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

    ~CResourceProvider_Impl( )
    {
        delete m_ResMgr;
    }

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

    OUString getResString( sal_Int16 aId )
    {
        String   aResString;
        OUString aResOUString;

        const ::vos::OGuard aGuard( Application::GetSolarMutex() );

        try
        {
            OSL_ASSERT( m_ResMgr );

            // translate the control id to a resource id
            sal_Int16 aResId = CtrlIdToResId( aId );

            if ( aResId > -1 )
            {
                aResString = String( ResId( aResId, m_ResMgr ) );
                aResOUString = OUString( aResString );
            }
        }
        catch(...)
        {
        }

        return aResOUString;
    }

public:
    ResMgr* m_ResMgr;
};

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

CResourceProvider::CResourceProvider( ) :
    m_pImpl( new CResourceProvider_Impl() )
{
}

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

CResourceProvider::~CResourceProvider( )
{
    delete m_pImpl;
}

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

OUString CResourceProvider::getResString( sal_Int32 aId )
{
   return m_pImpl->getResString( aId );
}
<commit_msg>INTEGRATION: CWS mhu06 (1.5.48); FILE MERGED 2005/04/22 11:45:49 mhu 1.5.48.1: #i47753# Adapted to moved resources (from 'svt' to 'fps_office').<commit_after>/*************************************************************************
 *
 *  $RCSfile: resourceprovider.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-27 08:53:18 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif

#include <svtools/svtools.hrc>

//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------

using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;

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

#define RES_NAME fps_office

#define FOLDERPICKER_TITLE            500
#define FOLDER_PICKER_DEF_DESCRIPTION 501

//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------

struct _Entry
{
    sal_Int32 ctrlId;
    sal_Int16 resId;
};

_Entry CtrlIdToResIdTable[] = {
    { CHECKBOX_AUTOEXTENSION,                   STR_SVT_FILEPICKER_AUTO_EXTENSION },
    { CHECKBOX_PASSWORD,                        STR_SVT_FILEPICKER_PASSWORD },
    { CHECKBOX_FILTEROPTIONS,                   STR_SVT_FILEPICKER_FILTER_OPTIONS },
    { CHECKBOX_READONLY,                        STR_SVT_FILEPICKER_READONLY },
    { CHECKBOX_LINK,                            STR_SVT_FILEPICKER_INSERT_AS_LINK },
    { CHECKBOX_PREVIEW,                         STR_SVT_FILEPICKER_SHOW_PREVIEW },
    { PUSHBUTTON_PLAY,                          STR_SVT_FILEPICKER_PLAY },
    { LISTBOX_VERSION_LABEL,                    STR_SVT_FILEPICKER_VERSION },
    { LISTBOX_TEMPLATE_LABEL,                   STR_SVT_FILEPICKER_TEMPLATES },
    { LISTBOX_IMAGE_TEMPLATE_LABEL,             STR_SVT_FILEPICKER_IMAGE_TEMPLATE },
    { CHECKBOX_SELECTION,                       STR_SVT_FILEPICKER_SELECTION },
    { FOLDERPICKER_TITLE,                       STR_SVT_FOLDERPICKER_DEFAULT_TITLE },
    { FOLDER_PICKER_DEF_DESCRIPTION,            STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION }
};

const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );

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

sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
    sal_Int16 aResId = -1;

    for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
    {
        if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
        {
            aResId = CtrlIdToResIdTable[i].resId;
            break;
        }
    }

    return aResId;
}

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

class CResourceProvider_Impl
{
public:

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

    CResourceProvider_Impl( )
    {
        m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
    }

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

    ~CResourceProvider_Impl( )
    {
        delete m_ResMgr;
    }

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

    OUString getResString( sal_Int16 aId )
    {
        String   aResString;
        OUString aResOUString;

        const ::vos::OGuard aGuard( Application::GetSolarMutex() );

        try
        {
            OSL_ASSERT( m_ResMgr );

            // translate the control id to a resource id
            sal_Int16 aResId = CtrlIdToResId( aId );

            if ( aResId > -1 )
            {
                aResString = String( ResId( aResId, m_ResMgr ) );
                aResOUString = OUString( aResString );
            }
        }
        catch(...)
        {
        }

        return aResOUString;
    }

public:
    ResMgr* m_ResMgr;
};

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

CResourceProvider::CResourceProvider( ) :
    m_pImpl( new CResourceProvider_Impl() )
{
}

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

CResourceProvider::~CResourceProvider( )
{
    delete m_pImpl;
}

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

OUString CResourceProvider::getResString( sal_Int32 aId )
{
   return m_pImpl->getResString( aId );
}
<|endoftext|>


<commit_before>/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * Contact: maliit-discuss@lists.maliit.org
 *
 * 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
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mdirectinputcontextplugin.h"

#include "mimserver.h"
#include "mimapphostedserverlogic.h"

#include "connectionfactory.h"
#include "mimdirectserverconnection.h"
#include "miminputcontextdirectconnection.h"

#include <maliit/inputmethod.h>

using namespace std::tr1;

#include <minputcontext.h>
#include <QString>
#include <QStringList>

namespace {
    const QString MaliitDirectInputContextName(MALIIT_INPUTCONTEXT_NAME"Direct");
}

MDirectInputContextPlugin::MDirectInputContextPlugin(QObject *parent)
    : QInputContextPlugin(parent)
{
    // nothing
}

MDirectInputContextPlugin::~MDirectInputContextPlugin()
{
    // nothing
}

QInputContext *MDirectInputContextPlugin::create(const QString &key)
{
    QInputContext *ctx = NULL;

    if (key == MaliitDirectInputContextName) {
        QSharedPointer<MImDirectServerConnection> serverConnection =
                qSharedPointerObjectCast<MImDirectServerConnection>(Maliit::createServerConnection(MaliitDirectInputContextName));
        MImInputContextDirectConnection *icConnection = new MImInputContextDirectConnection;
        serverConnection->connectTo(icConnection);

        shared_ptr<MInputContextConnection> icConn(icConnection);
        QSharedPointer<MImAppHostedServerLogic> serverLogic(new MImAppHostedServerLogic);
        MImServer *imServer = new MImServer(serverLogic, icConn);

        Maliit::InputMethod::instance()->setWidget(serverLogic->pluginsProxyWidget());

        ctx = new MInputContext(serverConnection, MaliitDirectInputContextName, this);
        imServer->setParent(ctx);
    } else {
        qCritical() << "Unknown plugin name";
    }

    return ctx;
}

QString MDirectInputContextPlugin::description(const QString &s)
{
    Q_UNUSED(s);

    return "Maliit input context plugin";
}

QString MDirectInputContextPlugin::displayName(const QString &s)
{
    Q_UNUSED(s);

    // TODO: want this translated?
    return "Input context for Maliit input methods";
}

QStringList MDirectInputContextPlugin::keys() const
{
    return QStringList(MaliitDirectInputContextName);
}

QStringList MDirectInputContextPlugin::languages(const QString &)
{
    return QStringList("EN"); // FIXME
}

Q_EXPORT_PLUGIN2(mdirectinputcontext, MDirectInputContextPlugin)

<commit_msg>Explicitly specify temporary/persistent settings for MImSettings<commit_after>/* * This file is part of Maliit framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * Contact: maliit-discuss@lists.maliit.org
 *
 * 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
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mdirectinputcontextplugin.h"

#include "mimserver.h"
#include "mimapphostedserverlogic.h"

#include "connectionfactory.h"
#include "mimdirectserverconnection.h"
#include "miminputcontextdirectconnection.h"

#include <maliit/inputmethod.h>

using namespace std::tr1;

#include <minputcontext.h>
#include <QString>
#include <QStringList>

namespace {
    const QString MaliitDirectInputContextName(MALIIT_INPUTCONTEXT_NAME"Direct");
}

MDirectInputContextPlugin::MDirectInputContextPlugin(QObject *parent)
    : QInputContextPlugin(parent)
{
    // nothing
}

MDirectInputContextPlugin::~MDirectInputContextPlugin()
{
    // nothing
}

QInputContext *MDirectInputContextPlugin::create(const QString &key)
{
    QInputContext *ctx = NULL;

    if (key == MaliitDirectInputContextName) {
        QSharedPointer<MImDirectServerConnection> serverConnection =
                qSharedPointerObjectCast<MImDirectServerConnection>(Maliit::createServerConnection(MaliitDirectInputContextName));
        MImInputContextDirectConnection *icConnection = new MImInputContextDirectConnection;
        serverConnection->connectTo(icConnection);

        shared_ptr<MInputContextConnection> icConn(icConnection);
        QSharedPointer<MImAppHostedServerLogic> serverLogic(new MImAppHostedServerLogic);
        MImServer::configureSettings(MImServer::TemporarySettings);
        MImServer *imServer = new MImServer(serverLogic, icConn);

        Maliit::InputMethod::instance()->setWidget(serverLogic->pluginsProxyWidget());

        ctx = new MInputContext(serverConnection, MaliitDirectInputContextName, this);
        imServer->setParent(ctx);
    } else {
        qCritical() << "Unknown plugin name";
    }

    return ctx;
}

QString MDirectInputContextPlugin::description(const QString &s)
{
    Q_UNUSED(s);

    return "Maliit input context plugin";
}

QString MDirectInputContextPlugin::displayName(const QString &s)
{
    Q_UNUSED(s);

    // TODO: want this translated?
    return "Input context for Maliit input methods";
}

QStringList MDirectInputContextPlugin::keys() const
{
    return QStringList(MaliitDirectInputContextName);
}

QStringList MDirectInputContextPlugin::languages(const QString &)
{
    return QStringList("EN"); // FIXME
}

Q_EXPORT_PLUGIN2(mdirectinputcontext, MDirectInputContextPlugin)

<|endoftext|>


<commit_before>#include "precompiled.h"
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

// BufferStorage11.cpp Defines the BufferStorage11 class.

#include "libGLESv2/renderer/d3d11/BufferStorage11.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/d3d11/Renderer11.h"
#include "libGLESv2/renderer/d3d11/formatutils11.h"

namespace rx
{

BufferStorage11::BufferStorage11(Renderer11 *renderer)
{
    mRenderer = renderer;

    mStagingBuffer = NULL;
    mStagingBufferSize = 0;

    mSize = 0;

    mResolvedData = NULL;
    mResolvedDataSize = 0;
    mResolvedDataValid = false;

    mReadUsageCount = 0;
    mWriteUsageCount = 0;
}

BufferStorage11::~BufferStorage11()
{
    SafeRelease(mStagingBuffer);

    if (mResolvedData)
    {
        free(mResolvedData);
        mResolvedData = NULL;
    }

    for (size_t bufferIndex = 0; bufferIndex < mDirectBuffers.size(); bufferIndex++)
    {
        SafeDelete(mDirectBuffers[bufferIndex]);
    }
}

BufferStorage11 *BufferStorage11::makeBufferStorage11(BufferStorage *bufferStorage)
{
    ASSERT(HAS_DYNAMIC_TYPE(BufferStorage11*, bufferStorage));
    return static_cast<BufferStorage11*>(bufferStorage);
}

void *BufferStorage11::getData()
{
    ASSERT(mStagingBuffer);

    if (!mResolvedDataValid)
    {
        ID3D11Device *device = mRenderer->getDevice();
        ID3D11DeviceContext *context = mRenderer->getDeviceContext();
        HRESULT result;

        if (!mResolvedData || mResolvedDataSize < mStagingBufferSize)
        {
            free(mResolvedData);
            mResolvedData = malloc(mSize);
            mResolvedDataSize = mSize;
        }

        D3D11_MAPPED_SUBRESOURCE mappedResource;
        result = context->Map(mStagingBuffer, 0, D3D11_MAP_READ, 0, &mappedResource);
        if (FAILED(result))
        {
            return gl::error(GL_OUT_OF_MEMORY, (void*)NULL);
        }

        memcpy(mResolvedData, mappedResource.pData, mSize);

        context->Unmap(mStagingBuffer, 0);

        mResolvedDataValid = true;
    }

    mReadUsageCount = 0;

    return mResolvedData;
}

void BufferStorage11::setData(const void* data, unsigned int size, unsigned int offset)
{
    ID3D11Device *device = mRenderer->getDevice();
    ID3D11DeviceContext *context = mRenderer->getDeviceContext();
    HRESULT result;

    const unsigned int requiredStagingBufferSize = size + offset;
    const bool createStagingBuffer = !mStagingBuffer || mStagingBufferSize < requiredStagingBufferSize;

    if (createStagingBuffer)
    {
        D3D11_BUFFER_DESC bufferDesc;
        bufferDesc.ByteWidth = requiredStagingBufferSize;
        bufferDesc.Usage = D3D11_USAGE_STAGING;
        bufferDesc.BindFlags = 0;
        bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
        bufferDesc.MiscFlags = 0;
        bufferDesc.StructureByteStride = 0;

        HRESULT result;
        ID3D11Device *device = mRenderer->getDevice();
        ID3D11DeviceContext *context = mRenderer->getDeviceContext();
        ID3D11Buffer *newStagingBuffer;

        if (data && offset == 0)
        {
            D3D11_SUBRESOURCE_DATA initialData;
            initialData.pSysMem = data;
            initialData.SysMemPitch = requiredStagingBufferSize;
            initialData.SysMemSlicePitch = 0;

            result = device->CreateBuffer(&bufferDesc, &initialData, &newStagingBuffer);
        }
        else
        {
            result = device->CreateBuffer(&bufferDesc, NULL, &newStagingBuffer);
        }

        if (FAILED(result))
        {
            mStagingBufferSize = 0;
            return gl::error(GL_OUT_OF_MEMORY);
        }

        mStagingBufferSize = requiredStagingBufferSize;

        if (mStagingBuffer && offset > 0)
        {
            // If offset is greater than zero and the buffer is non-null, need to preserve the data from
            // the old buffer up to offset
            D3D11_BOX srcBox;
            srcBox.left = 0;
            srcBox.right = std::min(offset, requiredStagingBufferSize);
            srcBox.top = 0;
            srcBox.bottom = 1;
            srcBox.front = 0;
            srcBox.back = 1;

            context->CopySubresourceRegion(newStagingBuffer, 0, 0, 0, 0, mStagingBuffer, 0, &srcBox);
        }

        SafeRelease(mStagingBuffer);
        mStagingBuffer = newStagingBuffer;
    }

    if (data && (offset != 0 || !createStagingBuffer))
    {
        D3D11_MAPPED_SUBRESOURCE mappedResource;
        result = context->Map(mStagingBuffer, 0, D3D11_MAP_WRITE, 0, &mappedResource);
        if (FAILED(result))
        {
            return gl::error(GL_OUT_OF_MEMORY);
        }

        unsigned char *offsetBufferPointer = reinterpret_cast<unsigned char *>(mappedResource.pData) + offset;
        memcpy(offsetBufferPointer, data, size);

        context->Unmap(mStagingBuffer, 0);
    }

    for (size_t bufferIndex = 0; bufferIndex < mDirectBuffers.size(); bufferIndex++)
    {
        mDirectBuffers[bufferIndex]->markDirty();
    }

    mSize = std::max(mSize, requiredStagingBufferSize);
    mWriteUsageCount = 0;

    mResolvedDataValid = false;
}

void BufferStorage11::copyData(BufferStorage* sourceStorage, unsigned int size,
                               unsigned int sourceOffset, unsigned int destOffset)
{
    BufferStorage11* source = makeBufferStorage11(sourceStorage);
    if (source)
    {
        ID3D11DeviceContext *context = mRenderer->getDeviceContext();

        D3D11_BOX srcBox;
        srcBox.left = sourceOffset;
        srcBox.right = sourceOffset + size;
        srcBox.top = 0;
        srcBox.bottom = 1;
        srcBox.front = 0;
        srcBox.back = 1;

        ASSERT(mStagingBuffer && source->mStagingBuffer);
        context->CopySubresourceRegion(mStagingBuffer, 0, destOffset, 0, 0, source->mStagingBuffer, 0, &srcBox);
    }
}

void BufferStorage11::clear()
{
    mResolvedDataValid = false;
    mSize = 0;
}

unsigned int BufferStorage11::getSize() const
{
    return mSize;
}

bool BufferStorage11::supportsDirectBinding() const
{
    return true;
}

void BufferStorage11::markBufferUsage()
{
    mReadUsageCount++;
    mWriteUsageCount++;

    const unsigned int usageLimit = 5;

    if (mReadUsageCount > usageLimit && mResolvedData)
    {
        free(mResolvedData);
        mResolvedData = NULL;
        mResolvedDataSize = 0;
        mResolvedDataValid = false;
    }
}

ID3D11Buffer *BufferStorage11::getBuffer(bool isConstantBufferUsage)
{
    markBufferUsage();

    for (size_t bufferIndex = 0; bufferIndex < mDirectBuffers.size(); bufferIndex++)
    {
        DirectBufferStorage11 *directBuffer = mDirectBuffers[bufferIndex];

        if (directBuffer->isConstantBufferUsage() == isConstantBufferUsage)
        {
            if (directBuffer->isDirty())
            {
                // if updateFromStagingBuffer returns true, the D3D buffer has been recreated
                // and we should update our serial
                if (directBuffer->updateFromStagingBuffer(mStagingBuffer, mSize, 0))
                {
                    updateSerial();
                }
            }
            return directBuffer->getD3DBuffer();
        }
    }

    // buffer is not allocated, create it
    DirectBufferStorage11 *directBuffer = new DirectBufferStorage11(mRenderer, isConstantBufferUsage);
    directBuffer->updateFromStagingBuffer(mStagingBuffer, mSize, 0);

    mDirectBuffers.push_back(directBuffer);
    updateSerial();

    return directBuffer->getD3DBuffer();
}

ID3D11ShaderResourceView *BufferStorage11::getSRV(DXGI_FORMAT srvFormat)
{
    ID3D11Buffer *buffer = getBuffer(false);

    auto bufferSRVIt = mBufferResourceViews.find(srvFormat);

    if (bufferSRVIt != mBufferResourceViews.end())
    {
        if (bufferSRVIt->second.first == buffer)
        {
            return bufferSRVIt->second.second;
        }
        else
        {
            // The underlying buffer has changed since the SRV was created: recreate the SRV.
            SafeRelease(bufferSRVIt->second.second);
        }
    }

    ID3D11Device *device = mRenderer->getDevice();
    ID3D11ShaderResourceView *bufferSRV = NULL;

    D3D11_SHADER_RESOURCE_VIEW_DESC bufferSRVDesc;
    bufferSRVDesc.Buffer.ElementOffset = 0;
    bufferSRVDesc.Buffer.ElementWidth = mSize / d3d11::GetFormatPixelBytes(srvFormat, mRenderer->getCurrentClientVersion());
    bufferSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
    bufferSRVDesc.Format = srvFormat;

    HRESULT result = device->CreateShaderResourceView(buffer, &bufferSRVDesc, &bufferSRV);
    ASSERT(SUCCEEDED(result));

    mBufferResourceViews[srvFormat] = BufferSRVPair(buffer, bufferSRV);

    return bufferSRV;
}

DirectBufferStorage11::DirectBufferStorage11(Renderer11 *renderer, bool isConstantBufferUsage)
    : mRenderer(renderer),
      mIsConstantBufferUsage(isConstantBufferUsage),
      mDirectBuffer(NULL),
      mBufferSize(0),
      mDirty(false)
{
}

DirectBufferStorage11::~DirectBufferStorage11()
{
    SafeRelease(mDirectBuffer);
}

bool DirectBufferStorage11::isConstantBufferUsage() const
{
    return mIsConstantBufferUsage;
}

// Returns true if it recreates the direct buffer
bool DirectBufferStorage11::updateFromStagingBuffer(ID3D11Buffer *stagingBuffer, size_t size, size_t offset)
{
    ID3D11Device *device = mRenderer->getDevice();
    ID3D11DeviceContext *context = mRenderer->getDeviceContext();

    // unused for now
    ASSERT(offset == 0);

    unsigned int requiredBufferSize = size + offset;
    bool createBuffer = !mDirectBuffer || mBufferSize < requiredBufferSize;

    // (Re)initialize D3D buffer if needed
    if (createBuffer)
    {
        D3D11_BUFFER_DESC bufferDesc;
        fillBufferDesc(&bufferDesc, requiredBufferSize);

        ID3D11Buffer *newBuffer;
        HRESULT result = device->CreateBuffer(&bufferDesc, NULL, &newBuffer);

        if (FAILED(result))
        {
            return gl::error(GL_OUT_OF_MEMORY, false);
        }

        // No longer need the old buffer
        SafeRelease(mDirectBuffer);
        mDirectBuffer = newBuffer;

        mBufferSize = bufferDesc.ByteWidth;
    }
    else
    {
        mBufferSize = requiredBufferSize;
    }

    // Copy data via staging buffer
    D3D11_BOX srcBox;
    srcBox.left = 0;
    srcBox.right = size;
    srcBox.top = 0;
    srcBox.bottom = 1;
    srcBox.front = 0;
    srcBox.back = 1;

    context->CopySubresourceRegion(mDirectBuffer, 0, offset, 0, 0, stagingBuffer, 0, &srcBox);

    mDirty = false;

    return createBuffer;
}

void DirectBufferStorage11::fillBufferDesc(D3D11_BUFFER_DESC* bufferDesc, unsigned int bufferSize)
{
    bufferDesc->ByteWidth = bufferSize;
    bufferDesc->MiscFlags = 0;
    bufferDesc->StructureByteStride = 0;

    if (!mIsConstantBufferUsage)
    {
        bufferDesc->Usage = D3D11_USAGE_DEFAULT;
        bufferDesc->BindFlags = D3D11_BIND_INDEX_BUFFER | D3D11_BIND_VERTEX_BUFFER | D3D11_BIND_SHADER_RESOURCE;
        bufferDesc->CPUAccessFlags = 0;
    }
    else
    {
        bufferDesc->Usage = D3D11_USAGE_DYNAMIC;
        bufferDesc->BindFlags = D3D11_BIND_CONSTANT_BUFFER;
        bufferDesc->CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

        // Constant buffers must be of a limited size, and aligned to 16 byte boundaries
        // For our purposes we ignore any buffer data past the maximum constant buffer size
        bufferDesc->ByteWidth = roundUp(bufferDesc->ByteWidth, 16u);
        bufferDesc->ByteWidth = std::min(bufferDesc->ByteWidth, mRenderer->getMaxUniformBufferSize());
    }
}

}
<commit_msg>Don't let mBufferSize fall out of sync with the actual buffer size.  Pervents unnecessary buffer re-creations.<commit_after>#include "precompiled.h"
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

// BufferStorage11.cpp Defines the BufferStorage11 class.

#include "libGLESv2/renderer/d3d11/BufferStorage11.h"
#include "libGLESv2/main.h"
#include "libGLESv2/renderer/d3d11/Renderer11.h"
#include "libGLESv2/renderer/d3d11/formatutils11.h"

namespace rx
{

BufferStorage11::BufferStorage11(Renderer11 *renderer)
{
    mRenderer = renderer;

    mStagingBuffer = NULL;
    mStagingBufferSize = 0;

    mSize = 0;

    mResolvedData = NULL;
    mResolvedDataSize = 0;
    mResolvedDataValid = false;

    mReadUsageCount = 0;
    mWriteUsageCount = 0;
}

BufferStorage11::~BufferStorage11()
{
    SafeRelease(mStagingBuffer);

    if (mResolvedData)
    {
        free(mResolvedData);
        mResolvedData = NULL;
    }

    for (size_t bufferIndex = 0; bufferIndex < mDirectBuffers.size(); bufferIndex++)
    {
        SafeDelete(mDirectBuffers[bufferIndex]);
    }
}

BufferStorage11 *BufferStorage11::makeBufferStorage11(BufferStorage *bufferStorage)
{
    ASSERT(HAS_DYNAMIC_TYPE(BufferStorage11*, bufferStorage));
    return static_cast<BufferStorage11*>(bufferStorage);
}

void *BufferStorage11::getData()
{
    ASSERT(mStagingBuffer);

    if (!mResolvedDataValid)
    {
        ID3D11Device *device = mRenderer->getDevice();
        ID3D11DeviceContext *context = mRenderer->getDeviceContext();
        HRESULT result;

        if (!mResolvedData || mResolvedDataSize < mStagingBufferSize)
        {
            free(mResolvedData);
            mResolvedData = malloc(mSize);
            mResolvedDataSize = mSize;
        }

        D3D11_MAPPED_SUBRESOURCE mappedResource;
        result = context->Map(mStagingBuffer, 0, D3D11_MAP_READ, 0, &mappedResource);
        if (FAILED(result))
        {
            return gl::error(GL_OUT_OF_MEMORY, (void*)NULL);
        }

        memcpy(mResolvedData, mappedResource.pData, mSize);

        context->Unmap(mStagingBuffer, 0);

        mResolvedDataValid = true;
    }

    mReadUsageCount = 0;

    return mResolvedData;
}

void BufferStorage11::setData(const void* data, unsigned int size, unsigned int offset)
{
    ID3D11Device *device = mRenderer->getDevice();
    ID3D11DeviceContext *context = mRenderer->getDeviceContext();
    HRESULT result;

    const unsigned int requiredStagingBufferSize = size + offset;
    const bool createStagingBuffer = !mStagingBuffer || mStagingBufferSize < requiredStagingBufferSize;

    if (createStagingBuffer)
    {
        D3D11_BUFFER_DESC bufferDesc;
        bufferDesc.ByteWidth = requiredStagingBufferSize;
        bufferDesc.Usage = D3D11_USAGE_STAGING;
        bufferDesc.BindFlags = 0;
        bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
        bufferDesc.MiscFlags = 0;
        bufferDesc.StructureByteStride = 0;

        HRESULT result;
        ID3D11Device *device = mRenderer->getDevice();
        ID3D11DeviceContext *context = mRenderer->getDeviceContext();
        ID3D11Buffer *newStagingBuffer;

        if (data && offset == 0)
        {
            D3D11_SUBRESOURCE_DATA initialData;
            initialData.pSysMem = data;
            initialData.SysMemPitch = requiredStagingBufferSize;
            initialData.SysMemSlicePitch = 0;

            result = device->CreateBuffer(&bufferDesc, &initialData, &newStagingBuffer);
        }
        else
        {
            result = device->CreateBuffer(&bufferDesc, NULL, &newStagingBuffer);
        }

        if (FAILED(result))
        {
            mStagingBufferSize = 0;
            return gl::error(GL_OUT_OF_MEMORY);
        }

        mStagingBufferSize = requiredStagingBufferSize;

        if (mStagingBuffer && offset > 0)
        {
            // If offset is greater than zero and the buffer is non-null, need to preserve the data from
            // the old buffer up to offset
            D3D11_BOX srcBox;
            srcBox.left = 0;
            srcBox.right = std::min(offset, requiredStagingBufferSize);
            srcBox.top = 0;
            srcBox.bottom = 1;
            srcBox.front = 0;
            srcBox.back = 1;

            context->CopySubresourceRegion(newStagingBuffer, 0, 0, 0, 0, mStagingBuffer, 0, &srcBox);
        }

        SafeRelease(mStagingBuffer);
        mStagingBuffer = newStagingBuffer;
    }

    if (data && (offset != 0 || !createStagingBuffer))
    {
        D3D11_MAPPED_SUBRESOURCE mappedResource;
        result = context->Map(mStagingBuffer, 0, D3D11_MAP_WRITE, 0, &mappedResource);
        if (FAILED(result))
        {
            return gl::error(GL_OUT_OF_MEMORY);
        }

        unsigned char *offsetBufferPointer = reinterpret_cast<unsigned char *>(mappedResource.pData) + offset;
        memcpy(offsetBufferPointer, data, size);

        context->Unmap(mStagingBuffer, 0);
    }

    for (size_t bufferIndex = 0; bufferIndex < mDirectBuffers.size(); bufferIndex++)
    {
        mDirectBuffers[bufferIndex]->markDirty();
    }

    mSize = std::max(mSize, requiredStagingBufferSize);
    mWriteUsageCount = 0;

    mResolvedDataValid = false;
}

void BufferStorage11::copyData(BufferStorage* sourceStorage, unsigned int size,
                               unsigned int sourceOffset, unsigned int destOffset)
{
    BufferStorage11* source = makeBufferStorage11(sourceStorage);
    if (source)
    {
        ID3D11DeviceContext *context = mRenderer->getDeviceContext();

        D3D11_BOX srcBox;
        srcBox.left = sourceOffset;
        srcBox.right = sourceOffset + size;
        srcBox.top = 0;
        srcBox.bottom = 1;
        srcBox.front = 0;
        srcBox.back = 1;

        ASSERT(mStagingBuffer && source->mStagingBuffer);
        context->CopySubresourceRegion(mStagingBuffer, 0, destOffset, 0, 0, source->mStagingBuffer, 0, &srcBox);
    }
}

void BufferStorage11::clear()
{
    mResolvedDataValid = false;
    mSize = 0;
}

unsigned int BufferStorage11::getSize() const
{
    return mSize;
}

bool BufferStorage11::supportsDirectBinding() const
{
    return true;
}

void BufferStorage11::markBufferUsage()
{
    mReadUsageCount++;
    mWriteUsageCount++;

    const unsigned int usageLimit = 5;

    if (mReadUsageCount > usageLimit && mResolvedData)
    {
        free(mResolvedData);
        mResolvedData = NULL;
        mResolvedDataSize = 0;
        mResolvedDataValid = false;
    }
}

ID3D11Buffer *BufferStorage11::getBuffer(bool isConstantBufferUsage)
{
    markBufferUsage();

    for (size_t bufferIndex = 0; bufferIndex < mDirectBuffers.size(); bufferIndex++)
    {
        DirectBufferStorage11 *directBuffer = mDirectBuffers[bufferIndex];

        if (directBuffer->isConstantBufferUsage() == isConstantBufferUsage)
        {
            if (directBuffer->isDirty())
            {
                // if updateFromStagingBuffer returns true, the D3D buffer has been recreated
                // and we should update our serial
                if (directBuffer->updateFromStagingBuffer(mStagingBuffer, mSize, 0))
                {
                    updateSerial();
                }
            }
            return directBuffer->getD3DBuffer();
        }
    }

    // buffer is not allocated, create it
    DirectBufferStorage11 *directBuffer = new DirectBufferStorage11(mRenderer, isConstantBufferUsage);
    directBuffer->updateFromStagingBuffer(mStagingBuffer, mSize, 0);

    mDirectBuffers.push_back(directBuffer);
    updateSerial();

    return directBuffer->getD3DBuffer();
}

ID3D11ShaderResourceView *BufferStorage11::getSRV(DXGI_FORMAT srvFormat)
{
    ID3D11Buffer *buffer = getBuffer(false);

    auto bufferSRVIt = mBufferResourceViews.find(srvFormat);

    if (bufferSRVIt != mBufferResourceViews.end())
    {
        if (bufferSRVIt->second.first == buffer)
        {
            return bufferSRVIt->second.second;
        }
        else
        {
            // The underlying buffer has changed since the SRV was created: recreate the SRV.
            SafeRelease(bufferSRVIt->second.second);
        }
    }

    ID3D11Device *device = mRenderer->getDevice();
    ID3D11ShaderResourceView *bufferSRV = NULL;

    D3D11_SHADER_RESOURCE_VIEW_DESC bufferSRVDesc;
    bufferSRVDesc.Buffer.ElementOffset = 0;
    bufferSRVDesc.Buffer.ElementWidth = mSize / d3d11::GetFormatPixelBytes(srvFormat, mRenderer->getCurrentClientVersion());
    bufferSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
    bufferSRVDesc.Format = srvFormat;

    HRESULT result = device->CreateShaderResourceView(buffer, &bufferSRVDesc, &bufferSRV);
    ASSERT(SUCCEEDED(result));

    mBufferResourceViews[srvFormat] = BufferSRVPair(buffer, bufferSRV);

    return bufferSRV;
}

DirectBufferStorage11::DirectBufferStorage11(Renderer11 *renderer, bool isConstantBufferUsage)
    : mRenderer(renderer),
      mIsConstantBufferUsage(isConstantBufferUsage),
      mDirectBuffer(NULL),
      mBufferSize(0),
      mDirty(false)
{
}

DirectBufferStorage11::~DirectBufferStorage11()
{
    SafeRelease(mDirectBuffer);
}

bool DirectBufferStorage11::isConstantBufferUsage() const
{
    return mIsConstantBufferUsage;
}

// Returns true if it recreates the direct buffer
bool DirectBufferStorage11::updateFromStagingBuffer(ID3D11Buffer *stagingBuffer, size_t size, size_t offset)
{
    ID3D11Device *device = mRenderer->getDevice();
    ID3D11DeviceContext *context = mRenderer->getDeviceContext();

    // unused for now
    ASSERT(offset == 0);

    unsigned int requiredBufferSize = size + offset;
    bool createBuffer = !mDirectBuffer || mBufferSize < requiredBufferSize;

    // (Re)initialize D3D buffer if needed
    if (createBuffer)
    {
        D3D11_BUFFER_DESC bufferDesc;
        fillBufferDesc(&bufferDesc, requiredBufferSize);

        ID3D11Buffer *newBuffer;
        HRESULT result = device->CreateBuffer(&bufferDesc, NULL, &newBuffer);

        if (FAILED(result))
        {
            return gl::error(GL_OUT_OF_MEMORY, false);
        }

        // No longer need the old buffer
        SafeRelease(mDirectBuffer);
        mDirectBuffer = newBuffer;

        mBufferSize = bufferDesc.ByteWidth;
    }

    // Copy data via staging buffer
    D3D11_BOX srcBox;
    srcBox.left = 0;
    srcBox.right = size;
    srcBox.top = 0;
    srcBox.bottom = 1;
    srcBox.front = 0;
    srcBox.back = 1;

    context->CopySubresourceRegion(mDirectBuffer, 0, offset, 0, 0, stagingBuffer, 0, &srcBox);

    mDirty = false;

    return createBuffer;
}

void DirectBufferStorage11::fillBufferDesc(D3D11_BUFFER_DESC* bufferDesc, unsigned int bufferSize)
{
    bufferDesc->ByteWidth = bufferSize;
    bufferDesc->MiscFlags = 0;
    bufferDesc->StructureByteStride = 0;

    if (!mIsConstantBufferUsage)
    {
        bufferDesc->Usage = D3D11_USAGE_DEFAULT;
        bufferDesc->BindFlags = D3D11_BIND_INDEX_BUFFER | D3D11_BIND_VERTEX_BUFFER | D3D11_BIND_SHADER_RESOURCE;
        bufferDesc->CPUAccessFlags = 0;
    }
    else
    {
        bufferDesc->Usage = D3D11_USAGE_DYNAMIC;
        bufferDesc->BindFlags = D3D11_BIND_CONSTANT_BUFFER;
        bufferDesc->CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

        // Constant buffers must be of a limited size, and aligned to 16 byte boundaries
        // For our purposes we ignore any buffer data past the maximum constant buffer size
        bufferDesc->ByteWidth = roundUp(bufferDesc->ByteWidth, 16u);
        bufferDesc->ByteWidth = std::min(bufferDesc->ByteWidth, mRenderer->getMaxUniformBufferSize());
    }
}

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#include <string>
#include <libport/cassert>
#include <cstdarg>
#include <libport/cstdlib>
#include <iostream>
#include <stdexcept>

#include <boost/assign/list_of.hpp>
using namespace boost::assign;

#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/debug.hh>
#include <libport/foreach.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <libport/unistd.h>
#include <libport/windows.hh>
#include <libport/option-parser.hh>

#include <urbi/exit.hh>
#include <urbi/package-info.hh>
#include <urbi/uclient.hh>
#include <urbi/urbi-root.hh>

GD_CATEGORY(Urbi.UrbiLaunch);

using namespace urbi;
using libport::program_name;

static UCallbackAction
onError(const UMessage& msg)
{
  LIBPORT_USE(msg);
  GD_FERROR("%s: load module error: %s", program_name(), msg.message);
  return URBI_CONTINUE;
}

static UCallbackAction
onDone(const UMessage&)
{
  ::exit(0);
}

static int
connect_plugin(const std::string& host, int port,
               const libport::cli_args_type& modules)
{
  UClient cl(host, port);
  if (cl.error())
    // UClient already displayed an error message.
    ::exit(1);
  cl.setErrorCallback(callback(&onError));
  cl.setCallback(callback(&onDone), "output");
  foreach (const std::string& m, modules)
    cl << "loadModule(\"" << m << "\");";
  cl << "output << 1;";
  while (true)
    sleep(1);
  return 0;
}

static void
usage(libport::OptionParser& parser)
{
  std::cout <<
    "usage: " << program_name() <<
    " [OPTIONS] MODULE_NAMES ... [-- UOPTIONS...]\n"
    "Start an UObject in either remote or plugin mode.\n"
              << parser <<
    "\n"
    "MODULE_NAMES is a list of modules.\n"
    "UOPTIONS are passed to urbi::main in remote and start modes.\n"
    "\n"
    "Exit values:\n"
    "  0  success\n"
    " " << EX_NOINPUT << "  some of the MODULES are missing\n"
    " " << EX_OSFILE << "  libuobject is missing\n"
    "  *  other kinds of errors\n"
    ;
  ::exit(EX_OK);
}

static
void
version()
{
  std::cout << urbi::package_info() << std::endl
            << libport::exit(EX_OK);
}

static
int
urbi_launch_(int argc, const char* argv[], UrbiRoot& urbi_root)
{
  libport::program_initialize(argc, argv);

  // The options passed to urbi::main.
  libport::cli_args_type args;

  args << argv[0];

  libport::OptionValue
    arg_custom("start using the shared library FILE", "custom", 'c', "FILE"),
    arg_pfile("file containing the port to listen to", "port-file", 0, "FILE");
  libport::OptionFlag
    arg_plugin("start as a plugin uobject on a running server", "plugin", 'p'),
    arg_remote("start as a remote uobject", "remote", 'r'),
    arg_start("start an urbi server and connect as plugin", "start", 's');
  libport::OptionsEnd arg_end;

  libport::OptionParser opt_parser;
  opt_parser << "Urbi-Launch options:"
	     << libport::opts::help
	     << libport::opts::version
	     << arg_custom
#ifndef LIBPORT_DEBUG_DISABLE
	     << libport::opts::debug
#endif
	     << "Mode selection:"
	     << arg_plugin
	     << arg_remote
	     << arg_start
	     << "Urbi-Launch options for plugin mode:"
	     << libport::opts::host
	     << libport::opts::port
	     << arg_pfile
	     << arg_end;

  // The list of modules.
  libport::cli_args_type modules;
  try
  {
    modules = opt_parser(libport::program_arguments());
  }
  catch (const libport::Error& e)
  {
    const libport::Error::errors_type& err = e.errors();
    foreach (std::string wrong_arg, err)
      libport::invalid_option(wrong_arg);
  }

  if (libport::opts::version.get())
    version();
  if (libport::opts::help.get())
    usage(opt_parser);

  // Connection mode.
  enum ConnectMode
  {
    /// Start a new engine and plug the module
    MODE_PLUGIN_START,
    /// Load the module in a running engine as a plugin
    MODE_PLUGIN_LOAD,
    /// Connect the module to a running engine (remote uobject)
    MODE_REMOTE
  };
  ConnectMode connect_mode = MODE_REMOTE;

  if (arg_plugin.get())
    connect_mode = MODE_PLUGIN_LOAD;
  if (arg_remote.get())
    connect_mode = MODE_REMOTE;
  if (arg_start.get())
    connect_mode = MODE_PLUGIN_START;

  /// Server host name.
  std::string host = libport::opts::host.value(UClient::default_host());
  if (libport::opts::host.filled())
    args << "--host" << host;

  /// Server port.
  int port = libport::opts::port.get<int>(urbi::UClient::URBI_PORT);
  if (libport::opts::port.filled())
    args << "--port" << libport::opts::port.value();

  if (arg_pfile.filled())
  {
    std::string file = arg_pfile.value();
    if (connect_mode == MODE_PLUGIN_LOAD)
      port = libport::file_contents_get<int>(file);
    args << "--port-file" << file;
  }
  args.insert(args.end(), arg_end.get().begin(), arg_end.get().end());

  /// Modules to load.
  if (connect_mode == MODE_PLUGIN_LOAD)
    return connect_plugin(host, port, modules);
  foreach (const std::string& s, modules)
    args << "--module" << s;

  // Open the right core library.
  if (arg_custom.filled())
    urbi_root.load_custom(arg_custom.value());
  else if (connect_mode == MODE_REMOTE)
    urbi_root.load_remote();
  else
    urbi_root.load_plugin();
  return urbi_root.urbi_main(args, true, true);
}

extern "C"
{
  int
  URBI_SDK_API
  urbi_launch(int argc, const char* argv[], UrbiRoot& root)
    try
    {
      return urbi_launch_(argc, argv, root);
    }
    catch (const std::exception& e)
    {
      std::cerr << argv[0] << ": " << e.what() << std::endl
                << libport::exit(EX_FAIL);
    }
}
<commit_msg>Urbi.Launch: fix.<commit_after>/*
 * Copyright (C) 2008-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#include <string>
#include <libport/cassert>
#include <cstdarg>
#include <libport/cstdlib>
#include <iostream>
#include <stdexcept>

#include <boost/assign/list_of.hpp>
using namespace boost::assign;

#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/debug.hh>
#include <libport/foreach.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>
#include <libport/unistd.h>
#include <libport/windows.hh>
#include <libport/option-parser.hh>

#include <urbi/exit.hh>
#include <urbi/package-info.hh>
#include <urbi/uclient.hh>
#include <urbi/urbi-root.hh>

GD_CATEGORY(Urbi.UrbiLaunch);

using namespace urbi;
using libport::program_name;

static UCallbackAction
onError(const UMessage& msg)
{
  LIBPORT_USE(msg);
  GD_FERROR("%s: load module error: %s", program_name(), msg.message);
  return URBI_CONTINUE;
}

static UCallbackAction
onDone(const UMessage&)
{
  ::exit(0);
}

static int
connect_plugin(const std::string& host, int port,
               const libport::cli_args_type& modules)
{
  UClient cl(host, port);
  if (cl.error())
    // UClient already displayed an error message.
    ::exit(1);
  cl.setErrorCallback(callback(&onError));
  cl.setCallback(callback(&onDone), "output");
  foreach (const std::string& m, modules)
    cl << "loadModule(\"" << m << "\");";
  cl << "output << 1;";
  while (true)
    sleep(1);
  return 0;
}

static void
usage(libport::OptionParser& parser)
{
  std::cout <<
    "usage: " << program_name() <<
    " [OPTIONS] MODULE_NAMES ... [-- UOPTIONS...]\n"
    "Start an UObject in either remote or plugin mode.\n"
              << parser <<
    "\n"
    "MODULE_NAMES is a list of modules.\n"
    "UOPTIONS are passed to urbi::main in remote and start modes.\n"
    "\n"
    "Exit values:\n"
    "  0  success\n"
    " " << EX_NOINPUT << "  some of the MODULES are missing\n"
    " " << EX_OSFILE << "  libuobject is missing\n"
    "  *  other kinds of errors\n"
    ;
  ::exit(EX_OK);
}

static
void
version()
{
  std::cout << urbi::package_info() << std::endl
            << libport::exit(EX_OK);
}

static
int
urbi_launch_(int argc, const char* argv[], UrbiRoot& urbi_root)
{
  libport::program_initialize(argc, argv);

  // The options passed to urbi::main.
  libport::cli_args_type args;

  args << argv[0];

  libport::OptionValue
    arg_custom("start using the shared library FILE", "custom", 'c', "FILE"),
    arg_pfile("file containing the port to listen to", "port-file", 0, "FILE");
  libport::OptionFlag
    arg_plugin("start as a plugin uobject on a running server", "plugin", 'p'),
    arg_remote("start as a remote uobject", "remote", 'r'),
    arg_start("start an urbi server and connect as plugin", "start", 's');
  libport::OptionsEnd arg_end;

  libport::OptionParser opt_parser;
  opt_parser << "Urbi-Launch options:"
	     << libport::opts::help
	     << libport::opts::version
	     << arg_custom
#ifndef LIBPORT_DEBUG_DISABLE
	     << libport::opts::debug
#endif
	     << "Mode selection:"
	     << arg_plugin
	     << arg_remote
	     << arg_start
	     << "Urbi-Launch options for plugin mode:"
	     << libport::opts::host
	     << libport::opts::port
	     << arg_pfile
	     << arg_end;

  // The list of modules.
  libport::cli_args_type modules;
  try
  {
    modules = opt_parser(libport::program_arguments());
  }
  catch (const libport::Error& e)
  {
    foreach (std::string wrong_arg, e.errors())
      libport::invalid_option(wrong_arg);
  }

  if (libport::opts::version.get())
    version();
  if (libport::opts::help.get())
    usage(opt_parser);

  // Connection mode.
  enum ConnectMode
  {
    /// Start a new engine and plug the module
    MODE_PLUGIN_START,
    /// Load the module in a running engine as a plugin
    MODE_PLUGIN_LOAD,
    /// Connect the module to a running engine (remote uobject)
    MODE_REMOTE
  };

  ConnectMode connect_mode =
    arg_plugin.get()   ? MODE_PLUGIN_LOAD
    : arg_remote.get() ? MODE_REMOTE
    : arg_start.get()  ? MODE_PLUGIN_START
    :                    MODE_REMOTE;

  // Server host name.
  std::string host = libport::opts::host.value(UClient::default_host());
  if (libport::opts::host.filled())
    args << "--host" << host;

  // Server port.
  int port = libport::opts::port.get<int>(urbi::UClient::URBI_PORT);
  if (libport::opts::port.filled())
    args << "--port" << libport::opts::port.value();

  if (arg_pfile.filled())
  {
    std::string file = arg_pfile.value();
    if (connect_mode == MODE_PLUGIN_LOAD)
      port = libport::file_contents_get<int>(file);
    args << "--port-file" << file;
  }

  // Modules to load.
  if (connect_mode == MODE_PLUGIN_LOAD)
    return connect_plugin(host, port, modules);
  foreach (const std::string& s, modules)
    args << "--module" << s;

  // Other arguments.
  args.insert(args.end(), arg_end.get().begin(), arg_end.get().end());

  // Open the right core library.
  if (arg_custom.filled())
    urbi_root.load_custom(arg_custom.value());
  else if (connect_mode == MODE_REMOTE)
    urbi_root.load_remote();
  else
    urbi_root.load_plugin();
  return urbi_root.urbi_main(args, true, true);
}

extern "C"
{
  int
  URBI_SDK_API
  urbi_launch(int argc, const char* argv[], UrbiRoot& root)
    try
    {
      return urbi_launch_(argc, argv, root);
    }
    catch (const std::exception& e)
    {
      std::cerr << argv[0] << ": " << e.what() << std::endl
                << libport::exit(EX_FAIL);
    }
}
<|endoftext|>


<commit_before>#pragma once
/*
* Covariant Script Programming Language
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2017 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
* Website: http://covariant.cn/cs
*
* Namespaces:
* cs: Main Namespace
* cs_impl: Implement Namespace
*/
// Mozart
#include "../include/mozart/static_stack.hpp"
#include "../include/mozart/random.hpp"
#include "../include/mozart/timer.hpp"
#include "../include/mozart/tree.hpp"
// LibDLL
#include "../include/libdll/dll.hpp"
// STL
#include <unordered_map>
#include <unordered_set>
#include <forward_list>
#include <functional>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <istream>
#include <ostream>
#include <utility>
#include <string>
#include <memory>
#include <cmath>
#include <deque>
#include <list>
#include <map>
// CovScript Headers
#include "./exceptions.hpp"
#include "./any.hpp"
#include "./typedef.hpp"

namespace cs {
// Version
	const std::string version="1.0.3";
// Output Precision
	static int output_precision=8;
// Callable and Function
	class callable final {
	public:
		using function_type=std::function<var(array&)>;
	private:
		function_type mFunc;
		bool mConstant=false;
	public:
		callable()=delete;
		callable(const callable&)=default;
		callable(const function_type& func,bool constant=false):mFunc(func),mConstant(constant) {}
		bool is_constant() const
		{
			return mConstant;
		}
		var call(array& args) const
		{
			return mFunc(args);
		}
	};
	class function final {
		friend class statement_return;
		mutable var mRetVal;
		std::deque<std::string> mArgs;
		std::deque<statement_base*> mBody;
		std::shared_ptr<std::unordered_map<string,var>> mData;
	public:
		function()=delete;
		function(const std::deque<std::string>& args,const std::deque<statement_base*>& body):mArgs(args),mBody(body) {}
		~function()=default;
		var call(array&) const;
		void set_data(const std::shared_ptr<std::unordered_map<string,var>>& data)
		{
			mData=data;
		}
	};
	class object_method final {
		var mObj;
		var mCallable;
	public:
		object_method()=delete;
		object_method(const var& obj,const var& callable):mObj(obj),mCallable(callable) {}
		~object_method()=default;
		const var& get_callable() const
		{
			return mCallable;
		}
		var operator()(array& args) const
		{
			args.push_front(mObj);
			var retval=mCallable.const_val<callable>().call(args);
			args.pop_front();
			return retval;
		}
	};
// Type and struct
	struct pointer final {
		var data;
		pointer()=default;
		pointer(const var& v):data(v) {}
		bool operator==(const pointer& ptr) const
		{
			return data.is_same(ptr.data);
		}
	};
	static const pointer null_pointer= {};
	struct type final {
		std::function<var()> constructor;
		std::size_t id;
		extension_t extensions;
		type()=delete;
		type(const std::function<var()>& c,std::size_t i):constructor(c),id(i) {}
		type(const std::function<var()>& c,std::size_t i,extension_t ext):constructor(c),id(i),extensions(ext) {}
		var& get_var(const std::string&) const;
	};
	class structure final {
		std::size_t m_hash;
		std::string m_name;
		std::shared_ptr<std::unordered_map<string,var>> m_data;
	public:
		structure()=delete;
		structure(std::size_t hash,const std::string& name,const std::shared_ptr<std::unordered_map<string,var>>& data):m_hash(hash),m_name(typeid(structure).name()+name),m_data(data) {}
		structure(const structure& s):m_hash(s.m_hash),m_name(s.m_name),m_data(std::make_shared<std::unordered_map<string,var>>(*s.m_data))
		{
			for(auto& it:*m_data) {
				it.second.clone();
				if(it.second.type()==typeid(function))
					it.second.val<function>(true).set_data(m_data);
			}
		}
		~structure()=default;
		std::shared_ptr<std::unordered_map<string,var>>& get_domain()
		{
			return m_data;
		}
		std::size_t get_hash() const
		{
			return m_hash;
		}
		var& get_var(const std::string& name) const
		{
			if(m_data->count(name)>0)
				return (*m_data)[name];
			else
				throw syntax_error("Struct \""+m_name+"\" have no member called \""+name+"\".");
		}
	};
	class struct_builder final {
		static std::size_t mCount;
		std::size_t mHash;
		std::string mName;
		std::deque<statement_base*> mMethod;
	public:
		struct_builder()=delete;
		struct_builder(const std::string& name,const std::deque<statement_base*>& method):mHash(++mCount),mName(name),mMethod(method) {}
		struct_builder(const struct_builder&)=default;
		~struct_builder()=default;
		std::size_t get_hash() const
		{
			return mHash;
		}
		var operator()();
	};
	std::size_t struct_builder::mCount=0;
// Internal Garbage Collection
	template<typename T>class garbage_collector final {
		std::forward_list<T*> table_new;
		std::forward_list<T*> table_delete;
	public:
		garbage_collector()=default;
		garbage_collector(const garbage_collector&)=delete;
		~garbage_collector()
		{
			for(auto& ptr:table_delete)
				table_new.remove(ptr);
			for(auto& ptr:table_new)
				delete ptr;
		}
		void add(void* ptr)
		{
			table_new.push_front(static_cast<T*>(ptr));
		}
		void remove(void* ptr)
		{
			table_delete.push_front(static_cast<T*>(ptr));
		}
	};
// Namespace and extensions
	class name_space final {
		std::unordered_map<string,var> m_data;
	public:
		name_space()=default;
		name_space(const name_space&)=delete;
		name_space(const std::unordered_map<string,var>& dat):m_data(dat) {}
		~name_space()=default;
		void add_var(const std::string& name,const var& var)
		{
			if(m_data.count(name)>0)
				m_data[name]=var;
			else
				m_data.emplace(name,var);
		}
		var& get_var(const std::string& name)
		{
			if(m_data.count(name)>0)
				return m_data[name];
			else
				throw syntax_error("Use of undefined variable \""+name+"\" in extension.");
		}
	};
	class name_space_holder final {
		name_space* m_ns=nullptr;
		cov::dll m_dll;
	public:
		name_space_holder()=delete;
		name_space_holder(name_space* ptr):m_ns(ptr) {}
		name_space_holder(const std::string& path):m_dll(path)
		{
			m_ns=reinterpret_cast<name_space*(*)()>(m_dll.get_address("__CS_EXTENSION__"))();
		}
		~name_space_holder()=default;
		var& get_var(const std::string& name)
		{
			if(m_ns==nullptr)
				throw internal_error("Use of nullptr of extension.");
			return m_ns->get_var(name);
		}
	};
// Var definition
	struct define_var_profile {
		std::string id;
		cov::tree<token_base*> expr;
	};
	void parse_define_var(cov::tree<token_base*>&,define_var_profile&);
// Implement
	var& type::get_var(const std::string& name) const
	{
		if(extensions.get()!=nullptr)
			return extensions->get_var(name);
		else
			throw syntax_error("Type does not support the extension");
	}
// literal format
	var parse_value(const std::string& str)
	{
		if(str=="true")
			return true;
		if(str=="false")
			return false;
		try {
			return number(std::stold(str));
		}
		catch(...) {
			return str;
		}
		return str;
	}
// Copy
	void copy_no_return(var& val)
	{
		val.clone();
		val.detach();
	}
	var copy(var val)
	{
		val.clone();
		val.detach();
		return val;
	}
}
namespace cs_impl {
	template<>void detach<cs::pair>(cs::pair& val)
	{
		cs::copy_no_return(val.first);
		cs::copy_no_return(val.second);
	}
	template<>void detach<cs::list>(cs::list& val)
	{
		for(auto& it:val)
			cs::copy_no_return(it);
	}
	template<>void detach<cs::array>(cs::array& val)
	{
		for(auto& it:val)
			cs::copy_no_return(it);
	}
	template<>void detach<cs::hash_map>(cs::hash_map& val)
	{
		for(auto& it:val)
			cs::copy_no_return(it.second);
	}
	template<>std::string to_string<cs::number>(const cs::number& val)
	{
		std::stringstream ss;
		std::string str;
		ss<<std::setprecision(cs::output_precision)<<val;
		ss>>str;
		return std::move(str);
	}
	template<>std::string to_string<char>(const char& c)
	{
		return std::move(std::string(1,c));
	}
}
<commit_msg>修复在某些编译器上的编译错误<commit_after>#pragma once
/*
* Covariant Script Programming Language
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2017 Michael Lee(李登淳)
* Email: mikecovlee@163.com
* Github: https://github.com/mikecovlee
* Website: http://covariant.cn/cs
*
* Namespaces:
* cs: Main Namespace
* cs_impl: Implement Namespace
*/
// Mozart
#include "../include/mozart/static_stack.hpp"
#include "../include/mozart/random.hpp"
#include "../include/mozart/timer.hpp"
#include "../include/mozart/tree.hpp"
// LibDLL
#include "../include/libdll/dll.hpp"
// STL
#include <unordered_map>
#include <unordered_set>
#include <forward_list>
#include <functional>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <istream>
#include <ostream>
#include <utility>
#include <cctype>
#include <string>
#include <memory>
#include <cmath>
#include <deque>
#include <list>
#include <map>
// CovScript Headers
#include "./exceptions.hpp"
#include "./any.hpp"
#include "./typedef.hpp"

namespace cs {
// Version
	const std::string version="1.0.3";
// Output Precision
	static int output_precision=8;
// Callable and Function
	class callable final {
	public:
		using function_type=std::function<var(array&)>;
	private:
		function_type mFunc;
		bool mConstant=false;
	public:
		callable()=delete;
		callable(const callable&)=default;
		callable(const function_type& func,bool constant=false):mFunc(func),mConstant(constant) {}
		bool is_constant() const
		{
			return mConstant;
		}
		var call(array& args) const
		{
			return mFunc(args);
		}
	};
	class function final {
		friend class statement_return;
		mutable var mRetVal;
		std::deque<std::string> mArgs;
		std::deque<statement_base*> mBody;
		std::shared_ptr<std::unordered_map<string,var>> mData;
	public:
		function()=delete;
		function(const std::deque<std::string>& args,const std::deque<statement_base*>& body):mArgs(args),mBody(body) {}
		~function()=default;
		var call(array&) const;
		void set_data(const std::shared_ptr<std::unordered_map<string,var>>& data)
		{
			mData=data;
		}
	};
	class object_method final {
		var mObj;
		var mCallable;
	public:
		object_method()=delete;
		object_method(const var& obj,const var& callable):mObj(obj),mCallable(callable) {}
		~object_method()=default;
		const var& get_callable() const
		{
			return mCallable;
		}
		var operator()(array& args) const
		{
			args.push_front(mObj);
			var retval=mCallable.const_val<callable>().call(args);
			args.pop_front();
			return retval;
		}
	};
// Type and struct
	struct pointer final {
		var data;
		pointer()=default;
		pointer(const var& v):data(v) {}
		bool operator==(const pointer& ptr) const
		{
			return data.is_same(ptr.data);
		}
	};
	static const pointer null_pointer= {};
	struct type final {
		std::function<var()> constructor;
		std::size_t id;
		extension_t extensions;
		type()=delete;
		type(const std::function<var()>& c,std::size_t i):constructor(c),id(i) {}
		type(const std::function<var()>& c,std::size_t i,extension_t ext):constructor(c),id(i),extensions(ext) {}
		var& get_var(const std::string&) const;
	};
	class structure final {
		std::size_t m_hash;
		std::string m_name;
		std::shared_ptr<std::unordered_map<string,var>> m_data;
	public:
		structure()=delete;
		structure(std::size_t hash,const std::string& name,const std::shared_ptr<std::unordered_map<string,var>>& data):m_hash(hash),m_name(typeid(structure).name()+name),m_data(data) {}
		structure(const structure& s):m_hash(s.m_hash),m_name(s.m_name),m_data(std::make_shared<std::unordered_map<string,var>>(*s.m_data))
		{
			for(auto& it:*m_data) {
				it.second.clone();
				if(it.second.type()==typeid(function))
					it.second.val<function>(true).set_data(m_data);
			}
		}
		~structure()=default;
		std::shared_ptr<std::unordered_map<string,var>>& get_domain()
		{
			return m_data;
		}
		std::size_t get_hash() const
		{
			return m_hash;
		}
		var& get_var(const std::string& name) const
		{
			if(m_data->count(name)>0)
				return (*m_data)[name];
			else
				throw syntax_error("Struct \""+m_name+"\" have no member called \""+name+"\".");
		}
	};
	class struct_builder final {
		static std::size_t mCount;
		std::size_t mHash;
		std::string mName;
		std::deque<statement_base*> mMethod;
	public:
		struct_builder()=delete;
		struct_builder(const std::string& name,const std::deque<statement_base*>& method):mHash(++mCount),mName(name),mMethod(method) {}
		struct_builder(const struct_builder&)=default;
		~struct_builder()=default;
		std::size_t get_hash() const
		{
			return mHash;
		}
		var operator()();
	};
	std::size_t struct_builder::mCount=0;
// Internal Garbage Collection
	template<typename T>class garbage_collector final {
		std::forward_list<T*> table_new;
		std::forward_list<T*> table_delete;
	public:
		garbage_collector()=default;
		garbage_collector(const garbage_collector&)=delete;
		~garbage_collector()
		{
			for(auto& ptr:table_delete)
				table_new.remove(ptr);
			for(auto& ptr:table_new)
				delete ptr;
		}
		void add(void* ptr)
		{
			table_new.push_front(static_cast<T*>(ptr));
		}
		void remove(void* ptr)
		{
			table_delete.push_front(static_cast<T*>(ptr));
		}
	};
// Namespace and extensions
	class name_space final {
		std::unordered_map<string,var> m_data;
	public:
		name_space()=default;
		name_space(const name_space&)=delete;
		name_space(const std::unordered_map<string,var>& dat):m_data(dat) {}
		~name_space()=default;
		void add_var(const std::string& name,const var& var)
		{
			if(m_data.count(name)>0)
				m_data[name]=var;
			else
				m_data.emplace(name,var);
		}
		var& get_var(const std::string& name)
		{
			if(m_data.count(name)>0)
				return m_data[name];
			else
				throw syntax_error("Use of undefined variable \""+name+"\" in extension.");
		}
	};
	class name_space_holder final {
		name_space* m_ns=nullptr;
		cov::dll m_dll;
	public:
		name_space_holder()=delete;
		name_space_holder(name_space* ptr):m_ns(ptr) {}
		name_space_holder(const std::string& path):m_dll(path)
		{
			m_ns=reinterpret_cast<name_space*(*)()>(m_dll.get_address("__CS_EXTENSION__"))();
		}
		~name_space_holder()=default;
		var& get_var(const std::string& name)
		{
			if(m_ns==nullptr)
				throw internal_error("Use of nullptr of extension.");
			return m_ns->get_var(name);
		}
	};
// Var definition
	struct define_var_profile {
		std::string id;
		cov::tree<token_base*> expr;
	};
	void parse_define_var(cov::tree<token_base*>&,define_var_profile&);
// Implement
	var& type::get_var(const std::string& name) const
	{
		if(extensions.get()!=nullptr)
			return extensions->get_var(name);
		else
			throw syntax_error("Type does not support the extension");
	}
// literal format
	var parse_value(const std::string& str)
	{
		if(str=="true")
			return true;
		if(str=="false")
			return false;
		try {
			return number(std::stold(str));
		}
		catch(...) {
			return str;
		}
		return str;
	}
// Copy
	void copy_no_return(var& val)
	{
		val.clone();
		val.detach();
	}
	var copy(var val)
	{
		val.clone();
		val.detach();
		return val;
	}
}
namespace cs_impl {
	template<>void detach<cs::pair>(cs::pair& val)
	{
		cs::copy_no_return(val.first);
		cs::copy_no_return(val.second);
	}
	template<>void detach<cs::list>(cs::list& val)
	{
		for(auto& it:val)
			cs::copy_no_return(it);
	}
	template<>void detach<cs::array>(cs::array& val)
	{
		for(auto& it:val)
			cs::copy_no_return(it);
	}
	template<>void detach<cs::hash_map>(cs::hash_map& val)
	{
		for(auto& it:val)
			cs::copy_no_return(it.second);
	}
	template<>std::string to_string<cs::number>(const cs::number& val)
	{
		std::stringstream ss;
		std::string str;
		ss<<std::setprecision(cs::output_precision)<<val;
		ss>>str;
		return std::move(str);
	}
	template<>std::string to_string<char>(const char& c)
	{
		return std::move(std::string(1,c));
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2015 CyberVision, Inc.
 *
 * 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.
 */

#include "ReportingManager.hpp"

#include "ConfigurationConstants.hpp"

namespace power_plant {

ReportingManager::ReportingManager(kaa::IKaaClient& kaaClient)
    : kaaClient_(kaaClient)
    , logUploadStrategy_(std::make_shared<kaa::DefaultLogUploadStrategy>(&kaaClient_.getChannelManager()))
{
    logUploadStrategy_->setCountThreshold(POWER_PLANT_REPORTING_FREQUENCY);
    kaaClient_.setLogUploadStrategy(logUploadStrategy_);
}

void ReportingManager::processConfiguration(const kaa::KaaRootConfiguration& configuration)
{
    std::lock_guard<std::mutex> configurationLock(strategyGuard_);
    logUploadStrategy_->setCountThreshold(configuration.reportingFrequency);
}

void ReportingManager::addReport(const kaa::KaaUserLogRecord& report)
{
    std::lock_guard<std::mutex> configurationLock(strategyGuard_);
    kaaClient_.addLogRecord(report);
}

} /* namespace power_plant */
<commit_msg>APP-9: Fix build of power plant client.<commit_after>/*
 * Copyright 2014-2015 CyberVision, Inc.
 *
 * 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.
 */

#include "ReportingManager.hpp"

#include "ConfigurationConstants.hpp"

namespace power_plant {

ReportingManager::ReportingManager(kaa::IKaaClient& kaaClient)
    : kaaClient_(kaaClient)
    , logUploadStrategy_(std::make_shared<kaa::DefaultLogUploadStrategy>())
{
    logUploadStrategy_->setCountThreshold(POWER_PLANT_REPORTING_FREQUENCY);
    logUploadStrategy_->setRetryPeriod(3);
    kaaClient_.setLogUploadStrategy(logUploadStrategy_);
}

void ReportingManager::processConfiguration(const kaa::KaaRootConfiguration& configuration)
{
    std::lock_guard<std::mutex> configurationLock(strategyGuard_);
    logUploadStrategy_->setCountThreshold(configuration.reportingFrequency);
}

void ReportingManager::addReport(const kaa::KaaUserLogRecord& report)
{
    std::lock_guard<std::mutex> configurationLock(strategyGuard_);
    kaaClient_.addLogRecord(report);
}

} /* namespace power_plant */
<|endoftext|>