<commit_before>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#include "libmesh_config.h"

// Currently, the EigenSystem should only be available
// if SLEPc support is enabled.
#if defined(LIBMESH_HAVE_SLEPC)

// C++ includes

// Local includes
#include "eigen_system.h"
#include "equation_systems.h"
#include "sparse_matrix.h"
#include "eigen_solver.h"
#include "dof_map.h"
#include "mesh.h"
#include "qoi_set.h"

// ------------------------------------------------------------
// EigenSystem implementation
EigenSystem::EigenSystem (EquationSystems& es,
			  const std::string& name,
			  const unsigned int number
			  ) :
  Parent           (es, name, number),
  matrix_A         (NULL),
  matrix_B         (NULL),
  eigen_solver     (EigenSolver<Number>::build()),
  _n_converged_eigenpairs (0),
  _n_iterations           (0),
  _is_generalized_eigenproblem (false),
  _eigen_problem_type (NHEP)
{
}

EigenSystem::~EigenSystem ()
{
  // clear data
  this->clear();
}

void EigenSystem::clear ()
{
  // Clear the parent data
  Parent::clear();

  // delete the matricies
  delete matrix_A;
  delete matrix_B;

  // NULL-out the matricies.
  matrix_A = NULL;
  matrix_B = NULL;

  // clear the solver
  eigen_solver->clear();

}

void EigenSystem::set_eigenproblem_type (EigenProblemType ept)
{
  _eigen_problem_type = ept;

  eigen_solver->set_eigenproblem_type(ept);

  // std::cout<< "The Problem type is set to be: "<<std::endl;

  switch (_eigen_problem_type)
    {
    case HEP: // std::cout<<"Hermitian"<<std::endl;
      break;

    case NHEP: // std::cout<<"Non-Hermitian"<<std::endl;
      break;

    case GHEP: // std::cout<<"Gerneralized Hermitian"<<std::endl;
      break;

    case GNHEP: // std::cout<<"Generalized Non-Hermitian"<<std::endl;
      break;

    default: // std::cout<<"not properly specified"<<std::endl;
      libmesh_error();
      break;

    }
}

void EigenSystem::init_data ()
{

  // initialize parent data
  Parent::init_data();

  // define the type of eigenproblem
  if (_eigen_problem_type == GNHEP || _eigen_problem_type == GHEP)
    _is_generalized_eigenproblem = true;

  // build the system matrix
  matrix_A = SparseMatrix<Number>::build().release();

  // add matrix to the _dof_map
  // and compute the sparsity
  DofMap& dof_map = this->get_dof_map();

  dof_map.attach_matrix(*matrix_A);

  // build matrix_B only in case of a
  // generalized problem
  if (_is_generalized_eigenproblem)
    {
      matrix_B = SparseMatrix<Number>::build().release();
      dof_map.attach_matrix(*matrix_B);
    }

  dof_map.compute_sparsity(this->get_mesh());

  // initialize and zero system matrix
  matrix_A->init();
  matrix_A->zero();

  // eventually initialize and zero system matrix_B
  if (_is_generalized_eigenproblem)
    {
      matrix_B->init();
      matrix_B->zero();
    }

}

void EigenSystem::reinit ()
{
  // initialize parent data
  Parent::reinit();

}

void EigenSystem::solve ()
{

  // A reference to the EquationSystems
  EquationSystems& es = this->get_equation_systems();

  // check that necessary parameters have been set
  libmesh_assert (es.parameters.have_parameter<unsigned int>("eigenpairs"));
  libmesh_assert (es.parameters.have_parameter<unsigned int>("basis vectors"));

  if (this->assemble_before_solve)
    // Assemble the linear system
    this->assemble ();

  // Get the tolerance for the solver and the maximum
  // number of iterations. Here, we simply adopt the linear solver
  // specific parameters.
  const Real tol            =
    es.parameters.get<Real>("linear solver tolerance");

  const unsigned int maxits =
    es.parameters.get<unsigned int>("linear solver maximum iterations");

  const unsigned int nev    =
    es.parameters.get<unsigned int>("eigenpairs");

  const unsigned int ncv    =
    es.parameters.get<unsigned int>("basis vectors");

  std::pair<unsigned int, unsigned int> solve_data;

  // call the solver depending on the type of eigenproblem
  if (_is_generalized_eigenproblem)
    {
      //in case of a generalized eigenproblem
      solve_data = eigen_solver->solve_generalized (*matrix_A,*matrix_B, nev, ncv, tol, maxits);

    }

  else
    {
      libmesh_assert (matrix_B == NULL);

      //in case of a standard eigenproblem
      solve_data = eigen_solver->solve_standard (*matrix_A, nev, ncv, tol, maxits);

    }

  this->_n_converged_eigenpairs = solve_data.first;
  this->_n_iterations           = solve_data.second;

}

void EigenSystem::sensitivity_solve (const ParameterVector&)
{
  libmesh_not_implemented();
}

void EigenSystem::adjoint_solve (const QoiSet&)
{
  libmesh_not_implemented();
}

void EigenSystem::adjoint_qoi_parameter_sensitivity
  (const QoISet&,
   const ParameterVector&,
   SensitivityData&)
{
  libmesh_not_implemented();
}

void EigenSystem::forward_qoi_parameter_sensitivity
  (const QoISet&,
   const ParameterVector&,
   SensitivityData&)
{
  libmesh_not_implemented();
}

void EigenSystem::assemble ()
{

  // Assemble the linear system
  Parent::assemble ();

}

std::pair<Real, Real> EigenSystem::get_eigenpair (unsigned int i)
{
  // call the eigen_solver get_eigenpair method
  return eigen_solver->get_eigenpair (i, *solution);
}

#endif // LIBMESH_HAVE_SLEPC
<commit_msg>Another small fix for --enable_slepc<commit_after>// $Id$

// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#include "libmesh_config.h"

// Currently, the EigenSystem should only be available
// if SLEPc support is enabled.
#if defined(LIBMESH_HAVE_SLEPC)

// C++ includes

// Local includes
#include "eigen_system.h"
#include "equation_systems.h"
#include "sparse_matrix.h"
#include "eigen_solver.h"
#include "dof_map.h"
#include "mesh.h"
#include "qoi_set.h"

// ------------------------------------------------------------
// EigenSystem implementation
EigenSystem::EigenSystem (EquationSystems& es,
			  const std::string& name,
			  const unsigned int number
			  ) :
  Parent           (es, name, number),
  matrix_A         (NULL),
  matrix_B         (NULL),
  eigen_solver     (EigenSolver<Number>::build()),
  _n_converged_eigenpairs (0),
  _n_iterations           (0),
  _is_generalized_eigenproblem (false),
  _eigen_problem_type (NHEP)
{
}

EigenSystem::~EigenSystem ()
{
  // clear data
  this->clear();
}

void EigenSystem::clear ()
{
  // Clear the parent data
  Parent::clear();

  // delete the matricies
  delete matrix_A;
  delete matrix_B;

  // NULL-out the matricies.
  matrix_A = NULL;
  matrix_B = NULL;

  // clear the solver
  eigen_solver->clear();

}

void EigenSystem::set_eigenproblem_type (EigenProblemType ept)
{
  _eigen_problem_type = ept;

  eigen_solver->set_eigenproblem_type(ept);

  // std::cout<< "The Problem type is set to be: "<<std::endl;

  switch (_eigen_problem_type)
    {
    case HEP: // std::cout<<"Hermitian"<<std::endl;
      break;

    case NHEP: // std::cout<<"Non-Hermitian"<<std::endl;
      break;

    case GHEP: // std::cout<<"Gerneralized Hermitian"<<std::endl;
      break;

    case GNHEP: // std::cout<<"Generalized Non-Hermitian"<<std::endl;
      break;

    default: // std::cout<<"not properly specified"<<std::endl;
      libmesh_error();
      break;

    }
}

void EigenSystem::init_data ()
{

  // initialize parent data
  Parent::init_data();

  // define the type of eigenproblem
  if (_eigen_problem_type == GNHEP || _eigen_problem_type == GHEP)
    _is_generalized_eigenproblem = true;

  // build the system matrix
  matrix_A = SparseMatrix<Number>::build().release();

  // add matrix to the _dof_map
  // and compute the sparsity
  DofMap& dof_map = this->get_dof_map();

  dof_map.attach_matrix(*matrix_A);

  // build matrix_B only in case of a
  // generalized problem
  if (_is_generalized_eigenproblem)
    {
      matrix_B = SparseMatrix<Number>::build().release();
      dof_map.attach_matrix(*matrix_B);
    }

  dof_map.compute_sparsity(this->get_mesh());

  // initialize and zero system matrix
  matrix_A->init();
  matrix_A->zero();

  // eventually initialize and zero system matrix_B
  if (_is_generalized_eigenproblem)
    {
      matrix_B->init();
      matrix_B->zero();
    }

}

void EigenSystem::reinit ()
{
  // initialize parent data
  Parent::reinit();

}

void EigenSystem::solve ()
{

  // A reference to the EquationSystems
  EquationSystems& es = this->get_equation_systems();

  // check that necessary parameters have been set
  libmesh_assert (es.parameters.have_parameter<unsigned int>("eigenpairs"));
  libmesh_assert (es.parameters.have_parameter<unsigned int>("basis vectors"));

  if (this->assemble_before_solve)
    // Assemble the linear system
    this->assemble ();

  // Get the tolerance for the solver and the maximum
  // number of iterations. Here, we simply adopt the linear solver
  // specific parameters.
  const Real tol            =
    es.parameters.get<Real>("linear solver tolerance");

  const unsigned int maxits =
    es.parameters.get<unsigned int>("linear solver maximum iterations");

  const unsigned int nev    =
    es.parameters.get<unsigned int>("eigenpairs");

  const unsigned int ncv    =
    es.parameters.get<unsigned int>("basis vectors");

  std::pair<unsigned int, unsigned int> solve_data;

  // call the solver depending on the type of eigenproblem
  if (_is_generalized_eigenproblem)
    {
      //in case of a generalized eigenproblem
      solve_data = eigen_solver->solve_generalized (*matrix_A,*matrix_B, nev, ncv, tol, maxits);

    }

  else
    {
      libmesh_assert (matrix_B == NULL);

      //in case of a standard eigenproblem
      solve_data = eigen_solver->solve_standard (*matrix_A, nev, ncv, tol, maxits);

    }

  this->_n_converged_eigenpairs = solve_data.first;
  this->_n_iterations           = solve_data.second;

}

