<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013-2015, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Devices/DeviceFilters/RecordPose.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Math/RigidTransform.h"

using SurgSim::DataStructures::DataGroup;
using SurgSim::Math::RigidTransform3d;

namespace SurgSim
{
namespace Devices
{

SURGSIM_REGISTER(SurgSim::Input::DeviceInterface, SurgSim::Devices::RecordPose, RecordPose);

RecordPose::RecordPose(const std::string& name) :
	DeviceFilter(name),
	m_cumulativeTime(0)
{
	m_timer.setMaxNumberOfFrames(1);
	m_timer.start();
}

RecordPose::~RecordPose()
{
	if (m_outputFile.is_open())
	{
		m_outputFile.close();
	}
}

void RecordPose::setFilename(const std::string& fileName)
{
	m_fileName = fileName;
}

const std::string& RecordPose::getFilename() const
{
	return m_fileName;
}

bool RecordPose::initialize()
{
	SURGSIM_ASSERT(!isInitialized()) << getName() << " already initialized.";

	m_outputFile.open(m_fileName, std::ios::out | std::ios::trunc);
	SURGSIM_LOG_IF(!m_outputFile.is_open(), SurgSim::Framework::Logger::getLogger("Devices/RecordPose"), WARNING) <<
		"File " << m_fileName << " could not be open to record device pose";
	m_initialized = m_outputFile.is_open();

	return m_initialized;
}

void RecordPose::filterInput(const std::string& device, const DataGroup& dataToFilter, DataGroup* result)
{
	*result = dataToFilter;

	RigidTransform3d pose;
	if (dataToFilter.poses().get(DataStructures::Names::POSE, &pose))
	{
		m_timer.markFrame();
		m_cumulativeTime += m_timer.getLastFramePeriod();
		// We back up the time along with the pose to make sure we can replay the motion real-time, no matter
		// which rate it is recorded and replayed.
		m_outputFile << m_cumulativeTime << pose.matrix();
	}
}

};  // namespace Devices
};  // namespace SurgSim
<commit_msg>RecordPose is now recording time and pose with end line in between.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013-2015, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Devices/DeviceFilters/RecordPose.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Math/RigidTransform.h"

using SurgSim::DataStructures::DataGroup;
using SurgSim::Math::RigidTransform3d;

namespace SurgSim
{
namespace Devices
{

SURGSIM_REGISTER(SurgSim::Input::DeviceInterface, SurgSim::Devices::RecordPose, RecordPose);

RecordPose::RecordPose(const std::string& name) :
	DeviceFilter(name),
	m_cumulativeTime(0)
{
	m_timer.setMaxNumberOfFrames(1);
	m_timer.start();
}

RecordPose::~RecordPose()
{
	if (m_outputFile.is_open())
	{
		m_outputFile.close();
	}
}

void RecordPose::setFilename(const std::string& fileName)
{
	m_fileName = fileName;
}

const std::string& RecordPose::getFilename() const
{
	return m_fileName;
}

bool RecordPose::initialize()
{
	SURGSIM_ASSERT(!isInitialized()) << getName() << " already initialized.";

	m_outputFile.open(m_fileName, std::ios::out | std::ios::trunc);
	SURGSIM_LOG_IF(!m_outputFile.is_open(), SurgSim::Framework::Logger::getLogger("Devices/RecordPose"), WARNING) <<
		"File " << m_fileName << " could not be open to record device pose";
	m_initialized = m_outputFile.is_open();

	return m_initialized;
}

void RecordPose::filterInput(const std::string& device, const DataGroup& dataToFilter, DataGroup* result)
{
	*result = dataToFilter;

	RigidTransform3d pose;
	if (dataToFilter.poses().get(DataStructures::Names::POSE, &pose))
	{
		m_timer.markFrame();
		m_cumulativeTime += m_timer.getLastFramePeriod();
		// We back up the time along with the pose to make sure we can replay the motion real-time, no matter
		// which rate it is recorded and replayed.
		m_outputFile << m_cumulativeTime << std::endl << pose.matrix() << std::endl;
	}
}

};  // namespace Devices
};  // namespace SurgSim
<|endoftext|>


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

#ifndef _CPPCANVAS_IMPLSPRITECANVAS_HXX
#define _CPPCANVAS_IMPLSPRITECANVAS_HXX

#ifndef _DRAFTS_COM_SUN_STAR_RENDERING_XSPRITECANVAS_HPP__
#include <drafts/com/sun/star/rendering/XSpriteCanvas.hpp>
#endif

#ifndef _BGFX_VECTOR_B2DSIZE_HXX
#include <basegfx/vector/b2dsize.hxx>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif

#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif

#ifndef _CPPCANVAS_SPRITECANVAS_HXX
#include <cppcanvas/spritecanvas.hxx>
#endif

#include <implbitmapcanvas.hxx>

namespace cppcanvas
{
    namespace internal
    {
        class ImplSpriteCanvas : public virtual SpriteCanvas, protected virtual ImplBitmapCanvas
        {
        public:
            ImplSpriteCanvas( const ::com::sun::star::uno::Reference<
                                  ::drafts::com::sun::star::rendering::XSpriteCanvas >& rCanvas );
            ImplSpriteCanvas(const ImplSpriteCanvas&);

            virtual ~ImplSpriteCanvas();

            virtual void                    setTransformation( const ::basegfx::B2DHomMatrix& rMatrix );

            virtual bool                    updateScreen( bool bUpdateAll ) const;

            virtual CustomSpriteSharedPtr   createCustomSprite( const ::basegfx::B2DSize& ) const;
            virtual SpriteSharedPtr         createClonedSprite( const SpriteSharedPtr& ) const;

            SpriteSharedPtr                 createSpriteFromBitmaps(
                const ::com::sun::star::uno::Sequence<
                    ::com::sun::star::uno::Reference<
                        ::drafts::com::sun::star::rendering::XBitmap > >&   animationBitmaps,
                sal_Int8                                                    interpolationMode );

            virtual CanvasSharedPtr         clone() const;

            virtual ::com::sun::star::uno::Reference<
                ::drafts::com::sun::star::rendering::XSpriteCanvas >    getUNOSpriteCanvas() const;

            /** This class passes the view transformation
                to child sprites

                This helper class is necessary, because the
                ImplSpriteCanvas object cannot hand out shared ptrs of
                itself, but has somehow pass an object to child
                sprites those can query for the canvas' view transform.
             */
            class TransformationArbiter
            {
            public:
                TransformationArbiter();

                void                        setTransformation( const ::basegfx::B2DHomMatrix& rViewTransform );
                ::basegfx::B2DHomMatrix     getTransformation() const;

            private:
                ::basegfx::B2DHomMatrix     maTransformation;
            };

            typedef ::boost::shared_ptr< TransformationArbiter > TransformationArbiterSharedPtr;

        private:
            // default: disabled assignment
            ImplSpriteCanvas& operator=( const ImplSpriteCanvas& );

            const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::rendering::XSpriteCanvas >    mxSpriteCanvas;
            TransformationArbiterSharedPtr                                                                  mpTransformArbiter;
        };
    }
}

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

#ifndef _CPPCANVAS_IMPLSPRITECANVAS_HXX
#define _CPPCANVAS_IMPLSPRITECANVAS_HXX

#ifndef _COM_SUN_STAR_RENDERING_XSPRITECANVAS_HPP__
#include <com/sun/star/rendering/XSpriteCanvas.hpp>
#endif

#ifndef _BGFX_VECTOR_B2DSIZE_HXX
#include <basegfx/vector/b2dsize.hxx>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif

#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif

#ifndef _CPPCANVAS_SPRITECANVAS_HXX
#include <cppcanvas/spritecanvas.hxx>
#endif

#include <implbitmapcanvas.hxx>

namespace cppcanvas
{
    namespace internal
    {
        class ImplSpriteCanvas : public virtual SpriteCanvas, protected virtual ImplBitmapCanvas
        {
        public:
            ImplSpriteCanvas( const ::com::sun::star::uno::Reference<
                                  ::com::sun::star::rendering::XSpriteCanvas >& rCanvas );
            ImplSpriteCanvas(const ImplSpriteCanvas&);

            virtual ~ImplSpriteCanvas();

            virtual void                    setTransformation( const ::basegfx::B2DHomMatrix& rMatrix );

            virtual bool                    updateScreen( bool bUpdateAll ) const;

            virtual CustomSpriteSharedPtr   createCustomSprite( const ::basegfx::B2DSize& ) const;
            virtual SpriteSharedPtr         createClonedSprite( const SpriteSharedPtr& ) const;

            SpriteSharedPtr                 createSpriteFromBitmaps(
                const ::com::sun::star::uno::Sequence<
                    ::com::sun::star::uno::Reference<
                        ::com::sun::star::rendering::XBitmap > >&   animationBitmaps,
                sal_Int8                                                    interpolationMode );

            virtual CanvasSharedPtr         clone() const;

            virtual ::com::sun::star::uno::Reference<
                ::com::sun::star::rendering::XSpriteCanvas >    getUNOSpriteCanvas() const;

            /** This class passes the view transformation
                to child sprites

                This helper class is necessary, because the
                ImplSpriteCanvas object cannot hand out shared ptrs of
                itself, but has somehow pass an object to child
                sprites those can query for the canvas' view transform.
             */
            class TransformationArbiter
            {
            public:
                TransformationArbiter();

                void                        setTransformation( const ::basegfx::B2DHomMatrix& rViewTransform );
                ::basegfx::B2DHomMatrix     getTransformation() const;

            private:
                ::basegfx::B2DHomMatrix     maTransformation;
            };

            typedef ::boost::shared_ptr< TransformationArbiter > TransformationArbiterSharedPtr;

        private:
            // default: disabled assignment
            ImplSpriteCanvas& operator=( const ImplSpriteCanvas& );

            const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XSpriteCanvas >    mxSpriteCanvas;
            TransformationArbiterSharedPtr                                                                  mpTransformArbiter;
        };
    }
}

#endif /* _CPPCANVAS_IMPLSPRITECANVAS_HXX */
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_ASSEMBLER_SYSTEM_HH
#define DUNE_GDT_ASSEMBLER_SYSTEM_HH

#include <type_traits>
#include <memory>

#include <dune/common/version.hh>

#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //&& HAVE_TBB //EXADUNE
# include <dune/grid/utility/partitioning/seedlist.hh>
# include <dune/stuff/common/parallel/partitioner.hh>
#endif

#include <dune/stuff/grid/walker.hh>
#include <dune/stuff/common/parallel/helper.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/constraints.hh>

#include "local/codim0.hh"
#include "local/codim1.hh"
#include "wrapper.hh"

namespace Dune {
namespace GDT {

template< class TestSpaceImp,
          class GridViewImp = typename TestSpaceImp::GridViewType,
          class AnsatzSpaceImp = TestSpaceImp >
class SystemAssembler
  : public DSG::Walker< GridViewImp >
{
  static_assert(std::is_base_of< SpaceInterface< typename TestSpaceImp::Traits >, TestSpaceImp >::value,
                "TestSpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of< SpaceInterface< typename AnsatzSpaceImp::Traits >, AnsatzSpaceImp >::value,
                "AnsatzSpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_same< typename TestSpaceImp::RangeFieldType, typename AnsatzSpaceImp::RangeFieldType >::value,
                "Types do not match!");
  typedef DSG::Walker< GridViewImp >                                  BaseType;
  typedef SystemAssembler<TestSpaceImp, GridViewImp, AnsatzSpaceImp > ThisType;
public:
  typedef TestSpaceImp                           TestSpaceType;
  typedef AnsatzSpaceImp                         AnsatzSpaceType;
  typedef typename TestSpaceType::RangeFieldType RangeFieldType;

  typedef typename BaseType::GridViewType     GridViewType;
  typedef typename BaseType::EntityType       EntityType;
  typedef typename BaseType::IntersectionType IntersectionType;

  typedef DSG::ApplyOn::WhichEntity< GridViewType >       ApplyOnWhichEntity;
  typedef DSG::ApplyOn::WhichIntersection< GridViewType > ApplyOnWhichIntersection;

  SystemAssembler(const TestSpaceType test, const AnsatzSpaceType ansatz, const GridViewType& grid_view)
    : BaseType(grid_view)
    , test_space_(test)
    , ansatz_space_(ansatz)
  {}

  SystemAssembler(const TestSpaceType test, const AnsatzSpaceType ansatz)
    : BaseType(test.grid_view())
    , test_space_(test)
    , ansatz_space_(ansatz)
  {}

  SystemAssembler(const TestSpaceType test)
    : BaseType(test.grid_view())
    , test_space_(test)
    , ansatz_space_(test)
  {}

  SystemAssembler(const TestSpaceType test, const GridViewType& grid_view)
    : BaseType(grid_view)
    , test_space_(test)
    , ansatz_space_(test_space_)
  {}

  const TestSpaceType& test_space() const
  {
    return *test_space_;
  }

  const AnsatzSpaceType& ansatz_space() const
  {
    return *ansatz_space_;
  }

  using BaseType::add;

  template< class C, class M >
  void add(Spaces::ConstraintsInterface< C, RangeFieldType >& constraints,
           Stuff::LA::MatrixInterface< M >& matrix,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    assert(matrix.rows() == test_space_->mapper().size());
    assert(matrix.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalMatrixConstraintsWrapper< TestSpaceType,
                                                     AnsatzSpaceType,
                                                     GridViewType,
                                                     typename C::derived_type,
                                                     typename M::derived_type > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_,
                                                        ansatz_space_,
                                                        where,
                                                        constraints.as_imp(),
                                                        matrix.as_imp()));
  } // ... add(...)