void EigenSystem::assemble_residual_derivatives (const ParameterVector&)
{
  libmesh_not_implemented();
}

void EigenSystem::sensitivity_solve (const ParameterVector&)
{
  libmesh_not_implemented();
}

void EigenSystem::adjoint_solve (const QoISet&)
{
  libmesh_not_implemented();
}

void EigenSystem::adjoint_qoi_parameter_sensitivity
  (const QoISet&,
   const ParameterVector&,
   SensitivityData&)
{
  libmesh_not_implemented();
}

void EigenSystem::forward_qoi_parameter_sensitivity
  (const QoISet&,
   const ParameterVector&,
   SensitivityData&)
{
  libmesh_not_implemented();
}

void EigenSystem::assemble ()
{

  // Assemble the linear system
  Parent::assemble ();

}

std::pair<Real, Real> EigenSystem::get_eigenpair (unsigned int i)
{
  // call the eigen_solver get_eigenpair method
  return eigen_solver->get_eigenpair (i, *solution);
}

#endif // LIBMESH_HAVE_SLEPC
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: parsersvc.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-17 13:35:35 $
 *
 *  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: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "parsersvc.hxx"

#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif
#ifndef CONFIGMGR_XML_SCHEMAPARSER_HXX
#include "schemaparser.hxx"
#endif
#ifndef CONFIGMGR_XML_LAYERPARSER_HXX
#include "layerparser.hxx"
#endif

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

#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMA_HPP_
#include <com/sun/star/configuration/backend/XSchema.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_
#include <com/sun/star/configuration/backend/XLayer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_
#include <com/sun/star/lang/WrappedTargetException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_MALFORMEDDATAEXCEPTION_HPP_
#include <com/sun/star/configuration/backend/MalformedDataException.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
// -----------------------------------------------------------------------------

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace xml
    {
// -----------------------------------------------------------------------------
        namespace uno   = ::com::sun::star::uno;
        namespace lang  = ::com::sun::star::lang;
        namespace io    = ::com::sun::star::io;
        namespace sax   = ::com::sun::star::xml::sax;
        namespace backenduno = ::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------

template <class BackendInterface>
struct ParserServiceTraits;
// -----------------------------------------------------------------------------
static inline void clear(OUString & _rs) { _rs = OUString(); }

// -----------------------------------------------------------------------------
template <class BackendInterface>
ParserService<BackendInterface>::ParserService(CreationArg _xContext)
: m_xServiceFactory(_xContext->getServiceManager(), uno::UNO_QUERY)
, m_aInputSource()
{
    if (!m_xServiceFactory.is())
    {
        OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration Parser: Context has no service factory"));
        throw uno::RuntimeException(sMessage,NULL);
    }
}
// -----------------------------------------------------------------------------

// XInitialization
template <class BackendInterface>
void SAL_CALL
    ParserService<BackendInterface>::initialize( const uno::Sequence< uno::Any >& aArguments )
        throw (uno::Exception, uno::RuntimeException)
{
    switch(aArguments.getLength())
    {
    case 0:
        break;

    case 1:
        if (aArguments[0] >>= m_aInputSource)
            break;

        if (aArguments[0] >>= m_aInputSource.aInputStream)
            break;

        {
            OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Cannot use argument to initialize a Configuration Parser"
                                                            "- InputSource or XInputStream expected"));
            throw lang::IllegalArgumentException(sMessage,*this,1);
        }
    default:
        {
            OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Too many arguments to initialize a Configuration Parser"));
            throw lang::IllegalArgumentException(sMessage,*this,0);
        }
    }
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
inline
ServiceInfoHelper ParserService<BackendInterface>::getServiceInfo()
{
    return ParserServiceTraits<BackendInterface>::getServiceInfo();
}
// -----------------------------------------------------------------------------