  template< class ConstraintsType, class V >
  void add(ConstraintsType& constraints,
           Stuff::LA::VectorInterface< V >& vector,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVectorConstraintsWrapper< ThisType, ConstraintsType, VectorType > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, constraints, vector_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim0Matrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M >& matrix,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim0Matrix< L >, MatrixType >
        WrapperType;
    this->codim0_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class Codim0Assembler, class M >
  void add_codim0_assembler(const Codim0Assembler& local_assembler,
                            Stuff::LA::MatrixInterface< M >& matrix,
                            const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, Codim0Assembler, MatrixType > WrapperType;
    this->codim0_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class Codim0Assembler, class V >
  void add_codim0_assembler(const Codim0Assembler& local_assembler,
                            Stuff::LA::VectorInterface< V >& vector,
                            const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, Codim0Assembler, VectorType > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim1CouplingMatrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M >& matrix,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1CouplingMatrix< L >, MatrixType >
        WrapperType;
    this->codim1_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim1BoundaryMatrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M >& matrix,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1BoundaryMatrix< L >, MatrixType >
        WrapperType;
    this->codim1_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class L, class V >
  void add(const LocalAssembler::Codim0Vector< L >& local_assembler,
           Stuff::LA::VectorInterface< V >& vector,
           const ApplyOnWhichEntity* where
              = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, LocalAssembler::Codim0Vector< L >, VectorType >
        WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  template< class L, class V >
  void add(const LocalAssembler::Codim1Vector< L >& local_assembler,
           Stuff::LA::VectorInterface< V >& vector,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = static_cast< VectorType& >(vector);
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalFaceVectorAssemblerWrapper< ThisType, LocalAssembler::Codim1Vector< L >, VectorType >
        WrapperType;
    this->codim1_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  void assemble(const bool clear_stack = true)
  {
    this->walk(clear_stack);
  }

#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //&& HAVE_TBB //EXADUNE
  void tbb_assemble(const bool clear_stack = true)
  {
    Stuff::IndexSetPartitioner< GridViewType > partioner(this->grid_view_.indexSet());
    SeedListPartitioning< typename GridViewType::Grid, 0 > partitioning(this->grid_view_, partioner);
    this->tbb_walk(partitioning, clear_stack);
  }
#endif

private:
  const DS::PerThreadValue<const TestSpaceType>& test_space_;
  const DS::PerThreadValue<const AnsatzSpaceType>& ansatz_space_;
}; // class SystemAssembler

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMBLER_SYSTEM_HH
<commit_msg>[assembler] fixes c&p error<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_ASSEMBLER_SYSTEM_HH
#define DUNE_GDT_ASSEMBLER_SYSTEM_HH

#include <type_traits>
#include <memory>

#include <dune/common/version.hh>

#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //&& HAVE_TBB //EXADUNE
# include <dune/grid/utility/partitioning/seedlist.hh>
# include <dune/stuff/common/parallel/partitioner.hh>
#endif

#include <dune/stuff/grid/walker.hh>
#include <dune/stuff/common/parallel/helper.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/constraints.hh>

#include "local/codim0.hh"
#include "local/codim1.hh"
#include "wrapper.hh"

namespace Dune {
namespace GDT {

template< class TestSpaceImp,
          class GridViewImp = typename TestSpaceImp::GridViewType,
          class AnsatzSpaceImp = TestSpaceImp >
class SystemAssembler
  : public DSG::Walker< GridViewImp >
{
  static_assert(std::is_base_of< SpaceInterface< typename TestSpaceImp::Traits >, TestSpaceImp >::value,
                "TestSpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of< SpaceInterface< typename AnsatzSpaceImp::Traits >, AnsatzSpaceImp >::value,
                "AnsatzSpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_same< typename TestSpaceImp::RangeFieldType, typename AnsatzSpaceImp::RangeFieldType >::value,
                "Types do not match!");
  typedef DSG::Walker< GridViewImp >                                  BaseType;
  typedef SystemAssembler<TestSpaceImp, GridViewImp, AnsatzSpaceImp > ThisType;
public:
  typedef TestSpaceImp                           TestSpaceType;
  typedef AnsatzSpaceImp                         AnsatzSpaceType;
  typedef typename TestSpaceType::RangeFieldType RangeFieldType;

  typedef typename BaseType::GridViewType     GridViewType;
  typedef typename BaseType::EntityType       EntityType;
  typedef typename BaseType::IntersectionType IntersectionType;

  typedef DSG::ApplyOn::WhichEntity< GridViewType >       ApplyOnWhichEntity;
  typedef DSG::ApplyOn::WhichIntersection< GridViewType > ApplyOnWhichIntersection;

  SystemAssembler(const TestSpaceType test, const AnsatzSpaceType ansatz, const GridViewType& grid_view)
    : BaseType(grid_view)
    , test_space_(test)
    , ansatz_space_(ansatz)
  {}

  SystemAssembler(const TestSpaceType test, const AnsatzSpaceType ansatz)
    : BaseType(test.grid_view())
    , test_space_(test)
    , ansatz_space_(ansatz)
  {}

  SystemAssembler(const TestSpaceType test)
    : BaseType(test.grid_view())
    , test_space_(test)
    , ansatz_space_(test)
  {}

  SystemAssembler(const TestSpaceType test, const GridViewType& grid_view)
    : BaseType(grid_view)
    , test_space_(test)
    , ansatz_space_(test_space_)
  {}

  const TestSpaceType& test_space() const
  {
    return *test_space_;
  }

  const AnsatzSpaceType& ansatz_space() const
  {
    return *ansatz_space_;
  }

  using BaseType::add;

  template< class C, class M >
  void add(Spaces::ConstraintsInterface< C, RangeFieldType >& constraints,
           Stuff::LA::MatrixInterface< M >& matrix,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    assert(matrix.rows() == test_space_->mapper().size());
    assert(matrix.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalMatrixConstraintsWrapper< TestSpaceType,
                                                     AnsatzSpaceType,
                                                     GridViewType,
                                                     typename C::derived_type,
                                                     typename M::derived_type > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_,
                                                        ansatz_space_,
                                                        where,
                                                        constraints.as_imp(),
                                                        matrix.as_imp()));
  } // ... add(...)

  template< class ConstraintsType, class V >
  void add(ConstraintsType& constraints,
           Stuff::LA::VectorInterface< V >& vector,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVectorConstraintsWrapper< ThisType, ConstraintsType, VectorType > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, constraints, vector_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim0Matrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M >& matrix,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim0Matrix< L >, MatrixType >
        WrapperType;
    this->codim0_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class Codim0Assembler, class M >
  void add_codim0_assembler(const Codim0Assembler& local_assembler,
                            Stuff::LA::MatrixInterface< M >& matrix,
                            const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, Codim0Assembler, MatrixType > WrapperType;
    this->codim0_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class Codim0Assembler, class V >
  void add_codim0_assembler(const Codim0Assembler& local_assembler,
                            Stuff::LA::VectorInterface< V >& vector,
                            const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, Codim0Assembler, VectorType > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim1CouplingMatrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M >& matrix,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1CouplingMatrix< L >, MatrixType >
        WrapperType;
    this->codim1_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim1BoundaryMatrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M >& matrix,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1BoundaryMatrix< L >, MatrixType >
        WrapperType;
    this->codim1_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class L, class V >
  void add(const LocalAssembler::Codim0Vector< L >& local_assembler,
           Stuff::LA::VectorInterface< V >& vector,
           const ApplyOnWhichEntity* where
              = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, LocalAssembler::Codim0Vector< L >, VectorType >
        WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  template< class L, class V >
  void add(const LocalAssembler::Codim1Vector< L >& local_assembler,
           Stuff::LA::VectorInterface< V >& vector,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = static_cast< VectorType& >(vector);
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalFaceVectorAssemblerWrapper< ThisType, LocalAssembler::Codim1Vector< L >, VectorType >
        WrapperType;
    this->codim1_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  void assemble(const bool clear_stack = true)
  {
    this->walk(clear_stack);
  }

#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //&& HAVE_TBB //EXADUNE
  void tbb_assemble(const bool clear_stack = true)
  {
    Stuff::IndexSetPartitioner< GridViewType > partioner(this->grid_view_.indexSet());
    SeedListPartitioning< typename GridViewType::Grid, 0 > partitioning(this->grid_view_, partioner);
    this->tbb_walk(partitioning, clear_stack);
  }
#endif

private:
  const DS::PerThreadValue<const TestSpaceType> test_space_;
  const DS::PerThreadValue<const AnsatzSpaceType> ansatz_space_;
}; // class SystemAssembler

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMBLER_SYSTEM_HH
<|endoftext|>


<commit_before>#ifndef COFFEE_MILL_UTIL_STRING_HPP
#define COFFEE_MILL_UTIL_STRING_HPP
#include <string>
#include <algorithm>

namespace mill
{

template<typename charT>
inline bool is_whitespace(charT c)
{
    return (c == ' ') || (c == '\t');
}

template<typename charT, typename Traits, typename Alloc>
std::basic_string<charT, Traits, Alloc>
remove_indent(const std::basic_string<charT, Traits, Alloc>& str)
{
    auto iter = str.cbegin();
    while(is_whitespace(*iter) && (iter != str.cend())){++iter;}
    return std::basic_string<charT>(iter, str.cend());
}

template<typename charT, typename Traits, typename Alloc>
std::basic_string<charT, Traits, Alloc>
remove_all(const charT c, const std::basic_string<charT, Traits, Alloc>& str)
{
    std::basic_string<charT> retval;
    for(auto iter = str.cbegin(); iter != str.cend(); ++iter)
    {
        if(*iter != c)
        {
            retval += *iter;
        }
    }
    return retval;
}

} // mill
#endif /* COFFEE_MILL_UTILITY */
<commit_msg>:recycle: refactor util/string by c++17 feature<commit_after>#ifndef COFFEE_MILL_UTIL_STRING_HPP
#define COFFEE_MILL_UTIL_STRING_HPP
#include <string>
#include <algorithm>

namespace mill
{

template<typename charT, typename Traits, typename Alloc>
std::basic_string<charT, Traits, Alloc>
remove_indent(const std::basic_string<charT, Traits, Alloc>& str)
{
    auto iter = str.cbegin();
    while(const char c = *iter; (c == ' ' || c == '\t') && (iter != str.cend()))
    {
        ++iter;
    }
    return std::basic_string<charT, Traits, Alloc>(iter, str.cend());
}

template<typename charT, typename Traits, typename Alloc>
std::basic_string<charT, Traits, Alloc>
remove_all(const charT c, const std::basic_string<charT, Traits, Alloc>& str)
{
    auto retval = str;
    retval.erase(std::remove(retval.begin(), retval.end(), c), retval.end());
    return retval;
}

} // mill
#endif /* COFFEE_MILL_UTILITY */
<|endoftext|>


<commit_before>// Copyright (c) 2009 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.

// This application is a test for AudioRendererAlgorithmOLA. It reads in a
// specified wav file (so far only 8, 16 and 32 bit are supported) and uses
// ARAO to scale the playback by a specified rate. Then it outputs the result
// to the specified location. Command line calls should be as follows:
//
//    wav_ola_test RATE INFILE OUTFILE

#include <iostream>
#include <string>

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/ref_counted.h"
#include "base/string_util.h"
#include "media/base/data_buffer.h"
#include "media/filters/audio_renderer_algorithm_ola.h"

using file_util::ScopedFILE;
using media::AudioRendererAlgorithmOLA;
using media::DataBuffer;

const size_t kDefaultWindowSize = 4096;

struct WavHeader {
  int32 riff;
  int32 chunk_size;
  char unused0[8];
  int32 subchunk1_size;
  int16 audio_format;
  int16 channels;
  int32 sample_rate;
  char unused1[6];
  int16 bit_rate;
  char unused2[4];
  int32 subchunk2_size;
};

// Dummy class to feed data to OLA algorithm. Necessary to create callback.
class Dummy {
 public:
  Dummy(FILE* in, AudioRendererAlgorithmOLA* ola)
      : input_(in),
        ola_(ola) {
  }

  void ReadDataForAlg() {
    scoped_refptr<DataBuffer> b(new DataBuffer());
    uint8* buf = b->GetWritableData(kDefaultWindowSize);
    if (fread(buf, 1, kDefaultWindowSize, input_) > 0) {
      ola_->EnqueueBuffer(b.get());
    }
  }

 private:
  FILE* input_;
  AudioRendererAlgorithmOLA* ola_;

  DISALLOW_COPY_AND_ASSIGN(Dummy);
};

int main(int argc, const char** argv) {
  AudioRendererAlgorithmOLA ola;
  CommandLine::Init(argc, argv);
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();

  std::vector<std::wstring> filenames(cmd_line->GetLooseValues());
  if (filenames.empty()) {
    std::cerr << "Usage: alg_test RATE INFILE OUTFILE\n"
              << std::endl;
    return 1;
  }

  // Retrieve command line options.
  std::string in_path(WideToUTF8(filenames[1]));
  std::string out_path(WideToUTF8(filenames[2]));
  double playback_rate = 0.0;

  // Determine speed of rerecord.
  if (!StringToDouble(WideToUTF8(filenames[0]), &playback_rate))
    playback_rate = 0.0;

  // Open input file.
  ScopedFILE input(file_util::OpenFile(in_path.c_str(), "rb"));
  if (!(input.get())) {
    LOG(ERROR) << "could not open input";
    return 1;
  }

  // Open output file.
  ScopedFILE output(file_util::OpenFile(out_path.c_str(), "wb"));
  if (!(output.get())) {
    LOG(ERROR) << "could not open output";
    return 1;
  }

  // Read in header.
  WavHeader wav;
  if (fread(&wav, sizeof(wav), 1, input.get()) < 1) {
    LOG(ERROR) << "could not read WAV header";
    return 1;
  }

  // Instantiate dummy class and callback to feed data to |ola|.
  Dummy guy(input.get(), &ola);
  AudioRendererAlgorithmOLA::RequestReadCallback* cb =
      NewCallback(&guy, &Dummy::ReadDataForAlg);
  ola.Initialize(wav.channels,
                 wav.bit_rate,
                 static_cast<float>(playback_rate),
                 cb);

  // Print out input format.
  std::cout << in_path << "\n"
            << "Channels: " << wav.channels << "\n"
            << "Sample Rate: " << wav.sample_rate << "\n"
            << "Bit Rate: " << wav.bit_rate << "\n"
            << "\n"
            << "Scaling audio by " << playback_rate << "x..." << std::endl;

  // Write the header back out again.
  if (fwrite(&wav, sizeof(wav), 1, output.get()) < 1) {
    LOG(ERROR) << "could not write WAV header";
    return 1;
  }

  // Create buffer to be filled by |ola|.
  scoped_refptr<DataBuffer> buffer(new DataBuffer());
  uint8* buf = buffer->GetWritableData(kDefaultWindowSize);

  // Keep track of bytes written to disk and bytes copied to |b|.
  size_t bytes_written = 0;
  size_t bytes;
  while ((bytes = ola.FillBuffer(buffer.get())) > 0) {
    if (fwrite(buf, 1, bytes, output.get()) != bytes) {
      LOG(ERROR) << "could not write data after " << bytes_written;
    } else {
      bytes_written += bytes;
    }
  }

  // Seek back to the beginning of our output file and update the header.
  wav.chunk_size = 36 + bytes_written;
  wav.subchunk1_size = 16;
  wav.subchunk2_size = bytes_written;
  fseek(output.get(), 0, SEEK_SET);
  fwrite(&wav, sizeof(wav), 1, output.get());

  return 0;
}
<commit_msg>Test fwrite returnval in wav_ola_test.cc to fix ubuntu compile warning. Review URL: http://codereview.chromium.org/155160<commit_after>// Copyright (c) 2009 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.

// This application is a test for AudioRendererAlgorithmOLA. It reads in a
// specified wav file (so far only 8, 16 and 32 bit are supported) and uses
// ARAO to scale the playback by a specified rate. Then it outputs the result
// to the specified location. Command line calls should be as follows:
//
//    wav_ola_test RATE INFILE OUTFILE

#include <iostream>
#include <string>

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/ref_counted.h"
#include "base/string_util.h"
#include "media/base/data_buffer.h"
#include "media/filters/audio_renderer_algorithm_ola.h"

using file_util::ScopedFILE;
using media::AudioRendererAlgorithmOLA;
using media::DataBuffer;

const size_t kDefaultWindowSize = 4096;

struct WavHeader {
  int32 riff;
  int32 chunk_size;
  char unused0[8];
  int32 subchunk1_size;
  int16 audio_format;
  int16 channels;
  int32 sample_rate;
  char unused1[6];
  int16 bit_rate;
  char unused2[4];
  int32 subchunk2_size;
};

// Dummy class to feed data to OLA algorithm. Necessary to create callback.
class Dummy {
 public:
  Dummy(FILE* in, AudioRendererAlgorithmOLA* ola)
      : input_(in),
        ola_(ola) {
  }

  void ReadDataForAlg() {
    scoped_refptr<DataBuffer> b(new DataBuffer());
    uint8* buf = b->GetWritableData(kDefaultWindowSize);
    if (fread(buf, 1, kDefaultWindowSize, input_) > 0) {
      ola_->EnqueueBuffer(b.get());
    }
  }

 private:
  FILE* input_;
  AudioRendererAlgorithmOLA* ola_;

  DISALLOW_COPY_AND_ASSIGN(Dummy);
};

int main(int argc, const char** argv) {
  AudioRendererAlgorithmOLA ola;
  CommandLine::Init(argc, argv);
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();

  std::vector<std::wstring> filenames(cmd_line->GetLooseValues());
  if (filenames.empty()) {
    std::cerr << "Usage: alg_test RATE INFILE OUTFILE\n"
              << std::endl;
    return 1;
  }

  // Retrieve command line options.
  std::string in_path(WideToUTF8(filenames[1]));
  std::string out_path(WideToUTF8(filenames[2]));
  double playback_rate = 0.0;

  // Determine speed of rerecord.
  if (!StringToDouble(WideToUTF8(filenames[0]), &playback_rate))
    playback_rate = 0.0;

  // Open input file.
  ScopedFILE input(file_util::OpenFile(in_path.c_str(), "rb"));
  if (!(input.get())) {
    LOG(ERROR) << "could not open input";
    return 1;
  }

  // Open output file.
  ScopedFILE output(file_util::OpenFile(out_path.c_str(), "wb"));
  if (!(output.get())) {
    LOG(ERROR) << "could not open output";
    return 1;
  }

  // Read in header.
  WavHeader wav;
  if (fread(&wav, sizeof(wav), 1, input.get()) < 1) {
    LOG(ERROR) << "could not read WAV header";
    return 1;
  }

  // Instantiate dummy class and callback to feed data to |ola|.
  Dummy guy(input.get(), &ola);
  AudioRendererAlgorithmOLA::RequestReadCallback* cb =
      NewCallback(&guy, &Dummy::ReadDataForAlg);
  ola.Initialize(wav.channels,
                 wav.bit_rate,
                 static_cast<float>(playback_rate),
                 cb);

  // Print out input format.
  std::cout << in_path << "\n"
            << "Channels: " << wav.channels << "\n"
            << "Sample Rate: " << wav.sample_rate << "\n"
            << "Bit Rate: " << wav.bit_rate << "\n"
            << "\n"
            << "Scaling audio by " << playback_rate << "x..." << std::endl;

  // Write the header back out again.
  if (fwrite(&wav, sizeof(wav), 1, output.get()) < 1) {
    LOG(ERROR) << "could not write WAV header";
    return 1;
  }

  // Create buffer to be filled by |ola|.
  scoped_refptr<DataBuffer> buffer(new DataBuffer());
  uint8* buf = buffer->GetWritableData(kDefaultWindowSize);

  // Keep track of bytes written to disk and bytes copied to |b|.
  size_t bytes_written = 0;
  size_t bytes;
  while ((bytes = ola.FillBuffer(buffer.get())) > 0) {
    if (fwrite(buf, 1, bytes, output.get()) != bytes) {
      LOG(ERROR) << "could not write data after " << bytes_written;
    } else {
      bytes_written += bytes;
    }
  }

  // Seek back to the beginning of our output file and update the header.
  wav.chunk_size = 36 + bytes_written;
  wav.subchunk1_size = 16;
  wav.subchunk2_size = bytes_written;
  fseek(output.get(), 0, SEEK_SET);
  if (fwrite(&wav, sizeof(wav), 1, output.get()) < 1) {
    LOG(ERROR) << "could not write wav header.";
    return 1;
  }

  return 0;
}
<|endoftext|>


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

#include "dp_lib_container.h"
#include "dp_backend.h"
#include "dp_ucb.h"
#include "rtl/uri.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "ucbhelper/content.hxx"
#include "comphelper/anytostring.hxx"
#include <memory>

using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using ::rtl::OUString;

namespace dp_registry
{
namespace backend
{
namespace script
{

//==============================================================================
class BackendImpl : public ::dp_registry::backend::PackageRegistryBackend
{
protected:
    // PackageRegistryBackend
    virtual Reference< deployment::XPackage > createPackage(
        OUString const & url,
        OUString const & mediaType, OUString const & subType,
        INetContentTypeParameterList const & params,
        Reference< XCommandEnvironment > const & xCmdEnv );

public:
    // currently only for library containers:
    enum { LAYER_NONE, LAYER_USER, LAYER_SHARED } m_layer;

    ::std::auto_ptr< LibraryContainer > m_basic_script_libs;
    ::std::auto_ptr< LibraryContainer > m_dialog_libs;

    inline BackendImpl(
        Reference< XComponentContext > const & xComponentContext,
        OUString const & implName,
        Sequence< OUString > const & supported_media_types )
        : PackageRegistryBackend(
            xComponentContext, implName, supported_media_types ),
          m_layer( LAYER_NONE )
        {}

    // XInitialization
    virtual void SAL_CALL initialize( Sequence< Any > const & args )
        throw (RuntimeException);

    // XPackageRegistry
    virtual OUString SAL_CALL detectMediaType( OUString const & url )
        throw (RuntimeException);
};

//==============================================================================
class PackageImpl : public ::dp_registry::backend::Package
{
    bool m_scriptLib;
    OUString m_libURL;
    OUString const & getLibName(
        Reference< XCommandEnvironment > const & xCmdEnv );

    inline BackendImpl * getMyBackend() const
        { return static_cast< BackendImpl * >(m_myBackend.get()); }

    inline LibraryContainer * getContainer() const
    {
        return m_scriptLib ? getMyBackend()->m_basic_script_libs.get()
                           : getMyBackend()->m_dialog_libs.get();
    }

    // OPropertySetHelper
    virtual void SAL_CALL getFastPropertyValue(
        Any & rValue, sal_Int32 nHandle ) const;

    // Package
    virtual t_Registered getRegStatus(
        ::osl::ResettableMutexGuard & guard,
        Reference< XCommandEnvironment > const & xCmdEnv );
    virtual bool processPackage(
        bool register_package,
        ::osl::ResettableMutexGuard & guard,
        Reference< XCommandEnvironment > const & xCmdEnv );

public:
    PackageImpl(
        ::rtl::Reference< PackageRegistryBackend > const & myBackend,
        OUString const & url,
        OUString const & mediaType,
        bool scriptLib )
        : Package( myBackend, url, mediaType,
                   OUString() /* no name yet */,
                   OUString() /* no display-name yet */,
                   scriptLib
                   ? OUSTR("Basic Script Library")
                   : OUSTR("Dialog Library") ),
          m_scriptLib( scriptLib ),
          m_libURL( make_url( url, scriptLib ? OUSTR("script.xlb")
                                             : OUSTR("dialog.xlb") ) )
        {}
};

//______________________________________________________________________________
void BackendImpl::initialize( Sequence< Any > const & args )
    throw (RuntimeException)
{
    PackageRegistryBackend::initialize( args );

    if (args.getLength() > 2) // optional context
    {
        OUString context( extract_throw< OUString >( args[ 2 ] ) );
        if (context.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("user") ))
            m_layer = LAYER_USER;
        else if (context.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("shared") ))
            m_layer = LAYER_SHARED;
    }
    if (m_layer != LAYER_NONE)
    {
        OUString basic_path(
            m_layer == LAYER_USER
            ? OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
                    SAL_CONFIGFILE("bootstrap")
                    ":UserInstallation}/user/basic")
            : OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
                    SAL_CONFIGFILE("bootstrap")
                    ":BaseInstallation}/share/basic") );
        m_basic_script_libs.reset(
            new LibraryContainer(
                make_url( basic_path, OUSTR("/script.xlc") ),
                getMutex(),
                getComponentContext() ) );
        m_dialog_libs.reset(
            new LibraryContainer(
                make_url( basic_path, OUSTR("/dialog.xlc") ),
                getMutex(),
                getComponentContext() ) );
    }
}

//==============================================================================
OUString SAL_CALL getImplementationName()
{
    return OUSTR("com.sun.star.comp.deployment.script.PackageRegistryBackend");
}

//==============================================================================
Reference< XInterface > SAL_CALL create(
    Reference< XComponentContext > const & xComponentContext )
    SAL_THROW( (Exception) )
{
    OUString const media_types [] = {
        OUSTR("application/vnd.sun.star.basic-script"),
        OUSTR("application/vnd.sun.star.dialog-library")
    };
    return static_cast< ::cppu::OWeakObject * >(
        new BackendImpl(
            xComponentContext, getImplementationName(),
            Sequence< OUString >( media_types, ARLEN(media_types) ) ) );
}

// XPackageRegistry
//______________________________________________________________________________
OUString BackendImpl::detectMediaType( OUString const & url )
    throw (RuntimeException)
{
    ::ucb::Content ucb_content;
    if (::ucb::Content::create( url, Reference< XCommandEnvironment >(),
                                ucb_content ) &&
        ucb_content.isFolder())
    {
        // probe for script.xlb:
        if (create_ucb_content(
                0, make_url( ucb_content.getURL(), OUSTR("script.xlb") ),
                Reference< XCommandEnvironment >(), false /* no throw */ ))
            return OUSTR("application/vnd.sun.star.basic-script");
        // probe for dialog.xlb:
        if (create_ucb_content(
                0, make_url( ucb_content.getURL(), OUSTR("dialog.xlb") ),
                Reference< XCommandEnvironment >(), false /* no throw */ ))
            return OUSTR("application/vnd.sun.star.dialog-library");
    }
    return OUString();
}

// PackageRegistryBackend
//______________________________________________________________________________
Reference< deployment::XPackage > BackendImpl::createPackage(
    OUString const & url,
    OUString const & mediaType, OUString const & subType,
    INetContentTypeParameterList const & params,
    Reference< XCommandEnvironment > const & xCmdEnv )
{
    if (subType.matchIgnoreAsciiCaseAsciiL(
            RTL_CONSTASCII_STRINGPARAM("vnd.sun.star.basic-script") ))
        return new PackageImpl( this, url, mediaType, true );
    if (subType.matchIgnoreAsciiCaseAsciiL(
            RTL_CONSTASCII_STRINGPARAM("vnd.sun.star.dialog-library") ))
        return new PackageImpl( this, url, mediaType, false );
    throw lang::IllegalArgumentException(
        OUSTR("invalid media-type given: ") + mediaType,
        static_cast< OWeakObject * >(this),
        static_cast< sal_Int16 >(-1 /* not known */) );
}

//##############################################################################

//______________________________________________________________________________
OUString const & PackageImpl::getLibName(
    Reference< XCommandEnvironment > const & xCmdEnv )
{
    ::osl::MutexGuard guard( getMutex() );
    if (m_name.getLength() == 0)
    {
        m_name = LibraryContainer::get_libname(
            m_libURL, xCmdEnv, getMyBackend()->getComponentContext() );
    }
    return m_name;
}

// OPropertySetHelper
//______________________________________________________________________________
void PackageImpl::getFastPropertyValue( Any & rValue, sal_Int32 nHandle ) const
{
    // xxx todo: upon disposing() getPropertyValue( URL )...
//     check();
    switch (nHandle)
    {
    case NAME:
    case DISPLAY_NAME:
    {
        try
        {
            rValue <<= const_cast< PackageImpl * >(this)->getLibName( 0 );
        }
        catch (RuntimeException &)
        {
            throw;
        }
        catch (Exception &)
        {
            Any exc( ::cppu::getCaughtException() );
            throw lang::WrappedTargetException(
                OUSTR("caught exception reading Basic library name!"),
                static_cast< OWeakObject * >(
                    const_cast< PackageImpl * >(this) ), exc );
        }
        break;
    }
    default:
        Package::getFastPropertyValue( rValue, nHandle );
        break;
    }
}

// Package
//______________________________________________________________________________
PackageImpl::t_Registered PackageImpl::getRegStatus(
    ::osl::ResettableMutexGuard & guard,
    Reference< XCommandEnvironment > const & xCmdEnv )
{
    BackendImpl * that = getMyBackend();
    if (that->m_layer == BackendImpl::LAYER_NONE)
        return REG_VOID;
    if (getContainer()->has( getLibName( xCmdEnv ), xCmdEnv ))
        return REG_REGISTERED;
    else
        return REG_NOT_REGISTERED;
}

//______________________________________________________________________________
bool PackageImpl::processPackage(
    bool register_package,
    ::osl::ResettableMutexGuard & guard,
    Reference< XCommandEnvironment > const & xCmdEnv )
{
    BackendImpl * that = getMyBackend();
    // xxx todo:
    OSL_ASSERT( that->m_layer != BackendImpl::LAYER_NONE );
    that->ensure_no_running_office();

    LibraryContainer * container = getContainer();
    bool success;
    if (register_package)
        success = container->insert( getLibName( xCmdEnv ), m_libURL, xCmdEnv );
    else // revokePackage()
        success = container->remove( getLibName( xCmdEnv ), m_libURL, xCmdEnv );
    success &= container->flush( xCmdEnv );
    return success;
}

} // namespace script
} // namespace backend
} // namespace dp_registry

<commit_msg>INTEGRATION: CWS unopkg2 (1.2.4); FILE MERGED 2004/06/09 14:09:21 dbo 1.2.4.6: #i30026# Basic/Dialogs libs found everywhere in legacy bundles 2004/05/26 12:38:25 dbo 1.2.4.5: #i20304# string review Issue number: Submitted by: Reviewed by: 2004/05/19 12:53:49 dbo 1.2.4.4: #i20304# minor fixes 2004/05/18 18:15:28 dbo 1.2.4.3: #115885# icons, minor fixes 2004/05/14 16:56:26 dbo 1.2.4.2: #i20304# live deployment, abort feature 2004/05/11 15:14:22 dbo 1.2.4.1: #i20304# major API revision, GUI Issue number: Submitted by: Reviewed by:<commit_after>/*************************************************************************
 *
 *  $RCSfile: dp_script.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2004-06-11 12:18:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "dp_script.hrc"
#include "dp_lib_container.h"
#include "dp_backend.h"
#include "dp_ucb.h"
#include "rtl/uri.hxx"
#include "ucbhelper/content.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "svtools/inettype.hxx"
#include "com/sun/star/script/XLibraryContainer.hpp"
#include <memory>

using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using ::rtl::OUString;
namespace css = ::com::sun::star;

namespace dp_registry
{
namespace backend
{
namespace script
{

//==============================================================================
class BackendImpl : public ::dp_registry::backend::PackageRegistryBackend
{
protected:
    // PackageRegistryBackend
    virtual Reference<deployment::XPackage> bindPackage_(
        OUString const & url, OUString const & mediaType,
        Reference<XCommandEnvironment> const & xCmdEnv );

public:
    Reference<css::script::XLibraryContainer> m_xScriptLibs;
    Reference<css::script::XLibraryContainer> m_xDialogLibs;
    ::std::auto_ptr<LibraryContainer> m_basic_script_libs;
    ::std::auto_ptr<LibraryContainer> m_dialog_libs;

    OUString m_strBasicLib;
    OUString m_strDialogLib;

    inline BackendImpl(
        Reference<XComponentContext> const & xComponentContext,
        OUString const & implName,
        Sequence<OUString> const & supportedMediaTypes )
        : PackageRegistryBackend(
            xComponentContext, implName, supportedMediaTypes ),
          m_strBasicLib( getResourceString(RID_STR_BASIC_LIB) ),
          m_strDialogLib( getResourceString(RID_STR_DIALOG_LIB) )
        {}

    // XInitialization
    virtual void SAL_CALL initialize( Sequence<Any> const & args )
        throw (Exception);
};

//==============================================================================
class PackageImpl : public ::dp_registry::backend::Package
{
protected:
    OUString m_scriptURL;
    OUString m_dialogURL;
    OUString m_dialogName;

    inline BackendImpl * getMyBackend() const
        { return static_cast<BackendImpl *>(m_myBackend.get()); }

    // Package
    virtual bool isRegistered_(
        ::osl::ResettableMutexGuard & guard,
        ::rtl::Reference<AbortChannel> const & abortChannel,
        Reference<XCommandEnvironment> const & xCmdEnv );
    virtual void processPackage_(
        ::osl::ResettableMutexGuard & guard,
        bool registerPackage,
        ::rtl::Reference<AbortChannel> const & abortChannel,
        Reference<XCommandEnvironment> const & xCmdEnv );

    inline PackageImpl(
        ::rtl::Reference<BackendImpl> const & myBackend,
        OUString const & url,
        OUString const & mediaType,
        OUString const & scriptURL, OUString const & dialogURL )
        : Package( myBackend.get(), url, mediaType,
                   OUString(), OUString(), // will be late-initialized
                   scriptURL.getLength() > 0
                   ? myBackend->m_strBasicLib : myBackend->m_strDialogLib ),
          m_scriptURL( scriptURL ),
          m_dialogURL( dialogURL )
        {}

public:
    static PackageImpl * create(
        ::rtl::Reference<BackendImpl> const & myBackend,
        OUString const & url,
        OUString const & mediaType,
        Reference<XCommandEnvironment> const &xCmdEnv,
        OUString const & scriptURL, OUString const & dialogURL );

    // XPackage
    virtual Any SAL_CALL getIcon( sal_Bool highContrast, sal_Bool smallIcon )
        throw (RuntimeException);
};

//______________________________________________________________________________
PackageImpl * PackageImpl::create(
    ::rtl::Reference<BackendImpl> const & myBackend,
    OUString const & url,
    OUString const & mediaType,
    Reference<XCommandEnvironment> const &xCmdEnv,
    OUString const & scriptURL, OUString const & dialogURL )
{
    ::std::auto_ptr<PackageImpl> ret(
        new PackageImpl( myBackend, url, mediaType, scriptURL, dialogURL ) );

    // name, displayName:
    if (dialogURL.getLength() > 0)
        ret->m_dialogName = LibraryContainer::get_libname(
            dialogURL, xCmdEnv, myBackend->getComponentContext() );
    if (scriptURL.getLength() > 0)
        ret->m_name = LibraryContainer::get_libname(
            scriptURL, xCmdEnv, myBackend->getComponentContext() );
    else
        ret->m_name = ret->m_dialogName;
    ret->m_displayName = ret->m_name;

    return ret.release();
}

//______________________________________________________________________________
void BackendImpl::initialize( Sequence< Any > const & args )
    throw (Exception)
{
    PackageRegistryBackend::initialize( args );

    if (! transientMode())
    {
        if (office_is_running())
        {
            Reference<XComponentContext> xContext( getComponentContext() );
            m_xScriptLibs.set(
                xContext->getServiceManager()->createInstanceWithContext(
                    OUSTR("com.sun.star."
                          "script.ApplicationScriptLibraryContainer"),
                    xContext ), UNO_QUERY_THROW );
            m_xDialogLibs.set(
                xContext->getServiceManager()->createInstanceWithContext(
                    OUSTR("com.sun.star."
                          "script.ApplicationDialogLibraryContainer"),
                    xContext ), UNO_QUERY_THROW );
        }
        else
        {
            OUString basic_path(
                m_eContext == CONTEXT_USER
                ? OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
                        SAL_CONFIGFILE("bootstrap")
                        ":UserInstallation}/user/basic")
                : OUSTR("vnd.sun.star.expand:${$SYSBINDIR/"
                        SAL_CONFIGFILE("bootstrap")
                        ":BaseInstallation}/share/basic") );
            m_basic_script_libs.reset(
                new LibraryContainer(
                    make_url( basic_path, OUSTR("/script.xlc") ),
                    getMutex(),
                    getComponentContext() ) );
            m_dialog_libs.reset(
                new LibraryContainer(
                    make_url( basic_path, OUSTR("/dialog.xlc") ),
                    getMutex(),
                    getComponentContext() ) );
        }
    }
}

//==============================================================================
OUString SAL_CALL getImplementationName()
{
    return OUSTR("com.sun.star.comp.deployment.script.PackageRegistryBackend");
}

//==============================================================================
Reference<XInterface> SAL_CALL create(
    Reference<XComponentContext> const & xComponentContext )
    SAL_THROW( (Exception) )
{
    OUString const mediaTypes [] = {
        OUSTR("application/vnd.sun.star.basic-script"),
        OUSTR("application/vnd.sun.star.dialog-library")
    };
    return static_cast< ::cppu::OWeakObject * >(
        new BackendImpl(
            xComponentContext, getImplementationName(),
            Sequence<OUString >( mediaTypes, ARLEN(mediaTypes) ) ) );
}

// PackageRegistryBackend
//______________________________________________________________________________
Reference<deployment::XPackage> BackendImpl::bindPackage_(
    OUString const & url, OUString const & mediaType_,
    Reference<XCommandEnvironment> const & xCmdEnv )
{
    OUString mediaType( mediaType_ );
    if (mediaType.getLength() == 0)
    {
        // detect media-type:
        ::ucb::Content ucbContent;
        if (create_ucb_content( &ucbContent, url, xCmdEnv ) &&
            ucbContent.isFolder())
        {
            // probe for script.xlb:
            if (create_ucb_content(
                    0, make_url( url, OUSTR("script.xlb") ),
                    xCmdEnv, false /* no throw */ ))
                mediaType = OUSTR("application/vnd.sun.star.basic-script");
            // probe for dialog.xlb:
            else if (create_ucb_content(
                         0, make_url( url, OUSTR("dialog.xlb") ),
                         xCmdEnv, false /* no throw */ ))
                mediaType = OUSTR("application/vnd.sun.star.dialog-library");
        }
        if (mediaType.getLength() == 0)
            throw lang::IllegalArgumentException(
                m_strCannotDetectMediaType + url,
                static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
    }

    String type, subType;
    INetContentTypeParameterList params;
    if (INetContentTypes::parse( mediaType, type, subType, &params ))
    {
        if (type.EqualsIgnoreCaseAscii("application"))
        {
            if (subType.EqualsIgnoreCaseAscii("vnd.sun.star.basic-script"))
            {
                OUString dialogURL( make_url( url, OUSTR("dialog.xlb") ) );
                if (! create_ucb_content(
                        0, dialogURL, xCmdEnv, false /* no throw */ ))
                    dialogURL = OUString();
                return PackageImpl::create(
                    this, url, mediaType, xCmdEnv,
                    make_url( url, OUSTR("script.xlb") ), dialogURL );
            }
            else if (subType.EqualsIgnoreCaseAscii(
                         "vnd.sun.star.dialog-library"))
            {
                return PackageImpl::create(
                    this, url, mediaType, xCmdEnv,
                    OUString(), make_url( url, OUSTR("dialog.xlb") ) );
            }
        }
    }
    throw lang::IllegalArgumentException(
        m_strUnsupportedMediaType + mediaType,
        static_cast<OWeakObject *>(this),
        static_cast<sal_Int16>(-1) );
}

//##############################################################################

// XPackage
//______________________________________________________________________________
Any PackageImpl::getIcon( sal_Bool highContrast, sal_Bool smallIcon )
    throw (RuntimeException)
{
    OSL_ASSERT( smallIcon );
    if (smallIcon)
    {
        sal_uInt16 ret;
        if (m_scriptURL.getLength() > 0)
            ret = highContrast ? RID_IMG_SCRIPTLIB_HC : RID_IMG_SCRIPTLIB;
        else
            ret = highContrast ? RID_IMG_DIALOGLIB_HC : RID_IMG_DIALOGLIB;
        return makeAny(ret);
    }
    return Package::getIcon( highContrast, smallIcon );
}

// Package
//______________________________________________________________________________
bool PackageImpl::isRegistered_(
    ::osl::ResettableMutexGuard & guard,
    ::rtl::Reference<AbortChannel> const & abortChannel,
    Reference<XCommandEnvironment> const & xCmdEnv )
{
    BackendImpl * that = getMyBackend();
    if (m_scriptURL.getLength() > 0)
    {
        if (that->m_xScriptLibs.is())
            return that->m_xScriptLibs->hasByName( m_name );
        else
            return that->m_basic_script_libs->has( m_name, xCmdEnv );
    }
    else
    {
        if (that->m_xDialogLibs.is())
            return that->m_xDialogLibs->hasByName( m_dialogName );
        else
            return that->m_dialog_libs->has( m_dialogName, xCmdEnv );
    }
}

//______________________________________________________________________________
void PackageImpl::processPackage_(
    ::osl::ResettableMutexGuard & guard,
    bool registerPackage,
    ::rtl::Reference<AbortChannel> const & abortChannel,
    Reference<XCommandEnvironment> const & xCmdEnv )
{
    BackendImpl * that = getMyBackend();
    if (registerPackage)
    {
        if (m_scriptURL.getLength() > 0)
        {
            if (that->m_xScriptLibs.is())
                that->m_xScriptLibs->createLibraryLink(
                    m_name, m_scriptURL, false /* ! read-only */ );
            else
                that->m_basic_script_libs->insert(
                    m_name, m_scriptURL, xCmdEnv );
        }
        if (m_dialogURL.getLength() > 0)
        {
            if (that->m_xDialogLibs.is())
                that->m_xDialogLibs->createLibraryLink(
                    m_dialogName, m_dialogURL, false /* ! read-only */ );
            else
                that->m_dialog_libs->insert(
                    m_dialogName, m_dialogURL, xCmdEnv );
        }
    }
    else // revokePackage()
    {
        try
        {
            if (m_scriptURL.getLength() > 0)
            {
                if (that->m_xScriptLibs.is())
                    that->m_xScriptLibs->removeLibrary( m_name );
                else
                    that->m_basic_script_libs->remove(
                        m_name, m_scriptURL, xCmdEnv );
            }
            if (m_dialogURL.getLength() > 0)
            {
                if (that->m_xDialogLibs.is())
                    that->m_xDialogLibs->removeLibrary( m_dialogName );
                else
                    that->m_dialog_libs->remove(
                        m_dialogName, m_dialogURL, xCmdEnv );
            }
        }
        catch (lang::WrappedTargetException & exc)
        {
            // unwrap WrappedTargetException:
            ::cppu::throwException( exc.TargetException );
        }
    }
}

} // namespace script
} // namespace backend
} // namespace dp_registry

<|endoftext|>