// XServiceInfo
template <class BackendInterface>
::rtl::OUString SAL_CALL
    ParserService<BackendInterface>::getImplementationName(  )
        throw (uno::RuntimeException)
{
    return getServiceInfo().getImplementationName();
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
sal_Bool SAL_CALL
    ParserService<BackendInterface>::supportsService( const ::rtl::OUString& ServiceName )
        throw (uno::RuntimeException)
{
    return getServiceInfo().supportsService( ServiceName );
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
uno::Sequence< ::rtl::OUString > SAL_CALL
    ParserService<BackendInterface>::getSupportedServiceNames(  )
        throw (uno::RuntimeException)
{
    return getServiceInfo().getSupportedServiceNames( );
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
void SAL_CALL
    ParserService<BackendInterface>::setInputStream( const uno::Reference< io::XInputStream >& aStream )
        throw (uno::RuntimeException)
{
    clear( m_aInputSource.sEncoding );
    clear( m_aInputSource.sSystemId );
    // clear( m_aInputSource.sPublicId );
    m_aInputSource.aInputStream = aStream;
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
uno::Reference< io::XInputStream > SAL_CALL
    ParserService<BackendInterface>::getInputStream(  )
        throw (uno::RuntimeException)
{
    return m_aInputSource.aInputStream;
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
void ParserService<BackendInterface>::parse(uno::Reference< sax::XDocumentHandler > const & _xHandler)
//    throw (backenduno::MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    OSL_PRECOND( _xHandler.is(), "ParserService: No SAX handler to parse to");

    typedef uno::Reference< sax::XParser > SaxParser;

    rtl::OUString const k_sSaxParserService( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Parser"));

    SaxParser xParser = SaxParser::query( m_xServiceFactory->createInstance(k_sSaxParserService) );

    if (!xParser.is())
    {
        OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration Parser: Cannot create SAX Parser"));
        throw uno::RuntimeException(sMessage,*this);
    }

    try
    {
        xParser->setDocumentHandler(_xHandler);
        xParser->parseStream( m_aInputSource );
    }
    catch (sax::SAXException & e)
    {
        uno::Any aWrapped = e.WrappedException.hasValue() ? e.WrappedException : uno::makeAny( e );
        OUString sSAXMessage = e.Message;

        // Expatwrap SAX service doubly wraps its errors ??
        sax::SAXException eInner;
        if (aWrapped >>= eInner)
        {
            if (eInner.WrappedException.hasValue()) aWrapped = eInner.WrappedException;

            rtl::OUStringBuffer sMsgBuf(eInner.Message);
            sMsgBuf.appendAscii("- {Parser Error: ").append(sSAXMessage).appendAscii(" }.");
            sSAXMessage = sMsgBuf.makeStringAndClear();
        }

        static backenduno::MalformedDataException const * const forDataError = 0;
        static lang::WrappedTargetException const * const forWrappedError = 0;
        if (aWrapped.isExtractableTo(getCppuType(forDataError)) ||
            aWrapped.isExtractableTo(getCppuType(forWrappedError)))
        {
            cppu::throwException(aWrapped);

            OSL_ASSERT(!"not reached");
        }

        rtl::OUStringBuffer sMessageBuf;
        sMessageBuf.appendAscii("Configuration Parser: a ").append( aWrapped.getValueTypeName() );
        sMessageBuf.appendAscii(" occurred while parsing: ");
        sMessageBuf.append(sSAXMessage);

        throw lang::WrappedTargetException(sMessageBuf.makeStringAndClear(),*this,aWrapped);
    }
}

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
AsciiServiceName const aSchemaParserServices[] =
{
    "com.sun.star.configuration.backend.xml.SchemaParser",
    0
};
const ServiceImplementationInfo aSchemaParserSI =
{
    "com.sun.star.comp.configuration.backend.xml.SchemaParser",
    aSchemaParserServices,
    0
};
// -----------------------------------------------------------------------------
AsciiServiceName const aLayerParserServices[] =
{
    "com.sun.star.configuration.backend.xml.LayerParser",
    0
};
const ServiceImplementationInfo aLayerParserSI =
{
    "com.sun.star.comp.configuration.backend.xml.LayerParser",
    aLayerParserServices,
    0
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
template <>
struct ParserServiceTraits< backenduno::XSchema >
{
    typedef backenduno::XSchemaHandler Handler;

    static ServiceImplementationInfo const * getServiceInfo()
    { return & aSchemaParserSI; }
};
// -----------------------------------------------------------------------------
template <>
struct ParserServiceTraits< backenduno::XLayer >
{
    typedef backenduno::XLayerHandler Handler;

    static ServiceImplementationInfo const * getServiceInfo()
    { return & aLayerParserSI; }
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

typedef ParserService< backenduno::XSchema > SchemaParserService_Base;

class SchemaParserService : public SchemaParserService_Base
{
public:
    typedef SchemaParser::HandlerRef HandlerArg;

    SchemaParserService(CreationArg _xContext)
    : SchemaParserService_Base(_xContext)
    {
    }

    virtual void SAL_CALL readSchema( HandlerArg const & aHandler )
        throw (backenduno::MalformedDataException, lang::WrappedTargetException,
               lang::NullPointerException, uno::RuntimeException);

    virtual void SAL_CALL readComponent( HandlerArg const & aHandler )
        throw (backenduno::MalformedDataException, lang::WrappedTargetException,
               lang::NullPointerException, uno::RuntimeException);

    virtual void SAL_CALL readTemplates( HandlerArg const & aHandler )
        throw (backenduno::MalformedDataException, lang::WrappedTargetException,
               lang::NullPointerException, uno::RuntimeException);
};
// -----------------------------------------------------------------------------

typedef ParserService< backenduno::XLayer > LayerParserService_Base;

class LayerParserService : public LayerParserService_Base
{
public:
    typedef LayerParser::HandlerRef HandlerArg;

    LayerParserService(CreationArg _xContext)
    : LayerParserService_Base(_xContext)
    {
    }

    virtual void SAL_CALL readData( HandlerArg const & aHandler )
        throw (backenduno::MalformedDataException, lang::WrappedTargetException,
               lang::NullPointerException, uno::RuntimeException);
};

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL instantiateSchemaParser( CreationContext const& xContext )
{
    return * new SchemaParserService(xContext);
}
uno::Reference< uno::XInterface > SAL_CALL instantiateLayerParser( CreationContext const& xContext )
{
    return * new LayerParserService(xContext);
}
// -----------------------------------------------------------------------------
const ServiceRegistrationInfo* getSchemaParserServiceInfo()
{ return getRegistrationInfo(& aSchemaParserSI); }
const ServiceRegistrationInfo* getLayerParserServiceInfo()
{ return getRegistrationInfo(& aLayerParserSI); }
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
static OUString nullHandlerMessage(char const * where)
{
    OSL_ASSERT(where);
    OUString msg = OUString::createFromAscii(where);
    return msg.concat(OUString::createFromAscii(": Error - NULL handler passed."));
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readSchema( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
    throw (backenduno::MalformedDataException, lang::WrappedTargetException,
           lang::NullPointerException, uno::RuntimeException)
{
    if (!aHandler.is())
        throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readSchema"),*this);

    SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectAll);
    this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readComponent( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
    throw (backenduno::MalformedDataException, lang::WrappedTargetException,
           lang::NullPointerException, uno::RuntimeException)
{
    if (!aHandler.is())
        throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readComponent"),*this);

    SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectComponent);
    this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readTemplates( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
    throw (backenduno::MalformedDataException, lang::WrappedTargetException,
           lang::NullPointerException, uno::RuntimeException)
{
    if (!aHandler.is())
        throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readTemplates"),*this);

    SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectTemplates);
    this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL LayerParserService::readData( uno::Reference< backenduno::XLayerHandler > const & aHandler )
    throw (backenduno::MalformedDataException, lang::WrappedTargetException,
           lang::NullPointerException, uno::RuntimeException)
{
    if (!aHandler.is())
        throw lang::NullPointerException(nullHandlerMessage("LayerParserService::readData"),*this);

    SaxHandler xHandler = new LayerParser(this->getServiceFactory(),aHandler);
    this->parse( xHandler );
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
    } // namespace

// -----------------------------------------------------------------------------
} // namespace

<commit_msg>INTEGRATION: CWS cfgapi (1.6.94); FILE MERGED 2004/05/07 10:47:02 ssmith 1.6.94.1: #112671# clearing inputStream after initial parsing<commit_after>/*************************************************************************
 *
 *  $RCSfile: parsersvc.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2004-06-18 15:52:22 $
 *
 *  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: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "parsersvc.hxx"

#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif
#ifndef CONFIGMGR_XML_SCHEMAPARSER_HXX
#include "schemaparser.hxx"
#endif
#ifndef CONFIGMGR_XML_LAYERPARSER_HXX
#include "layerparser.hxx"
#endif

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

#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMA_HPP_
#include <com/sun/star/configuration/backend/XSchema.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_
#include <com/sun/star/configuration/backend/XLayer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_
#include <com/sun/star/lang/WrappedTargetException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_MALFORMEDDATAEXCEPTION_HPP_
#include <com/sun/star/configuration/backend/MalformedDataException.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif
// -----------------------------------------------------------------------------

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace xml
    {
// -----------------------------------------------------------------------------
        namespace uno   = ::com::sun::star::uno;
        namespace lang  = ::com::sun::star::lang;
        namespace io    = ::com::sun::star::io;
        namespace sax   = ::com::sun::star::xml::sax;
        namespace backenduno = ::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------

template <class BackendInterface>
struct ParserServiceTraits;
// -----------------------------------------------------------------------------
static inline void clear(OUString & _rs) { _rs = OUString(); }

// -----------------------------------------------------------------------------
template <class BackendInterface>
ParserService<BackendInterface>::ParserService(CreationArg _xContext)
: m_xServiceFactory(_xContext->getServiceManager(), uno::UNO_QUERY)
, m_aInputSource()
{
    if (!m_xServiceFactory.is())
    {
        OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration Parser: Context has no service factory"));
        throw uno::RuntimeException(sMessage,NULL);
    }
}
// -----------------------------------------------------------------------------

// XInitialization
template <class BackendInterface>
void SAL_CALL
    ParserService<BackendInterface>::initialize( const uno::Sequence< uno::Any >& aArguments )
        throw (uno::Exception, uno::RuntimeException)
{
    switch(aArguments.getLength())
    {
    case 0:
        break;

    case 1:
        if (aArguments[0] >>= m_aInputSource)
            break;

        if (aArguments[0] >>= m_aInputSource.aInputStream)
            break;

        {
            OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Cannot use argument to initialize a Configuration Parser"
                                                            "- InputSource or XInputStream expected"));
            throw lang::IllegalArgumentException(sMessage,*this,1);
        }
    default:
        {
            OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Too many arguments to initialize a Configuration Parser"));
            throw lang::IllegalArgumentException(sMessage,*this,0);
        }
    }
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
inline
ServiceInfoHelper ParserService<BackendInterface>::getServiceInfo()
{
    return ParserServiceTraits<BackendInterface>::getServiceInfo();
}
// -----------------------------------------------------------------------------

// XServiceInfo
template <class BackendInterface>
::rtl::OUString SAL_CALL
    ParserService<BackendInterface>::getImplementationName(  )
        throw (uno::RuntimeException)
{
    return getServiceInfo().getImplementationName();
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
sal_Bool SAL_CALL
    ParserService<BackendInterface>::supportsService( const ::rtl::OUString& ServiceName )
        throw (uno::RuntimeException)
{
    return getServiceInfo().supportsService( ServiceName );
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
uno::Sequence< ::rtl::OUString > SAL_CALL
    ParserService<BackendInterface>::getSupportedServiceNames(  )
        throw (uno::RuntimeException)
{
    return getServiceInfo().getSupportedServiceNames( );
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
void SAL_CALL
    ParserService<BackendInterface>::setInputStream( const uno::Reference< io::XInputStream >& aStream )
        throw (uno::RuntimeException)
{
    clear( m_aInputSource.sEncoding );
    clear( m_aInputSource.sSystemId );
    // clear( m_aInputSource.sPublicId );
    m_aInputSource.aInputStream = aStream;
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
uno::Reference< io::XInputStream > SAL_CALL
    ParserService<BackendInterface>::getInputStream(  )
        throw (uno::RuntimeException)
{
    return m_aInputSource.aInputStream;
}
// -----------------------------------------------------------------------------

template <class BackendInterface>
void ParserService<BackendInterface>::parse(uno::Reference< sax::XDocumentHandler > const & _xHandler)
//    throw (backenduno::MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    OSL_PRECOND( _xHandler.is(), "ParserService: No SAX handler to parse to");

    typedef uno::Reference< sax::XParser > SaxParser;

    rtl::OUString const k_sSaxParserService( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Parser"));

    SaxParser xParser = SaxParser::query( m_xServiceFactory->createInstance(k_sSaxParserService) );

    if (!xParser.is())
    {
        OUString sMessage( RTL_CONSTASCII_USTRINGPARAM("Configuration Parser: Cannot create SAX Parser"));
        throw uno::RuntimeException(sMessage,*this);
    }

    try
    {
        xParser->setDocumentHandler(_xHandler);

        sax::InputSource aInputSourceCopy = m_aInputSource;
        //Set the sax input stream to null, an input stream can only be parsed once
        m_aInputSource.aInputStream = NULL;
        xParser->parseStream( aInputSourceCopy );
    }
    catch (sax::SAXException & e)
    {
        uno::Any aWrapped = e.WrappedException.hasValue() ? e.WrappedException : uno::makeAny( e );
        OUString sSAXMessage = e.Message;

        // Expatwrap SAX service doubly wraps its errors ??
        sax::SAXException eInner;
        if (aWrapped >>= eInner)
        {
            if (eInner.WrappedException.hasValue()) aWrapped = eInner.WrappedException;

            rtl::OUStringBuffer sMsgBuf(eInner.Message);
            sMsgBuf.appendAscii("- {Parser Error: ").append(sSAXMessage).appendAscii(" }.");
            sSAXMessage = sMsgBuf.makeStringAndClear();
        }

        static backenduno::MalformedDataException const * const forDataError = 0;
        static lang::WrappedTargetException const * const forWrappedError = 0;
        if (aWrapped.isExtractableTo(getCppuType(forDataError)) ||
            aWrapped.isExtractableTo(getCppuType(forWrappedError)))
        {
            cppu::throwException(aWrapped);

            OSL_ASSERT(!"not reached");
        }

        rtl::OUStringBuffer sMessageBuf;
        sMessageBuf.appendAscii("Configuration Parser: a ").append( aWrapped.getValueTypeName() );
        sMessageBuf.appendAscii(" occurred while parsing: ");
        sMessageBuf.append(sSAXMessage);

        throw lang::WrappedTargetException(sMessageBuf.makeStringAndClear(),*this,aWrapped);
    }
}

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
AsciiServiceName const aSchemaParserServices[] =
{
    "com.sun.star.configuration.backend.xml.SchemaParser",
    0
};
const ServiceImplementationInfo aSchemaParserSI =
{
    "com.sun.star.comp.configuration.backend.xml.SchemaParser",
    aSchemaParserServices,
    0
};
// -----------------------------------------------------------------------------
AsciiServiceName const aLayerParserServices[] =
{
    "com.sun.star.configuration.backend.xml.LayerParser",
    0
};
const ServiceImplementationInfo aLayerParserSI =
{
    "com.sun.star.comp.configuration.backend.xml.LayerParser",
    aLayerParserServices,
    0
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
template <>
struct ParserServiceTraits< backenduno::XSchema >
{
    typedef backenduno::XSchemaHandler Handler;

    static ServiceImplementationInfo const * getServiceInfo()
    { return & aSchemaParserSI; }
};
// -----------------------------------------------------------------------------
template <>
struct ParserServiceTraits< backenduno::XLayer >
{
    typedef backenduno::XLayerHandler Handler;

    static ServiceImplementationInfo const * getServiceInfo()
    { return & aLayerParserSI; }
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

typedef ParserService< backenduno::XSchema > SchemaParserService_Base;

class SchemaParserService : public SchemaParserService_Base
{
public:
    typedef SchemaParser::HandlerRef HandlerArg;

    SchemaParserService(CreationArg _xContext)
    : SchemaParserService_Base(_xContext)
    {
    }

    virtual void SAL_CALL readSchema( HandlerArg const & aHandler )
        throw (backenduno::MalformedDataException, lang::WrappedTargetException,
               lang::NullPointerException, uno::RuntimeException);

    virtual void SAL_CALL readComponent( HandlerArg const & aHandler )
        throw (backenduno::MalformedDataException, lang::WrappedTargetException,
               lang::NullPointerException, uno::RuntimeException);

    virtual void SAL_CALL readTemplates( HandlerArg const & aHandler )
        throw (backenduno::MalformedDataException, lang::WrappedTargetException,
               lang::NullPointerException, uno::RuntimeException);
};
// -----------------------------------------------------------------------------

typedef ParserService< backenduno::XLayer > LayerParserService_Base;

class LayerParserService : public LayerParserService_Base
{
public:
    typedef LayerParser::HandlerRef HandlerArg;

    LayerParserService(CreationArg _xContext)
    : LayerParserService_Base(_xContext)
    {
    }

    virtual void SAL_CALL readData( HandlerArg const & aHandler )
        throw (backenduno::MalformedDataException, lang::WrappedTargetException,
               lang::NullPointerException, uno::RuntimeException);
};

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL instantiateSchemaParser( CreationContext const& xContext )
{
    return * new SchemaParserService(xContext);
}
uno::Reference< uno::XInterface > SAL_CALL instantiateLayerParser( CreationContext const& xContext )
{
    return * new LayerParserService(xContext);
}
// -----------------------------------------------------------------------------
const ServiceRegistrationInfo* getSchemaParserServiceInfo()
{ return getRegistrationInfo(& aSchemaParserSI); }
const ServiceRegistrationInfo* getLayerParserServiceInfo()
{ return getRegistrationInfo(& aLayerParserSI); }
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
static OUString nullHandlerMessage(char const * where)
{
    OSL_ASSERT(where);
    OUString msg = OUString::createFromAscii(where);
    return msg.concat(OUString::createFromAscii(": Error - NULL handler passed."));
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readSchema( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
    throw (backenduno::MalformedDataException, lang::WrappedTargetException,
           lang::NullPointerException, uno::RuntimeException)
{
    if (!aHandler.is())
        throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readSchema"),*this);

    SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectAll);
    this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readComponent( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
    throw (backenduno::MalformedDataException, lang::WrappedTargetException,
           lang::NullPointerException, uno::RuntimeException)
{
    if (!aHandler.is())
        throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readComponent"),*this);

    SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectComponent);
    this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL SchemaParserService::readTemplates( uno::Reference< backenduno::XSchemaHandler > const & aHandler )
    throw (backenduno::MalformedDataException, lang::WrappedTargetException,
           lang::NullPointerException, uno::RuntimeException)
{
    if (!aHandler.is())
        throw lang::NullPointerException(nullHandlerMessage("SchemaParserService::readTemplates"),*this);

    SaxHandler xHandler = new SchemaParser(this->getServiceFactory(),aHandler, SchemaParser::selectTemplates);
    this->parse( xHandler );
}
// -----------------------------------------------------------------------------
void SAL_CALL LayerParserService::readData( uno::Reference< backenduno::XLayerHandler > const & aHandler )
    throw (backenduno::MalformedDataException, lang::WrappedTargetException,
           lang::NullPointerException, uno::RuntimeException)
{
    if (!aHandler.is())
        throw lang::NullPointerException(nullHandlerMessage("LayerParserService::readData"),*this);

    SaxHandler xHandler = new LayerParser(this->getServiceFactory(),aHandler);
    this->parse( xHandler );
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
    } // namespace

// -----------------------------------------------------------------------------
} // namespace

<|endoftext|>


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

#include "base/auto_reset.h"
#include "base/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_writer.h"
#include "base/path_service.h"
#include "base/safe_numerics.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/apps/app_browsertest_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/media_galleries/media_file_system_registry.h"
#include "chrome/browser/media_galleries/media_galleries_preferences.h"
#include "chrome/browser/media_galleries/media_galleries_test_util.h"
#include "chrome/browser/storage_monitor/storage_info.h"
#include "chrome/browser/storage_monitor/storage_monitor.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/test/test_utils.h"

#if defined(OS_WIN) || defined(OS_MACOSX)
#include "chrome/browser/media_galleries/fileapi/picasa_finder.h"
#include "chrome/common/media_galleries/picasa_test_util.h"
#include "chrome/common/media_galleries/picasa_types.h"
#include "chrome/common/media_galleries/pmp_test_util.h"
#endif

using extensions::PlatformAppBrowserTest;

namespace {

// Dummy device properties.
const char kDeviceId[] = "testDeviceId";
const char kDeviceName[] = "foobar";
#if defined(FILE_PATH_USES_DRIVE_LETTERS)
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("C:\\qux");
#else
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("/qux");
#endif

// This function is to ensure at least one (fake) media gallery exists for
// testing platforms with no default media galleries, such as CHROMEOS.
void MakeFakeMediaGalleryForTest(Profile* profile, const base::FilePath& path) {
  MediaGalleriesPreferences* preferences =
      g_browser_process->media_file_system_registry()->GetPreferences(profile);
  base::RunLoop runloop;
  preferences->EnsureInitialized(runloop.QuitClosure());
  runloop.Run();

  MediaGalleryPrefInfo gallery_info;
  ASSERT_FALSE(preferences->LookUpGalleryByPath(path, &gallery_info));
  preferences->AddGallery(gallery_info.device_id,
                          gallery_info.path,
                          false /* user_added */,
                          gallery_info.volume_label,
                          gallery_info.vendor_name,
                          gallery_info.model_name,
                          gallery_info.total_size_in_bytes,
                          gallery_info.last_attach_time);

  content::RunAllPendingInMessageLoop();
}

}  // namespace

class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest {
 protected:
  MediaGalleriesPlatformAppBrowserTest() : test_jpg_size_(0) {}
  virtual ~MediaGalleriesPlatformAppBrowserTest() {}

  virtual void SetUpOnMainThread() OVERRIDE {
    PlatformAppBrowserTest::SetUpOnMainThread();
    ensure_media_directories_exists_.reset(new EnsureMediaDirectoriesExists);
    PopulatePicturesDirectoryTestData();
  }

  virtual void TearDownOnMainThread() OVERRIDE {
    ensure_media_directories_exists_.reset();
    PlatformAppBrowserTest::TearDownOnMainThread();
  }

  bool RunMediaGalleriesTest(const std::string& extension_name) {
    base::ListValue empty_list_value;
    return RunMediaGalleriesTestWithArg(extension_name, empty_list_value);
  }

  bool RunMediaGalleriesTestWithArg(const std::string& extension_name,
                                    const base::ListValue& custom_arg_value) {
    // Copy the test data for this test into a temporary directory. Then add
    // a common_injected.js to the temporary copy and run it.
    const char kTestDir[] = "api_test/media_galleries/";
    base::FilePath from_dir =
        test_data_dir_.AppendASCII(kTestDir + extension_name);
    from_dir = from_dir.NormalizePathSeparators();

    base::ScopedTempDir temp_dir;
    if (!temp_dir.CreateUniqueTempDir())
      return false;

    if (!base::CopyDirectory(from_dir, temp_dir.path(), true))
      return false;

    base::FilePath common_js_path(
        GetCommonDataDir().AppendASCII("common_injected.js"));
    base::FilePath inject_js_path(
        temp_dir.path().AppendASCII(extension_name)
                       .AppendASCII("common_injected.js"));
    if (!base::CopyFile(common_js_path, inject_js_path))
      return false;

    const char* custom_arg = NULL;
    std::string json_string;
    if (!custom_arg_value.empty()) {
      base::JSONWriter::Write(&custom_arg_value, &json_string);
      custom_arg = json_string.c_str();
    }

    base::AutoReset<base::FilePath> reset(&test_data_dir_, temp_dir.path());
    return RunPlatformAppTestWithArg(extension_name, custom_arg);
  }

  void AttachFakeDevice() {
    device_id_ = StorageInfo::MakeDeviceId(
        StorageInfo::REMOVABLE_MASS_STORAGE_WITH_DCIM, kDeviceId);

    StorageMonitor::GetInstance()->receiver()->ProcessAttach(
        StorageInfo(device_id_, base::string16(), kDevicePath,
                    ASCIIToUTF16(kDeviceName), base::string16(),
                    base::string16(), 0));
    content::RunAllPendingInMessageLoop();
  }

  void DetachFakeDevice() {
    StorageMonitor::GetInstance()->receiver()->ProcessDetach(device_id_);
    content::RunAllPendingInMessageLoop();
  }

  void PopulatePicturesDirectoryTestData() {
    if (ensure_media_directories_exists_->num_galleries() == 0)
      return;

    base::FilePath test_data_path(GetCommonDataDir());
    base::FilePath write_path;
    ASSERT_TRUE(PathService::Get(chrome::DIR_USER_PICTURES, &write_path));

    // Valid file, should show up in JS as a FileEntry.
    ASSERT_TRUE(base::CopyFile(test_data_path.AppendASCII("test.jpg"),
                               write_path.AppendASCII("test.jpg")));

    // Invalid file, should not show up as a FileEntry in JS at all.
    ASSERT_TRUE(base::CopyFile(test_data_path.AppendASCII("test.txt"),
                               write_path.AppendASCII("test.txt")));

    int64 file_size;
    ASSERT_TRUE(file_util::GetFileSize(test_data_path.AppendASCII("test.jpg"),
                                       &file_size));
    test_jpg_size_ = base::checked_numeric_cast<int>(file_size);
  }

#if defined(OS_WIN) || defined(OS_MACOSX)
  void PopulatePicasaTestData(const base::FilePath& picasa_app_data_root) {
    base::FilePath picasa_database_path =
        picasa::MakePicasaDatabasePath(picasa_app_data_root);
    base::FilePath picasa_temp_dir_path =
        picasa_database_path.DirName().AppendASCII(picasa::kPicasaTempDirName);
    ASSERT_TRUE(file_util::CreateDirectory(picasa_database_path));
    ASSERT_TRUE(file_util::CreateDirectory(picasa_temp_dir_path));

    // Create fake folder directories.
    base::FilePath folders_root =
        ensure_media_directories_exists_->GetFakePicasaFoldersRootPath();
    base::FilePath fake_folder_1 = folders_root.AppendASCII("folder1");
    base::FilePath fake_folder_2 = folders_root.AppendASCII("folder2");
    ASSERT_TRUE(file_util::CreateDirectory(fake_folder_1));
    ASSERT_TRUE(file_util::CreateDirectory(fake_folder_2));

    // Write folder and album contents.
    picasa::WriteTestAlbumTable(
        picasa_database_path, fake_folder_1, fake_folder_2);
    picasa::WriteTestAlbumsImagesIndex(fake_folder_1, fake_folder_2);

    base::FilePath test_jpg_path = GetCommonDataDir().AppendASCII("test.jpg");
    ASSERT_TRUE(base::CopyFile(
        test_jpg_path, fake_folder_1.AppendASCII("InBoth.jpg")));
    ASSERT_TRUE(base::CopyFile(
        test_jpg_path, fake_folder_1.AppendASCII("InSecondAlbumOnly.jpg")));
    ASSERT_TRUE(base::CopyFile(
        test_jpg_path, fake_folder_2.AppendASCII("InFirstAlbumOnly.jpg")));
  }
#endif

  base::FilePath GetCommonDataDir() const {
    return test_data_dir_.AppendASCII("api_test")
                         .AppendASCII("media_galleries")
                         .AppendASCII("common");
  }

  int num_galleries() const {
    return ensure_media_directories_exists_->num_galleries();
  }

  int test_jpg_size() const { return test_jpg_size_; }

  EnsureMediaDirectoriesExists* ensure_media_directories_exists() const {
    return ensure_media_directories_exists_.get();
  }

 private:
  std::string device_id_;
  int test_jpg_size_;
  scoped_ptr<EnsureMediaDirectoriesExists> ensure_media_directories_exists_;
};

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MediaGalleriesNoAccess) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  MakeFakeMediaGalleryForTest(browser()->profile(), temp_dir.path());

  base::ListValue custom_args;
  custom_args.AppendInteger(num_galleries() + 1);

  ASSERT_TRUE(RunMediaGalleriesTestWithArg("no_access", custom_args))
      << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, NoGalleriesRead) {
  ASSERT_TRUE(RunMediaGalleriesTest("no_galleries")) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       NoGalleriesCopyTo) {
  ASSERT_TRUE(RunMediaGalleriesTest("no_galleries_copy_to")) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MediaGalleriesRead) {
  base::ListValue custom_args;
  custom_args.AppendInteger(num_galleries());
  custom_args.AppendInteger(test_jpg_size());

  ASSERT_TRUE(RunMediaGalleriesTestWithArg("read_access", custom_args))
      << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MediaGalleriesCopyTo) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  MakeFakeMediaGalleryForTest(browser()->profile(), temp_dir.path());
  ASSERT_TRUE(RunMediaGalleriesTest("copy_to_access")) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MediaGalleriesAccessAttached) {
  AttachFakeDevice();

  base::ListValue custom_args;
  custom_args.AppendInteger(num_galleries() + 1);
  custom_args.AppendString(kDeviceName);

  ASSERT_TRUE(RunMediaGalleriesTestWithArg("access_attached", custom_args))
      << message_;

  DetachFakeDevice();
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       GetFilesystemMetadata) {
  ASSERT_TRUE(RunMediaGalleriesTest("metadata")) << message_;
}

#if defined(OS_WIN)|| defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       PicasaDefaultLocation) {
#if defined(OS_WIN)
  PopulatePicasaTestData(
      ensure_media_directories_exists()->GetFakeLocalAppDataPath());
#elif defined(OS_MACOSX)
  PopulatePicasaTestData(
      ensure_media_directories_exists()->GetFakeAppDataPath());
#endif
  ASSERT_TRUE(RunMediaGalleriesTest("picasa")) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       PicasaCustomLocation) {
  base::ScopedTempDir custom_picasa_app_data_root;
  ASSERT_TRUE(custom_picasa_app_data_root.CreateUniqueTempDir());
  ensure_media_directories_exists()->SetCustomPicasaAppDataPath(
      custom_picasa_app_data_root.path());
  PopulatePicasaTestData(custom_picasa_app_data_root.path());
  ASSERT_TRUE(RunMediaGalleriesTest("picasa")) << message_;
}
#endif  // defined(OS_WIN) || defined(OS_MACOSX)
<commit_msg>Disable MediaGalleriesPlatformAppBrowserTest.MediaGalleriesCopyTo for being flaky.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/auto_reset.h"
#include "base/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_writer.h"
#include "base/path_service.h"
#include "base/safe_numerics.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/apps/app_browsertest_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/media_galleries/media_file_system_registry.h"
#include "chrome/browser/media_galleries/media_galleries_preferences.h"
#include "chrome/browser/media_galleries/media_galleries_test_util.h"
#include "chrome/browser/storage_monitor/storage_info.h"
#include "chrome/browser/storage_monitor/storage_monitor.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/test/test_utils.h"

#if defined(OS_WIN) || defined(OS_MACOSX)
#include "chrome/browser/media_galleries/fileapi/picasa_finder.h"
#include "chrome/common/media_galleries/picasa_test_util.h"
#include "chrome/common/media_galleries/picasa_types.h"
#include "chrome/common/media_galleries/pmp_test_util.h"
#endif

using extensions::PlatformAppBrowserTest;

namespace {

// Dummy device properties.
const char kDeviceId[] = "testDeviceId";
const char kDeviceName[] = "foobar";
#if defined(FILE_PATH_USES_DRIVE_LETTERS)
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("C:\\qux");
#else
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("/qux");
#endif

// This function is to ensure at least one (fake) media gallery exists for
// testing platforms with no default media galleries, such as CHROMEOS.
void MakeFakeMediaGalleryForTest(Profile* profile, const base::FilePath& path) {
  MediaGalleriesPreferences* preferences =
      g_browser_process->media_file_system_registry()->GetPreferences(profile);
  base::RunLoop runloop;
  preferences->EnsureInitialized(runloop.QuitClosure());
  runloop.Run();

  MediaGalleryPrefInfo gallery_info;
  ASSERT_FALSE(preferences->LookUpGalleryByPath(path, &gallery_info));
  preferences->AddGallery(gallery_info.device_id,
                          gallery_info.path,
                          false /* user_added */,
                          gallery_info.volume_label,
                          gallery_info.vendor_name,
                          gallery_info.model_name,
                          gallery_info.total_size_in_bytes,
                          gallery_info.last_attach_time);

  content::RunAllPendingInMessageLoop();
}

}  // namespace

class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest {
 protected:
  MediaGalleriesPlatformAppBrowserTest() : test_jpg_size_(0) {}
  virtual ~MediaGalleriesPlatformAppBrowserTest() {}

  virtual void SetUpOnMainThread() OVERRIDE {
    PlatformAppBrowserTest::SetUpOnMainThread();
    ensure_media_directories_exists_.reset(new EnsureMediaDirectoriesExists);
    PopulatePicturesDirectoryTestData();
  }

  virtual void TearDownOnMainThread() OVERRIDE {
    ensure_media_directories_exists_.reset();
    PlatformAppBrowserTest::TearDownOnMainThread();
  }

  bool RunMediaGalleriesTest(const std::string& extension_name) {
    base::ListValue empty_list_value;
    return RunMediaGalleriesTestWithArg(extension_name, empty_list_value);
  }

  bool RunMediaGalleriesTestWithArg(const std::string& extension_name,
                                    const base::ListValue& custom_arg_value) {
    // Copy the test data for this test into a temporary directory. Then add
    // a common_injected.js to the temporary copy and run it.
    const char kTestDir[] = "api_test/media_galleries/";
    base::FilePath from_dir =
        test_data_dir_.AppendASCII(kTestDir + extension_name);
    from_dir = from_dir.NormalizePathSeparators();

    base::ScopedTempDir temp_dir;
    if (!temp_dir.CreateUniqueTempDir())
      return false;

    if (!base::CopyDirectory(from_dir, temp_dir.path(), true))
      return false;

    base::FilePath common_js_path(
        GetCommonDataDir().AppendASCII("common_injected.js"));
    base::FilePath inject_js_path(
        temp_dir.path().AppendASCII(extension_name)
                       .AppendASCII("common_injected.js"));
    if (!base::CopyFile(common_js_path, inject_js_path))
      return false;

    const char* custom_arg = NULL;
    std::string json_string;
    if (!custom_arg_value.empty()) {
      base::JSONWriter::Write(&custom_arg_value, &json_string);
      custom_arg = json_string.c_str();
    }

    base::AutoReset<base::FilePath> reset(&test_data_dir_, temp_dir.path());
    return RunPlatformAppTestWithArg(extension_name, custom_arg);
  }

  void AttachFakeDevice() {
    device_id_ = StorageInfo::MakeDeviceId(
        StorageInfo::REMOVABLE_MASS_STORAGE_WITH_DCIM, kDeviceId);

    StorageMonitor::GetInstance()->receiver()->ProcessAttach(
        StorageInfo(device_id_, base::string16(), kDevicePath,
                    ASCIIToUTF16(kDeviceName), base::string16(),
                    base::string16(), 0));
    content::RunAllPendingInMessageLoop();
  }

  void DetachFakeDevice() {
    StorageMonitor::GetInstance()->receiver()->ProcessDetach(device_id_);
    content::RunAllPendingInMessageLoop();
  }

  void PopulatePicturesDirectoryTestData() {
    if (ensure_media_directories_exists_->num_galleries() == 0)
      return;

    base::FilePath test_data_path(GetCommonDataDir());
    base::FilePath write_path;
    ASSERT_TRUE(PathService::Get(chrome::DIR_USER_PICTURES, &write_path));

    // Valid file, should show up in JS as a FileEntry.
    ASSERT_TRUE(base::CopyFile(test_data_path.AppendASCII("test.jpg"),
                               write_path.AppendASCII("test.jpg")));

    // Invalid file, should not show up as a FileEntry in JS at all.
    ASSERT_TRUE(base::CopyFile(test_data_path.AppendASCII("test.txt"),
                               write_path.AppendASCII("test.txt")));

    int64 file_size;
    ASSERT_TRUE(file_util::GetFileSize(test_data_path.AppendASCII("test.jpg"),
                                       &file_size));
    test_jpg_size_ = base::checked_numeric_cast<int>(file_size);
  }

#if defined(OS_WIN) || defined(OS_MACOSX)
  void PopulatePicasaTestData(const base::FilePath& picasa_app_data_root) {
    base::FilePath picasa_database_path =
        picasa::MakePicasaDatabasePath(picasa_app_data_root);
    base::FilePath picasa_temp_dir_path =
        picasa_database_path.DirName().AppendASCII(picasa::kPicasaTempDirName);
    ASSERT_TRUE(file_util::CreateDirectory(picasa_database_path));
    ASSERT_TRUE(file_util::CreateDirectory(picasa_temp_dir_path));

    // Create fake folder directories.
    base::FilePath folders_root =
        ensure_media_directories_exists_->GetFakePicasaFoldersRootPath();
    base::FilePath fake_folder_1 = folders_root.AppendASCII("folder1");
    base::FilePath fake_folder_2 = folders_root.AppendASCII("folder2");
    ASSERT_TRUE(file_util::CreateDirectory(fake_folder_1));
    ASSERT_TRUE(file_util::CreateDirectory(fake_folder_2));

    // Write folder and album contents.
    picasa::WriteTestAlbumTable(
        picasa_database_path, fake_folder_1, fake_folder_2);
    picasa::WriteTestAlbumsImagesIndex(fake_folder_1, fake_folder_2);

    base::FilePath test_jpg_path = GetCommonDataDir().AppendASCII("test.jpg");
    ASSERT_TRUE(base::CopyFile(
        test_jpg_path, fake_folder_1.AppendASCII("InBoth.jpg")));
    ASSERT_TRUE(base::CopyFile(
        test_jpg_path, fake_folder_1.AppendASCII("InSecondAlbumOnly.jpg")));
    ASSERT_TRUE(base::CopyFile(
        test_jpg_path, fake_folder_2.AppendASCII("InFirstAlbumOnly.jpg")));
  }
#endif

  base::FilePath GetCommonDataDir() const {
    return test_data_dir_.AppendASCII("api_test")
                         .AppendASCII("media_galleries")
                         .AppendASCII("common");
  }

  int num_galleries() const {
    return ensure_media_directories_exists_->num_galleries();
  }

  int test_jpg_size() const { return test_jpg_size_; }

  EnsureMediaDirectoriesExists* ensure_media_directories_exists() const {
    return ensure_media_directories_exists_.get();
  }

 private:
  std::string device_id_;
  int test_jpg_size_;
  scoped_ptr<EnsureMediaDirectoriesExists> ensure_media_directories_exists_;
};

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MediaGalleriesNoAccess) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  MakeFakeMediaGalleryForTest(browser()->profile(), temp_dir.path());

  base::ListValue custom_args;
  custom_args.AppendInteger(num_galleries() + 1);

  ASSERT_TRUE(RunMediaGalleriesTestWithArg("no_access", custom_args))
      << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, NoGalleriesRead) {
  ASSERT_TRUE(RunMediaGalleriesTest("no_galleries")) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       NoGalleriesCopyTo) {
  ASSERT_TRUE(RunMediaGalleriesTest("no_galleries_copy_to")) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MediaGalleriesRead) {
  base::ListValue custom_args;
  custom_args.AppendInteger(num_galleries());
  custom_args.AppendInteger(test_jpg_size());

  ASSERT_TRUE(RunMediaGalleriesTestWithArg("read_access", custom_args))
      << message_;
}

// Flaky: crbug.com/314576
#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       DISABLED_MediaGalleriesCopyTo) {
#else
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MediaGalleriesCopyTo) {
#endif
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  MakeFakeMediaGalleryForTest(browser()->profile(), temp_dir.path());
  ASSERT_TRUE(RunMediaGalleriesTest("copy_to_access")) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MediaGalleriesAccessAttached) {
  AttachFakeDevice();

  base::ListValue custom_args;
  custom_args.AppendInteger(num_galleries() + 1);
  custom_args.AppendString(kDeviceName);

  ASSERT_TRUE(RunMediaGalleriesTestWithArg("access_attached", custom_args))
      << message_;

  DetachFakeDevice();
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       GetFilesystemMetadata) {
  ASSERT_TRUE(RunMediaGalleriesTest("metadata")) << message_;
}

#if defined(OS_WIN)|| defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       PicasaDefaultLocation) {
#if defined(OS_WIN)
  PopulatePicasaTestData(
      ensure_media_directories_exists()->GetFakeLocalAppDataPath());
#elif defined(OS_MACOSX)
  PopulatePicasaTestData(
      ensure_media_directories_exists()->GetFakeAppDataPath());
#endif
  ASSERT_TRUE(RunMediaGalleriesTest("picasa")) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       PicasaCustomLocation) {
  base::ScopedTempDir custom_picasa_app_data_root;
  ASSERT_TRUE(custom_picasa_app_data_root.CreateUniqueTempDir());
  ensure_media_directories_exists()->SetCustomPicasaAppDataPath(
      custom_picasa_app_data_root.path());
  PopulatePicasaTestData(custom_picasa_app_data_root.path());
  ASSERT_TRUE(RunMediaGalleriesTest("picasa")) << message_;
}
#endif  // defined(OS_WIN) || defined(OS_MACOSX)
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------//
//                 █      █                                                   //
//                 ████████                                                   //
//               ██        ██                                                 //
//              ███  █  █  ███    CCBNode_Loader_PropertySetters.cpp          //
//              █ █        █ █    MonsterFramework                            //
//               ████████████                                                 //
//             █              █   Copyright (c) 2015 AmazingCow               //
//            █     █    █     █  www.AmazingCow.com                          //
//            █     █    █     █                                              //
//             █              █   N2OMatt - n2omatt@amazingcow.com            //
//               ████████████     www.amazingcow.com/n2omatt                  //
//                                                                            //
//                                                                            //
//                  This software is licensed as BSD-3                        //
//                 CHECK THE COPYING FILE TO MORE DETAILS                     //
//                                                                            //
//    Permission is granted to anyone to use this software for any purpose,   //
//   including commercial applications, and to alter it and redistribute it   //
//               freely, subject to the following restrictions:               //
//                                                                            //
//     0. You **CANNOT** change the type of the license.                      //
//     1. The origin of this software must not be misrepresented;             //
//        you must not claim that you wrote the original software.            //
//     2. If you use this software in a product, an acknowledgment in the     //
//        product IS HIGHLY APPRECIATED, both in source and binary forms.     //
//        (See opensource.AmazingCow.com/acknowledgment.html for details).    //
//        If you will not acknowledge, just send us a email. We'll be         //
//        *VERY* happy to see our work being used by other people. :)         //
//        The email is: acknowledgmentopensource@AmazingCow.com               //
//     3. Altered source versions must be plainly marked as such,             //
//        and must notbe misrepresented as being the original software.       //
//     4. This notice may not be removed or altered from any source           //
//        distribution.                                                       //
//     5. Most important, you must have fun. ;)                               //
//                                                                            //
//      Visit opensource.amazingcow.com for more open-source projects.        //
//                                                                            //
//                                  Enjoy :)                                  //
//----------------------------------------------------------------------------//

#include "CCBNodeLoader_PropertySetters.h"
#include "CCBNodeLoader_Decoders.h"

#include <typeinfo>

USING_NS_STD_CC_CD_MF

// Anchor Point //
void mf::_set_anchorPoint(cc::Node *obj, const cc::Value &value)
{
    obj->setAnchorPoint(_decodeAsPoint(value));
}
void mf::_set_ignoreAnchorPointForPosition(cc::Node *obj, const cc::Value &value)
{
    obj->ignoreAnchorPointForPosition(_decodeAsCheck(value));
}

// Transforms //
void mf::_set_position(cc::Node *obj, const cc::Value &value)
{
    obj->setPosition(_decodeAsPosition(value, obj->getParent()));
}
void mf::_set_scale(cc::Node *obj, const cc::Value &value)
{
    //EMSG: We're decided treat scale as a stand alone
    //property. So it's not depends of anything else.
    auto point = _decodeAsPoint(value);
    obj->setScale(point.x, point.y);
}
void mf::_set_rotation(cc::Node *obj, const cc::Value &value)
{
    obj->setRotation(_decodeAsDegrees(value));
}

// ???
void mf::_set_isEnabled(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::MenuItem *>(obj)->setEnabled(_decodeAsCheck(value));
}
void mf::_set_contentSize(cc::Node *obj, const cc::Value &value)
{
    obj->setContentSize(_decodeAsSize(value));
}

// Color / Opacity //
void mf::_set_color(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::LayerColor *>(obj)->setColor(_decodeAsColor3(value));
}
void mf::_set_opacity(cc::Node *obj, const cc::Value &value)
{
    obj->setOpacity(_decodeAsByte(value));
}

// Input //
void mf::_set_isTouchEnabled(cc::Node *obj, const cc::Value &value)
{
    //COWTODO:: Ignoring by now, but must check what this method will do.
}
void mf::_set_isAccelerometerEnabled(cc::Node *obj, const cc::Value &value)
{
    //COWTODO:: Ignoring by now, but must check what this method will do.
}

// Frame //
void mf::_set_displayFrame(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::Sprite *>(obj)->setSpriteFrame(_decodeAsSpriteFrame(value));
}

// Button //
void mf::_set_normalSpriteFrame(cc::Node *obj, const cc::Value &value)
{
    //COWTODO: Refactor and comment.
    if(typeid(*obj) == typeid(cc::MenuItemToggle))
    {
        auto toggle = static_cast<cc::MenuItemToggle *>(obj);

        cc::Sprite *sprite1 = cc::Sprite::create();
        cc::Sprite *sprite2 = cc::Sprite::create();

        mf::_set_displayFrame(sprite1,  value);
        mf::_set_displayFrame(sprite2, value);

        auto menuItem = cc::MenuItemSprite::create(sprite1, sprite2);
        toggle->addSubItem(menuItem);
        toggle->setSelectedIndex(0);
    }
    else
    {
        cc::Sprite *sprite = cc::Sprite::create();
        mf::_set_displayFrame(sprite, value);

        static_cast<cc::MenuItemSprite *>(obj)->setNormalImage(sprite);
    }
}
void mf::_set_selectedSpriteFrame(cc::Node *obj, const cc::Value &value)
{
    //COWTODO: Refactor and comment.
    if(typeid(*obj) == typeid(cc::MenuItemToggle))
    {
        auto toggle = static_cast<cc::MenuItemToggle *>(obj);

        cc::Sprite *sprite1 = cc::Sprite::create();
        cc::Sprite *sprite2 = cc::Sprite::create();

        mf::_set_displayFrame(sprite1,  value);
        mf::_set_displayFrame(sprite2, value);

        auto menuItem = cc::MenuItemSprite::create(sprite1, sprite2);

        toggle->addSubItem(menuItem);
    }
    else
    {
        cc::Sprite *sprite = cc::Sprite::create();
        mf::_set_displayFrame(sprite, value);

        static_cast<cc::MenuItemSprite *>(obj)->setSelectedImage(sprite);
    }
}
void mf::_set_disabledSpriteFrame(cc::Node *obj, const cc::Value &value)
{
    //Implement MFToggle support.

    //There's no information to set the sprite, this is due
    //the CocosBuild set the disabledSpriteFrame in plist even
    //if the user doesn't set any of them...
    if(_decodeAsSpriteFrame(value) == "")
        return;

    cc::Sprite *sprite = cc::Sprite::create();
    mf::_set_displayFrame(sprite, value);

    static_cast<cc::MenuItemSprite *>(obj)->setDisabledImage(sprite);
}
void mf::_set_block(cc::Node *obj, const cc::Value &value,
                    ILoadResolver *pResolver)
{
    pResolver->resolveMenuSelector(_decodeAsBlock(value),
                                   static_cast<cc::MenuItem *>(obj));
}

// Font //
void mf::_set_fontName(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::Label *>(obj)->setSystemFontName(value.asString());
}
void mf::_set_fontSize(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::Label *>(obj)->setSystemFontSize(_decodeAsFontScale(value));
}
void mf::_set_string(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::Label *>(obj)->setString(_decodeAsString(value));
}
<commit_msg>Add some COWTODOs.<commit_after>//----------------------------------------------------------------------------//
//                 █      █                                                   //
//                 ████████                                                   //
//               ██        ██                                                 //
//              ███  █  █  ███    CCBNode_Loader_PropertySetters.cpp          //
//              █ █        █ █    MonsterFramework                            //
//               ████████████                                                 //
//             █              █   Copyright (c) 2015 AmazingCow               //
//            █     █    █     █  www.AmazingCow.com                          //
//            █     █    █     █                                              //
//             █              █   N2OMatt - n2omatt@amazingcow.com            //
//               ████████████     www.amazingcow.com/n2omatt                  //
//                                                                            //
//                                                                            //
//                  This software is licensed as BSD-3                        //
//                 CHECK THE COPYING FILE TO MORE DETAILS                     //
//                                                                            //
//    Permission is granted to anyone to use this software for any purpose,   //
//   including commercial applications, and to alter it and redistribute it   //
//               freely, subject to the following restrictions:               //
//                                                                            //
//     0. You **CANNOT** change the type of the license.                      //
//     1. The origin of this software must not be misrepresented;             //
//        you must not claim that you wrote the original software.            //
//     2. If you use this software in a product, an acknowledgment in the     //
//        product IS HIGHLY APPRECIATED, both in source and binary forms.     //
//        (See opensource.AmazingCow.com/acknowledgment.html for details).    //
//        If you will not acknowledge, just send us a email. We'll be         //
//        *VERY* happy to see our work being used by other people. :)         //
//        The email is: acknowledgmentopensource@AmazingCow.com               //
//     3. Altered source versions must be plainly marked as such,             //
//        and must notbe misrepresented as being the original software.       //
//     4. This notice may not be removed or altered from any source           //
//        distribution.                                                       //
//     5. Most important, you must have fun. ;)                               //
//                                                                            //
//      Visit opensource.amazingcow.com for more open-source projects.        //
//                                                                            //
//                                  Enjoy :)                                  //
//----------------------------------------------------------------------------//

#include "CCBNodeLoader_PropertySetters.h"
#include "CCBNodeLoader_Decoders.h"

#include <typeinfo>

USING_NS_STD_CC_CD_MF

// Anchor Point //
void mf::_set_anchorPoint(cc::Node *obj, const cc::Value &value)
{
    obj->setAnchorPoint(_decodeAsPoint(value));
}
void mf::_set_ignoreAnchorPointForPosition(cc::Node *obj, const cc::Value &value)
{
    obj->ignoreAnchorPointForPosition(_decodeAsCheck(value));
}

// Transforms //
void mf::_set_position(cc::Node *obj, const cc::Value &value)
{
    obj->setPosition(_decodeAsPosition(value, obj->getParent()));
}
void mf::_set_scale(cc::Node *obj, const cc::Value &value)
{
    //EMSG: We're decided treat scale as a stand alone
    //property. So it's not depends of anything else.
    auto point = _decodeAsPoint(value);
    obj->setScale(point.x, point.y);
}
void mf::_set_rotation(cc::Node *obj, const cc::Value &value)
{
    obj->setRotation(_decodeAsDegrees(value));
}

// ???
void mf::_set_isEnabled(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::MenuItem *>(obj)->setEnabled(_decodeAsCheck(value));
}
void mf::_set_contentSize(cc::Node *obj, const cc::Value &value)
{
    obj->setContentSize(_decodeAsSize(value));
}

// Color / Opacity //
void mf::_set_color(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::LayerColor *>(obj)->setColor(_decodeAsColor3(value));
}
void mf::_set_opacity(cc::Node *obj, const cc::Value &value)
{
    obj->setOpacity(_decodeAsByte(value));
}

// Input //
void mf::_set_isTouchEnabled(cc::Node *obj, const cc::Value &value)
{
    //COWTODO:: Ignoring by now, but must check what this method will do.
}
void mf::_set_isAccelerometerEnabled(cc::Node *obj, const cc::Value &value)
{
    //COWTODO:: Ignoring by now, but must check what this method will do.
}

// Frame //
void mf::_set_displayFrame(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::Sprite *>(obj)->setSpriteFrame(_decodeAsSpriteFrame(value));
}

// Button //
void mf::_set_normalSpriteFrame(cc::Node *obj, const cc::Value &value)
{
    //COWTODO: Refactor and comment.
    if(typeid(*obj) == typeid(cc::MenuItemToggle))
    {
        auto toggle = static_cast<cc::MenuItemToggle *>(obj);

        cc::Sprite *sprite1 = cc::Sprite::create();
        cc::Sprite *sprite2 = cc::Sprite::create();

        mf::_set_displayFrame(sprite1,  value);
        mf::_set_displayFrame(sprite2, value);

        auto menuItem = cc::MenuItemSprite::create(sprite1, sprite2);
        toggle->addSubItem(menuItem);
        toggle->setSelectedIndex(0);
    }
    else
    {
        cc::Sprite *sprite = cc::Sprite::create();
        mf::_set_displayFrame(sprite, value);

        static_cast<cc::MenuItemSprite *>(obj)->setNormalImage(sprite);
    }
}
void mf::_set_selectedSpriteFrame(cc::Node *obj, const cc::Value &value)
{
    //COWTODO: Refactor and comment.
    if(typeid(*obj) == typeid(cc::MenuItemToggle))
    {
        auto toggle = static_cast<cc::MenuItemToggle *>(obj);

        cc::Sprite *sprite1 = cc::Sprite::create();
        cc::Sprite *sprite2 = cc::Sprite::create();

        mf::_set_displayFrame(sprite1,  value);
        mf::_set_displayFrame(sprite2, value);

        auto menuItem = cc::MenuItemSprite::create(sprite1, sprite2);

        toggle->addSubItem(menuItem);
    }
    else
    {
        cc::Sprite *sprite = cc::Sprite::create();
        mf::_set_displayFrame(sprite, value);

        static_cast<cc::MenuItemSprite *>(obj)->setSelectedImage(sprite);
    }
}
void mf::_set_disabledSpriteFrame(cc::Node *obj, const cc::Value &value)
{
    //COWTODO: Implement MFToggle support.

    //There's no information to set the sprite, this is due
    //the CocosBuild set the disabledSpriteFrame in plist even
    //if the user doesn't set any of them...
    if(_decodeAsSpriteFrame(value) == "")
        return;

    cc::Sprite *sprite = cc::Sprite::create();
    mf::_set_displayFrame(sprite, value);

    static_cast<cc::MenuItemSprite *>(obj)->setDisabledImage(sprite);
}
void mf::_set_block(cc::Node *obj, const cc::Value &value,
                    ILoadResolver *pResolver)
{
    pResolver->resolveMenuSelector(_decodeAsBlock(value),
                                   static_cast<cc::MenuItem *>(obj));
}

// Font //
void mf::_set_fontName(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::Label *>(obj)->setSystemFontName(value.asString());
}
void mf::_set_fontSize(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::Label *>(obj)->setSystemFontSize(_decodeAsFontScale(value));
}
void mf::_set_string(cc::Node *obj, const cc::Value &value)
{
    static_cast<cc::Label *>(obj)->setString(_decodeAsString(value));
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2009, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include "boost/python.hpp"

#include "IECore/Renderer.h"
#include "IECore/CompoundObject.h"
#include "IECore/CompoundParameter.h"
#include "IECore/MessageHandler.h"
#include "IECore/ParameterisedProcedural.h"
#include "IECore/bindings/ParameterisedProceduralBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/Wrapper.h"

using namespace boost::python;

namespace IECore
{

class ParameterisedProceduralWrap : public ParameterisedProcedural, public Wrapper<ParameterisedProcedural>
{

	public :

		ParameterisedProceduralWrap( PyObject *self )
			: Wrapper<ParameterisedProcedural>( self, this )
		{
		}

		virtual void doRenderState( RendererPtr renderer, ConstCompoundObjectPtr args ) const
		{
			try
			{
				override o = this->get_override( "doRenderState" );
				if( o )
				{
					o( renderer, boost::const_pointer_cast<CompoundObject>( args ) );
				}
				else
				{
					ParameterisedProcedural::doRenderState( renderer, args );
				}
			}
			catch( error_already_set )
			{
				PyErr_Print();
			}
			catch( const std::exception &e )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", e.what() );
			}
			catch( ... )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", "Caught unknown exception" );
			}

		}

		virtual Imath::Box3f doBound( ConstCompoundObjectPtr args ) const
		{
			try
			{
				override o = this->get_override( "doBound" );
				if( o )
				{
					return o( boost::const_pointer_cast<CompoundObject>( args ) );
				}
				else
				{
					msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "doBound() python method not defined" );
				}
			}
			catch( error_already_set )
			{
				PyErr_Print();
			}
			catch( const std::exception &e )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doBound", e.what() );
			}
			catch( ... )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "Caught unknown exception" );
			}
			return Imath::Box3f(); // empty
		}

		virtual void doRender( RendererPtr r, ConstCompoundObjectPtr args ) const
		{
			// ideally we might not do any exception handling here, and always leave it to the host.
			// but in our case the host is mainly 3delight and that does no exception handling at all.
			try
			{
				override o = this->get_override( "doRender" );
				if( o )
				{
					o( r, boost::const_pointer_cast<CompoundObject>( args ) );
				}
				else
				{
					msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "doRender() python method not defined" );
				}
			}
			catch( error_already_set )
			{
				PyErr_Print();
			}
			catch( const std::exception &e )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doRender", e.what() );
			}
			catch( ... )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "Caught unknown exception" );
			}
		}

};

IE_CORE_DECLAREPTR( ParameterisedProceduralWrap );

static ParameterPtr parameterisedProceduralGetItem( ParameterisedProcedural &o, const std::string &n )
{
	ParameterPtr p = o.parameters()->parameter<Parameter>( n );
	if( !p )
	{
		throw Exception( std::string("Parameter ") + n + " doesn't exist" );
	}
	return p;
}

void bindParameterisedProcedural()
{

	RunTimeTypedClass<ParameterisedProcedural, ParameterisedProceduralWrapPtr>()
		.def( init<>() )
		.def( "parameters", (CompoundParameterPtr (ParameterisedProcedural::*)())&ParameterisedProcedural::parameters )
		.def( "render", (void (ParameterisedProcedural::*)( RendererPtr ) const )&ParameterisedProcedural::render )
		.def( "render", (void (ParameterisedProcedural::*)( RendererPtr, bool, bool, bool, bool ) const )&ParameterisedProcedural::render, ( arg( "renderer" ), arg( "inAttributeBlock" ) = true, arg( "withState" ) = true, arg( "withGeometry" ) = true, arg( "immediateGeometry" ) = false ) )
		.def( "__getitem__", &parameterisedProceduralGetItem )
	;

}

} // namespace IECore
<commit_msg>Fixed failing test<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2009, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include "boost/python.hpp"

#include "IECore/Renderer.h"
#include "IECore/CompoundObject.h"
#include "IECore/CompoundParameter.h"
#include "IECore/MessageHandler.h"
#include "IECore/ParameterisedProcedural.h"
#include "IECore/bindings/ParameterisedProceduralBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/Wrapper.h"

using namespace boost::python;

namespace IECore
{

class ParameterisedProceduralWrap : public ParameterisedProcedural, public Wrapper<ParameterisedProcedural>
{

	public :

		ParameterisedProceduralWrap( PyObject *self )
			: Wrapper<ParameterisedProcedural>( self, this )
		{
		}

		virtual void doRenderState( RendererPtr renderer, ConstCompoundObjectPtr args ) const
		{
			try
			{
				override o = this->get_override( "doRenderState" );
				if( o )
				{
					o( renderer, boost::const_pointer_cast<CompoundObject>( args ) );
				}
				else
				{
					ParameterisedProcedural::doRenderState( renderer, args );
				}
			}
			catch( error_already_set )
			{
				PyErr_Print();
			}
			catch( const std::exception &e )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", e.what() );
			}
			catch( ... )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doRenderState", "Caught unknown exception" );
			}

		}

		virtual Imath::Box3f doBound( ConstCompoundObjectPtr args ) const
		{
			try
			{
				override o = this->get_override( "doBound" );
				if( o )
				{
					return o( boost::const_pointer_cast<CompoundObject>( args ) );
				}
				else
				{
					msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "doBound() python method not defined" );
				}
			}
			catch( error_already_set )
			{
				PyErr_Print();
			}
			catch( const std::exception &e )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doBound", e.what() );
			}
			catch( ... )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doBound", "Caught unknown exception" );
			}
			return Imath::Box3f(); // empty
		}

		virtual void doRender( RendererPtr r, ConstCompoundObjectPtr args ) const
		{
			// ideally we might not do any exception handling here, and always leave it to the host.
			// but in our case the host is mainly 3delight and that does no exception handling at all.
			try
			{
				override o = this->get_override( "doRender" );
				if( o )
				{
					o( r, boost::const_pointer_cast<CompoundObject>( args ) );
				}
				else
				{
					msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "doRender() python method not defined" );
				}
			}
			catch( error_already_set )
			{
				PyErr_Print();
			}
			catch( const std::exception &e )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doRender", e.what() );
			}
			catch( ... )
			{
				msg( Msg::Error, "ParameterisedProceduralWrap::doRender", "Caught unknown exception" );
			}
		}

		IE_COREPYTHON_RUNTIMETYPEDWRAPPERFNS( ParameterisedProcedural );

};

IE_CORE_DECLAREPTR( ParameterisedProceduralWrap );

static ParameterPtr parameterisedProceduralGetItem( ParameterisedProcedural &o, const std::string &n )
{
	ParameterPtr p = o.parameters()->parameter<Parameter>( n );
	if( !p )
	{
		throw Exception( std::string("Parameter ") + n + " doesn't exist" );
	}
	return p;
}

void bindParameterisedProcedural()
{

	RunTimeTypedClass<ParameterisedProcedural, ParameterisedProceduralWrapPtr>()
		.def( init<>() )
		.def( "parameters", (CompoundParameterPtr (ParameterisedProcedural::*)())&ParameterisedProcedural::parameters )
		.def( "render", (void (ParameterisedProcedural::*)( RendererPtr ) const )&ParameterisedProcedural::render )
		.def( "render", (void (ParameterisedProcedural::*)( RendererPtr, bool, bool, bool, bool ) const )&ParameterisedProcedural::render, ( arg( "renderer" ), arg( "inAttributeBlock" ) = true, arg( "withState" ) = true, arg( "withGeometry" ) = true, arg( "immediateGeometry" ) = false ) )
		.def( "__getitem__", &parameterisedProceduralGetItem )
	;

}

} // namespace IECore
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "../huffman/huffman_tree.hpp"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace unit_test_for_huffman
{
	using FrequencyMap = cpr::huffman::FrequencyMap < unsigned char, unsigned long > ;
	using HuffmanTree = cpr::huffman::HuffmanTree < unsigned char, unsigned long > ;
	TEST_CLASS(unit_test_for_huffman_tree)
	{
	public:

		TEST_METHOD(ctor)
		{
			std::vector<unsigned char> test_case{ 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c' };
			FrequencyMap fmap(test_case);
			HuffmanTree htree{ fmap };
		}

	};
}<commit_msg>tested ctor for huffman_tree, but more test cases needed.<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "../huffman/huffman_tree.hpp"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace unit_test_for_huffman
{
	using FrequencyMap = cpr::huffman::FrequencyMap < unsigned char, unsigned long > ;
	using HuffmanTree = cpr::huffman::HuffmanTree < unsigned char, unsigned long > ;
	TEST_CLASS(unit_test_for_huffman_tree)
	{
	public:

		TEST_METHOD(ctor)
		{
			//case 1 made up on my own
			std::vector<unsigned char> test_case{ 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c' };
			FrequencyMap fmap(test_case);
			HuffmanTree htree{ fmap };
			Assert::IsNotNull(htree.root().get());

			//case 2 based on 16.3 clrs
			auto empty_case = std::vector<unsigned char>();
			FrequencyMap fmap_from_clrs(empty_case);
			fmap_from_clrs['a'] = 45;
			fmap_from_clrs['b'] = 13;
			fmap_from_clrs['c'] = 12;
			fmap_from_clrs['d'] = 16;
			fmap_from_clrs['e'] = 9;
			fmap_from_clrs['f'] = 5;
			HuffmanTree htree_from_clrs{ fmap_from_clrs };

			Assert::AreEqual(100ul, htree_from_clrs.root()->freq_);
			Assert::AreEqual((unsigned char)0, htree_from_clrs.root()->character_);
			Assert::AreEqual((unsigned char)'a', htree_from_clrs.root()->left_->character_);

			// more test needed , but for now clrs is unavailable
		}
	};
}<|endoftext|>


<commit_before><commit_msg>Transform: Remove unused std header.<commit_after><|endoftext|>