<commit_before>
#include "config.h"

// system
#include <sstream>

// boost
#include <boost/filesystem.hpp>

// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/function/expression.hh>

// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/model/thermalblock.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/finitevolume/dune-pdelab.hh>

#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif

const std::string id = "stationary.linear.elliptic.fv.dp";

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "model = detailed.solvers.stationary.linear.elliptic.model.default" << std::endl;
    file << "[stuff.grid.provider.cube]" << std::endl;
    file << "level = 4" << std::endl;
    file << "filename = " << id << ".grid" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
    file << "diffusion.order = 0"  << std::endl;
    file << "diffusion.variable = x" << std::endl;
    file << "diffusion.expression.0 = 1.0"  << std::endl;
    file << "diffusion.expression.1 = 1.0"  << std::endl;
    file << "diffusion.expression.2 = 1.0"  << std::endl;
    file << "force.order = 0"  << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression.0 = 1.0"  << std::endl;
    file << "force.expression.1 = 1.0"  << std::endl;
    file << "force.expression.2 = 1.0"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression.0 = 0.0"  << std::endl;
    file << "dirichlet.expression.1 = 0.0"  << std::endl;
    file << "dirichlet.expression.2 = 0.0"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.thermalblock]" << std::endl;
    file << "diffusion.order = 0"  << std::endl;
    file << "diffusion.lowerLeft.0 = 0.0"  << std::endl; // should coincide with the grid
    file << "diffusion.lowerLeft.1 = 0.0"  << std::endl; // should coincide with the grid
    file << "diffusion.lowerLeft.2 = 0.0"  << std::endl; // should coincide with the grid
    file << "diffusion.upperRight.0 = 1.0"  << std::endl; // should coincide with the grid
    file << "diffusion.upperRight.1 = 1.0"  << std::endl; // should coincide with the grid
    file << "diffusion.upperRight.2 = 1.0"  << std::endl; // should coincide with the grid
    file << "diffusion.numElements.0 = 2"  << std::endl;
    file << "diffusion.numElements.1 = 2"  << std::endl;
    file << "diffusion.numElements.2 = 2"  << std::endl;
    file << "diffusion.component.0 = 1.0"  << std::endl;
    file << "diffusion.component.1 = 10.0"  << std::endl;
    file << "diffusion.component.2 = 3.0"  << std::endl;
    file << "diffusion.component.3 = 2.1"  << std::endl;
    file << "force.order = 0"  << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression.0 = 1.0"  << std::endl;
    file << "force.expression.1 = 1.0"  << std::endl;
    file << "force.expression.2 = 1.0"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression.0 = 0.0"  << std::endl;
    file << "dirichlet.expression.1 = 0.0"  << std::endl;
    file << "dirichlet.expression.2 = 0.0"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.finitevolume.dune-pdelab]" << std::endl;
    file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
    file << "solve.maxIter = 5000"  << std::endl;
    file << "solve.precision = 1e-12"  << std::endl;
    file << "visualize.filename = " << id << ".solution"  << std::endl;
    file << "visualize.name = solution"  << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange >
Dune::shared_ptr< Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > >
  createModel(const Dune::Stuff::Common::ExtendedParameterTree& paramTree)
{
  // prepare
  paramTree.assertKey(id + ".model");
  const std::string modelId = paramTree.sub(id).get("model", "default_value");
  typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelInterfaceType;
  // choose model
  if (modelId == "detailed.solvers.stationary.linear.elliptic.model.default") {
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id(), id);
    Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
    return model;
  } else if (modelId == "detailed.solvers.stationary.linear.elliptic.model.thermalblock") {
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Thermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id(), id);
    Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
    return model;
  } else {
    std::stringstream msg;
    msg << std::endl << "Error in " << id << ": unknown model ('" << modelId << "') given in the following Dune::Parametertree" << std::endl;
    paramTree.report(msg);
    DUNE_THROW(Dune::InvalidStateException, msg.str());
  } // choose model
} // ... createModel(...)

int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIHelper::instance(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);

    // logger
    Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
                                         Dune::Stuff::Common::LOG_CONSOLE |
                                         Dune::Stuff::Common::LOG_DEBUG);
    Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
    Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();

    // timer
    Dune::Timer timer;

    // grid
    info << "setting up grid: " << std::endl;
    debug.suspend();
    typedef Dune::Stuff::Grid::Provider::UnitCube<> GridProviderType;
    paramTree.assertSub(GridProviderType::id(), id);
    const GridProviderType gridProvider(paramTree.sub(GridProviderType::id()));
    typedef GridProviderType::GridType GridType;
    const GridType& grid = gridProvider.grid();
    typedef GridType::LeafGridView GridViewType;
    const Dune::shared_ptr< const GridViewType > gridView(new GridViewType(grid.leafView()));
    info << "  done (took " << timer.elapsed()
         << " sec, has " << grid.size(0) << " element";
    if (grid.size(0) > 1)
      info << "s";
    info << ")" << std::endl;
    info << "visualizing grid... " << std::flush;
    timer.reset();
    gridProvider.visualize(paramTree.sub(GridProviderType::id()).get("filename", id + "_grid"));
    info << " done (took " << timer.elapsed() << " sek)" << std::endl;
    debug.resume();

    // model
    info << "setting up model... " << std::flush;
    timer.reset();
    const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
    const unsigned int DUNE_UNUSED(dimRange) = 1;
    typedef GridProviderType::CoordinateType::value_type DomainFieldType;
    typedef DomainFieldType RangeFieldType;
    paramTree.assertSub(id, id);
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    const Dune::shared_ptr< const ModelType > model = createModel< DomainFieldType, dimDomain, RangeFieldType, dimRange >(paramTree);
    typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
    const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    // solver
    info << "initializing solver:" << std::endl;
    typedef Dune::Detailed::Solvers
        ::Stationary
        ::Linear
        ::Elliptic
        ::FiniteVolume::DunePdelab< ModelType, GridViewType, BoundaryInfoType, polOrder > SolverType;
    paramTree.assertSub(SolverType::id(), id);
    SolverType solver(model, gridView, boundaryInfo);
    solver.init("  ", debug);

    info << "solving:" << std::endl;
    typedef SolverType::VectorBackendType DofVectorType;
//    Dune::shared_ptr< DofVectorType > solution = solver.createVector();
//    solver.solve(*solution, paramTree.sub(SolverType::id()).sub("solve"), "  ", debug);
    //TODO: adapt function call to former interface
      solver.solve(paramTree.sub(SolverType::id()).sub("solve"), "  ", debug);

    info << "postprocessing:" << std::endl;
    solver.visualize(//*solution,
                     paramTree.sub(SolverType::id()).sub("visualize").get("filename", id + "_solution"),
                     paramTree.sub(SolverType::id()).sub("visualize").get("name", "solution"),
                     "  ",
                     debug);

    // if we came that far we can as well be happy about it
    return 0;
  } catch(Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<commit_msg>[examples...elliptic.finitevolume...] update and cleanup<commit_after>#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

// system
#include <sstream>

// boost
#include <boost/filesystem.hpp>

// dune-common
#include <dune/common/exceptions.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

// dune-stuff
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/function/expression.hh>

// dune-detailed-solvers
#include <dune/detailed/solvers/stationary/linear/elliptic/model/default.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/model/thermalblock.hh>
#include <dune/detailed/solvers/stationary/linear/elliptic/finitevolume/dune-pdelab.hh>

#ifdef POLORDER
const int polOrder = POLORDER;
#else
const int polOrder = 1;
#endif

const std::string id = "stationary.linear.elliptic.fv.dp";

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  // only write param file if there is none
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "model = detailed.solvers.stationary.linear.elliptic.model.default" << std::endl;
    file << "[stuff.grid.provider.cube]" << std::endl;
    file << "lowerLeft = [0.0; 0.0; 0.0]" << std::endl;
    file << "upperRight = [1.0; 1.0; 1.0]" << std::endl;
    file << "numElements = 4" << std::endl;
    file << "filename = " << id << ".grid" << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.default]" << std::endl;
    file << "diffusion.order = 0"  << std::endl;
    file << "diffusion.variable = x" << std::endl;
    file << "diffusion.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "force.order = 0"  << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "neumann.order = 0"  << std::endl;
    file << "neumann.variable = x" << std::endl;
    file << "neumann.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.model.thermalblock]" << std::endl;
    file << "diffusion.order = 0"  << std::endl;
    file << "diffusion.lowerLeft = [0.0; 0.0; 0.0]" << std::endl; // should coincide with the grid
    file << "diffusion.upperRight = [1.0; 1.0; 1.0]" << std::endl; // should coincide with the grid
    file << "diffusion.numElements = [2; 2; 2]"  << std::endl;
    file << "diffusion.components = [1.0; 10.0; 3.0; 2.1]"  << std::endl;
    file << "force.order = 0"  << std::endl;
    file << "force.variable = x" << std::endl;
    file << "force.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "dirichlet.order = 0"  << std::endl;
    file << "dirichlet.variable = x" << std::endl;
    file << "dirichlet.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "neumann.order = 0"  << std::endl;
    file << "neumann.variable = x" << std::endl;
    file << "neumann.expression = [1.0; 1.0; 1.0]"  << std::endl;
    file << "[detailed.solvers.stationary.linear.elliptic.finitevolume.dune-pdelab]" << std::endl;
    file << "solve.type = eigen.bicgstab.incompletelut" << std::endl;
    file << "solve.maxIter = 5000"  << std::endl;
    file << "solve.precision = 1e-12"  << std::endl;
    file << "visualize.filename = " << id << ".solution"  << std::endl;
    file << "visualize.name = solution"  << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange >
Dune::shared_ptr< Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > >
  createModel(const Dune::Stuff::Common::ExtendedParameterTree& paramTree)
{
  // prepare
  paramTree.assertKey(id + ".model");
  const std::string modelId = paramTree.sub(id).get("model", "default_value");
  typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelInterfaceType;
  // choose model
  if (modelId == "detailed.solvers.stationary.linear.elliptic.model.default") {
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id(), id);
    Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
    return model;
  } else if (modelId == "detailed.solvers.stationary.linear.elliptic.model.thermalblock") {
    typedef Dune::Detailed::Solvers::Stationary::Linear::Elliptic::Model::Thermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    paramTree.assertSub(ModelType::id(), id);
    Dune::shared_ptr< ModelInterfaceType > model(new ModelType(paramTree.sub(ModelType::id())));
    return model;
  } else {
    std::stringstream msg;
    msg << std::endl << "Error in " << id << ": unknown model ('" << modelId << "') given in the following Dune::Parametertree" << std::endl;
    paramTree.report(msg);
    DUNE_THROW(Dune::InvalidStateException, msg.str());
  } // choose model
} // ... createModel(...)

int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIHelper::instance(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);

    // logger
    Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
                                         Dune::Stuff::Common::LOG_CONSOLE |
                                         Dune::Stuff::Common::LOG_DEBUG);
    Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();
    Dune::Stuff::Common::LogStream& debug = Dune::Stuff::Common::Logger().debug();

    // timer
    Dune::Timer timer;

    // grid
    info << "setting up grid: " << std::endl;
    debug.suspend();
    typedef Dune::Stuff::Grid::Provider::Cube<> GridProviderType;
    paramTree.assertSub(GridProviderType::id(), id);
    const GridProviderType gridProvider(paramTree.sub(GridProviderType::id()));
    typedef GridProviderType::GridType GridType;
    const GridType& grid = gridProvider.grid();
    typedef GridType::LeafGridView GridViewType;
    const Dune::shared_ptr< const GridViewType > gridView(new GridViewType(grid.leafView()));
    info << "  done (took " << timer.elapsed()
         << " sec, has " << grid.size(0) << " element";
    if (grid.size(0) > 1)
      info << "s";
    info << ")" << std::endl;
    info << "visualizing grid... " << std::flush;
    timer.reset();
    gridProvider.visualize(paramTree.sub(GridProviderType::id()).get("filename", id + "_grid"));
    info << " done (took " << timer.elapsed() << " sek)" << std::endl;
    debug.resume();

    // model
    info << "setting up model... " << std::flush;
    timer.reset();
    const unsigned int DUNE_UNUSED(dimDomain) = GridProviderType::dim;
    const unsigned int DUNE_UNUSED(dimRange) = 1;
    typedef GridProviderType::CoordinateType::value_type DomainFieldType;
    typedef DomainFieldType RangeFieldType;
    paramTree.assertSub(id, id);
    typedef Dune::Detailed::Solvers
        ::Stationary
        ::Linear
        ::Elliptic
        ::Model::Interface<  DomainFieldType, dimDomain, RangeFieldType, dimRange > ModelType;
    const Dune::shared_ptr< const ModelType >
        model = createModel< DomainFieldType, dimDomain, RangeFieldType, dimRange >(paramTree);
    typedef Dune::Stuff::Grid::BoundaryInfo::AllDirichlet BoundaryInfoType;
    const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo(new BoundaryInfoType());
    info << "done (took " << timer.elapsed() << " sec)" << std::endl;

    // solver
    info << "initializing solver:" << std::endl;
    typedef Dune::Detailed::Solvers
        ::Stationary
        ::Linear
        ::Elliptic
        ::FiniteVolume::DunePdelab< ModelType, GridViewType, BoundaryInfoType, polOrder > SolverType;
    paramTree.assertSub(SolverType::id(), id);
    SolverType solver(model, gridView, boundaryInfo);
    solver.init("  ", debug);

    info << "solving:" << std::endl;
    typedef SolverType::VectorBackendType DofVectorType;
//    Dune::shared_ptr< DofVectorType > solution = solver.createVector();
//    solver.solve(*solution, paramTree.sub(SolverType::id()).sub("solve"), "  ", debug);
    //TODO: adapt function call to former interface
      solver.solve(paramTree.sub(SolverType::id()).sub("solve"), "  ", debug);

    info << "postprocessing:" << std::endl;
    solver.visualize(//*solution,
                     paramTree.sub(SolverType::id()).sub("visualize").get("filename", id + "_solution"),
                     paramTree.sub(SolverType::id()).sub("visualize").get("name", "solution"),
                     "  ",
                     debug);

    // if we came that far we can as well be happy about it
    return 0;
  } catch (Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch ( ... ) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: baslibnode.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:22:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SCRIPTING_BASLIBNODE_HXX
#define SCRIPTING_BASLIBNODE_HXX

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XLIBRARYCONTAINER_HPP_
#include <com/sun/star/script/XLibraryContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_BROWSE_XBROWSENODE_HPP_
#include <com/sun/star/script/browse/XBrowseNode.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

class BasicManager;

//.........................................................................
namespace basprov
{
//.........................................................................

    //  ----------------------------------------------------
    //  class BasicLibraryNodeImpl
    //  ----------------------------------------------------

    typedef ::cppu::WeakImplHelper1<
        ::com::sun::star::script::browse::XBrowseNode > BasicLibraryNodeImpl_BASE;

    class BasicLibraryNodeImpl : public BasicLibraryNodeImpl_BASE
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >    m_xContext;
     ::rtl::OUString  m_sScriptingContext;
        BasicManager* m_pBasicManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer > m_xLibContainer;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xLibrary;
        ::rtl::OUString m_sLibName;
        bool m_bIsAppScript;

    public:
        BasicLibraryNodeImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext,
        const ::rtl::OUString& sScriptingContext,
            BasicManager* pBasicManager,
            const ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >& xLibContainer,
            const ::rtl::OUString& sLibName, bool isAppScript=true );
        virtual ~BasicLibraryNodeImpl();

        // XBrowseNode
        virtual ::rtl::OUString SAL_CALL getName(  )
            throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > > SAL_CALL getChildNodes(  )
            throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL hasChildNodes(  )
            throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Int16 SAL_CALL getType(  )
            throw (::com::sun::star::uno::RuntimeException);
    };

//.........................................................................
}   // namespace basprov
//.........................................................................

#endif // SCRIPTING_BASLIBNODE_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.7.108); FILE MERGED 2008/04/01 15:31:46 thb 1.7.108.3: #i85898# Stripping all external header guards 2008/04/01 12:37:19 thb 1.7.108.2: #i85898# Stripping all external header guards 2008/03/31 13:35:59 rt 1.7.108.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: baslibnode.hxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SCRIPTING_BASLIBNODE_HXX
#define SCRIPTING_BASLIBNODE_HXX

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/script/XLibraryContainer.hpp>
#include <com/sun/star/script/browse/XBrowseNode.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <cppuhelper/implbase1.hxx>

class BasicManager;

//.........................................................................
namespace basprov
{
//.........................................................................

    //  ----------------------------------------------------
    //  class BasicLibraryNodeImpl
    //  ----------------------------------------------------

    typedef ::cppu::WeakImplHelper1<
        ::com::sun::star::script::browse::XBrowseNode > BasicLibraryNodeImpl_BASE;

    class BasicLibraryNodeImpl : public BasicLibraryNodeImpl_BASE
    {
    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >    m_xContext;
     ::rtl::OUString  m_sScriptingContext;
        BasicManager* m_pBasicManager;
        ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer > m_xLibContainer;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xLibrary;
        ::rtl::OUString m_sLibName;
        bool m_bIsAppScript;

    public:
        BasicLibraryNodeImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext,
        const ::rtl::OUString& sScriptingContext,
            BasicManager* pBasicManager,
            const ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >& xLibContainer,
            const ::rtl::OUString& sLibName, bool isAppScript=true );
        virtual ~BasicLibraryNodeImpl();

        // XBrowseNode
        virtual ::rtl::OUString SAL_CALL getName(  )
            throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > > SAL_CALL getChildNodes(  )
            throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL hasChildNodes(  )
            throw (::com::sun::star::uno::RuntimeException);
        virtual sal_Int16 SAL_CALL getType(  )
            throw (::com::sun::star::uno::RuntimeException);
    };

//.........................................................................
}   // namespace basprov
//.........................................................................

#endif // SCRIPTING_BASLIBNODE_HXX
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2014 Yorik van Havre <yorik@uncreated.net>              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#include "Base/Reader.h"
#include "Mod/Path/App/Tool.h"
#include "Mod/Path/App/Tooltable.h"

// inclusion of the generated files (generated out of ToolPy.xml and TooltablePy.xml)
#include "ToolPy.h"
#include "TooltablePy.h"
#include "TooltablePy.cpp"

using namespace Path;

#if PY_MAJOR_VERSION >= 3
#  define PYSTRING_FROMSTRING(str)  PyUnicode_FromString(str)
#  define PYINT_TYPE                PyLong_Type
#  define PYINT_FROMLONG(l)         PyLong_FromLong(l)
#  define PYINT_ASLONG(o)           PyLong_AsLong(o)
#else
#  define PYSTRING_FROMSTRING(str)  PyString_FromString(str)
#  define PYINT_TYPE                PyInt_Type
#  define PYINT_FROMLONG(l)         PyInt_FromLong(l)
#  define PYINT_ASLONG(o)           PyInt_AsLong(o)
#endif

// returns a string which represents the object e.g. when printed in python
std::string TooltablePy::representation(void) const
{
    std::stringstream str;
    str.precision(5);
    str << "Tooltable containing ";
    str << getTooltablePtr()->getSize() << " tools";
    return str.str();
}

PyObject *TooltablePy::PyMake(struct _typeobject *, PyObject *, PyObject *)  // Python wrapper
{
    return new TooltablePy(new Tooltable);
}

// constructor method
int TooltablePy::PyInit(PyObject* args, PyObject* /*kwd*/)
{
    //char *name="Tooltable";
    //int version = 1;

    if (PyArg_ParseTuple(args, "")) {
        return 0;
    }
    PyErr_Clear(); // set by PyArg_ParseTuple()

    PyObject *pcObj;
    if (PyArg_ParseTuple(args, "O!", &(PyDict_Type), &pcObj)) {
        try {
            Py::Dict dict(pcObj);
            setTools(dict);
        } catch(...) {
            PyErr_SetString(PyExc_TypeError, "The dictionary can only contain int:tool pairs");
            return -1;
        }
        return 0;
    }
    PyErr_Clear(); // set by PyArg_ParseTuple()

    if (PyArg_ParseTuple(args, "O!", &(PyList_Type), &pcObj)) {
        Py::List list(pcObj);
        for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
            if (PyObject_TypeCheck((*it).ptr(), &(Path::ToolPy::Type))) {
                Path::Tool &tool = *static_cast<Path::ToolPy*>((*it).ptr())->getToolPtr();
                getTooltablePtr()->addTool(tool);
            }
        }
        return 0;
    }

    PyErr_SetString(PyExc_TypeError, "Argument must be either empty or a list or a dictionary");
    return -1;
}

// Commands get/set

Py::Dict TooltablePy::getTools(void) const
{
    Py::Dict dict;
    for(std::map<int,Path::Tool*>::iterator i = getTooltablePtr()->Tools.begin(); i != getTooltablePtr()->Tools.end(); ++i) {
        PyObject *tool = new Path::ToolPy(i->second);
        dict.setItem(Py::Long(i->first), Py::asObject(tool));
    }
    return dict;
}

void TooltablePy::setTools(Py::Dict arg)
{
    getTooltablePtr()->Tools.clear();
    PyObject* dict_copy = PyDict_Copy(arg.ptr());
    PyObject *key, *value;
    Py_ssize_t pos = 0;
    while (PyDict_Next(dict_copy, &pos, &key, &value)) {
        if ( PyObject_TypeCheck(key,&(PYINT_TYPE)) && ((PyObject_TypeCheck(value, &(Path::ToolPy::Type))) || PyObject_TypeCheck(value, &PyDict_Type))) {
            int ckey = (int)PYINT_ASLONG(key);
            if (PyObject_TypeCheck(value, &(Path::ToolPy::Type))) {
              Path::Tool &tool = *static_cast<Path::ToolPy*>(value)->getToolPtr();
              getTooltablePtr()->setTool(tool, ckey);
            } else {
              PyErr_Clear();
              Path::Tool *tool = new Path::Tool;
              // The 'pyTool' object must be created on the heap otherwise Python
              // will fail to properly track the reference counts and aborts
              // in debug mode.
              Path::ToolPy* pyTool = new Path::ToolPy(tool);
              PyObject* success = pyTool->setFromTemplate(value);
              if (!success) {
                Py_DECREF(pyTool);
                throw Py::Exception();
              }
              getTooltablePtr()->setTool(*tool, ckey);
              Py_DECREF(pyTool);
              Py_DECREF(success);
            }
        } else {
            throw Py::TypeError("The dictionary can only contain int:tool pairs");
        }
    }
}

// specific methods

PyObject* TooltablePy::copy(PyObject * args)
{
    if (PyArg_ParseTuple(args, "")) {
        return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
    }
    throw Py::TypeError("This method accepts no argument");
}

PyObject* TooltablePy::addTools(PyObject * args)
{
    PyObject* o;
    if (PyArg_ParseTuple(args, "O!", &(Path::ToolPy::Type), &o)) {
        Path::Tool &tool = *static_cast<Path::ToolPy*>(o)->getToolPtr();
        getTooltablePtr()->addTool(tool);
        //return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
        Py_INCREF(Py_None);
        return Py_None;
    }
    PyErr_Clear();
    if (PyArg_ParseTuple(args, "O!", &(PyList_Type), &o)) {
        Py::List list(o);
        for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
            if (PyObject_TypeCheck((*it).ptr(), &(Path::ToolPy::Type))) {
                Path::Tool &tool = *static_cast<Path::ToolPy*>((*it).ptr())->getToolPtr();
                getTooltablePtr()->addTool(tool);
            }
        }
        //return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
        Py_INCREF(Py_None);
        return Py_None;
    }
    Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - tool or list of tools expected");
}

PyObject* TooltablePy::setTool(PyObject * args)
{
    PyObject* o;
    int pos = -1;
    if (PyArg_ParseTuple(args, "iO!", &pos, &(Path::ToolPy::Type), &o)) {
        Path::Tool &tool = *static_cast<Path::ToolPy*>(o)->getToolPtr();
        getTooltablePtr()->setTool(tool,pos);
        //return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
        Py_INCREF(Py_None);
        return Py_None;
    }
    Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected tool and optional integer");
}

PyObject* TooltablePy::getTool(PyObject * args)
{
    int pos = -1;
    if (PyArg_ParseTuple(args, "i", &pos)) {
        if (getTooltablePtr()->hasTool(pos))
        {
            Path::Tool tool = getTooltablePtr()->getTool(pos);
            return new ToolPy(new Path::Tool(tool));
        }
        else
        {
            Py_INCREF(Py_None);
            return Py_None;
        }
    }
    Py_Error(Base::BaseExceptionFreeCADError, "Argument must be integer");
}

PyObject* TooltablePy::deleteTool(PyObject * args)
{
    int pos = -1;
    if (PyArg_ParseTuple(args, "|i", &pos)) {
        getTooltablePtr()->deleteTool(pos);
        //return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
        Py_INCREF(Py_None);
        return Py_None;
    }
    Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected an integer (optional)");
}

// custom attributes get/set

PyObject *TooltablePy::getCustomAttributes(const char* /*attr*/) const
{
    return 0;
}

int TooltablePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
    return 0;
}

Py::Int TooltablePy::getVersion(void) const
{
    return Py::Int(getTooltablePtr()->Version);
}

void TooltablePy::setVersion(Py::Int version) {
    getTooltablePtr()->Version = version;
}

Py::String TooltablePy::getName(void) const
{
    return Py::String(getTooltablePtr()->Name.c_str());
}

void TooltablePy::setName(Py::String arg)
{
    std::string name = arg.as_std_string();
    getTooltablePtr()->Name = name;
}

PyObject* TooltablePy::setFromTemplate(PyObject * args)
{
    PyObject *dict = 0;
    if (PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict)) {
      Py::Dict d(dict);
      setTools(d);
      Py_Return ;
    }

    PyErr_SetString(PyExc_TypeError, "argument must be a dictionary returned from templateAttrs()");
    return 0;
}

PyObject* TooltablePy::templateAttrs(PyObject * args)
{
    (void)args;
    PyObject *dict = PyDict_New();
    for(std::map<int,Path::Tool*>::iterator i = getTooltablePtr()->Tools.begin(); i != getTooltablePtr()->Tools.end(); ++i) {
        // The 'tool' object must be created on the heap otherwise Python
        // will fail to properly track the reference counts and aborts
        // in debug mode.
        Path::ToolPy* tool = new Path::ToolPy(new Path::Tool(*i->second));
        PyObject *attrs = tool->templateAttrs(0);
        PyDict_SetItem(dict, PYINT_FROMLONG(i->first), attrs);
        Py_DECREF(tool);
    }
    return dict;
}

<commit_msg>Path: [skip ci] fix TooltablePy::getTools to avoid possible double destruction of a Tool instance<commit_after>/***************************************************************************
 *   Copyright (c) 2014 Yorik van Havre <yorik@uncreated.net>              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#include "Base/Reader.h"
#include "Mod/Path/App/Tool.h"
#include "Mod/Path/App/Tooltable.h"

// inclusion of the generated files (generated out of ToolPy.xml and TooltablePy.xml)
#include "ToolPy.h"
#include "TooltablePy.h"
#include "TooltablePy.cpp"

using namespace Path;

#if PY_MAJOR_VERSION >= 3
#  define PYSTRING_FROMSTRING(str)  PyUnicode_FromString(str)
#  define PYINT_TYPE                PyLong_Type
#  define PYINT_FROMLONG(l)         PyLong_FromLong(l)
#  define PYINT_ASLONG(o)           PyLong_AsLong(o)
#else
#  define PYSTRING_FROMSTRING(str)  PyString_FromString(str)
#  define PYINT_TYPE                PyInt_Type
#  define PYINT_FROMLONG(l)         PyInt_FromLong(l)
#  define PYINT_ASLONG(o)           PyInt_AsLong(o)
#endif

// returns a string which represents the object e.g. when printed in python
std::string TooltablePy::representation(void) const
{
    std::stringstream str;
    str.precision(5);
    str << "Tooltable containing ";
    str << getTooltablePtr()->getSize() << " tools";
    return str.str();
}

PyObject *TooltablePy::PyMake(struct _typeobject *, PyObject *, PyObject *)  // Python wrapper
{
    return new TooltablePy(new Tooltable);
}

// constructor method
int TooltablePy::PyInit(PyObject* args, PyObject* /*kwd*/)
{
    //char *name="Tooltable";
    //int version = 1;

    if (PyArg_ParseTuple(args, "")) {
        return 0;
    }
    PyErr_Clear(); // set by PyArg_ParseTuple()

    PyObject *pcObj;
    if (PyArg_ParseTuple(args, "O!", &(PyDict_Type), &pcObj)) {
        try {
            Py::Dict dict(pcObj);
            setTools(dict);
        } catch(...) {
            PyErr_SetString(PyExc_TypeError, "The dictionary can only contain int:tool pairs");
            return -1;
        }
        return 0;
    }
    PyErr_Clear(); // set by PyArg_ParseTuple()

    if (PyArg_ParseTuple(args, "O!", &(PyList_Type), &pcObj)) {
        Py::List list(pcObj);
        for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
            if (PyObject_TypeCheck((*it).ptr(), &(Path::ToolPy::Type))) {
                Path::Tool &tool = *static_cast<Path::ToolPy*>((*it).ptr())->getToolPtr();
                getTooltablePtr()->addTool(tool);
            }
        }
        return 0;
    }

    PyErr_SetString(PyExc_TypeError, "Argument must be either empty or a list or a dictionary");
    return -1;
}

// Commands get/set

Py::Dict TooltablePy::getTools(void) const
{
    Py::Dict dict;
    for(std::map<int,Path::Tool*>::iterator i = getTooltablePtr()->Tools.begin(); i != getTooltablePtr()->Tools.end(); ++i) {
        PyObject *tool = new Path::ToolPy(new Tool(*i->second));
        dict.setItem(Py::Long(i->first), Py::asObject(tool));
    }
    return dict;
}

void TooltablePy::setTools(Py::Dict arg)
{
    getTooltablePtr()->Tools.clear();
    PyObject* dict_copy = PyDict_Copy(arg.ptr());
    PyObject *key, *value;
    Py_ssize_t pos = 0;
    while (PyDict_Next(dict_copy, &pos, &key, &value)) {
        if ( PyObject_TypeCheck(key,&(PYINT_TYPE)) && ((PyObject_TypeCheck(value, &(Path::ToolPy::Type))) || PyObject_TypeCheck(value, &PyDict_Type))) {
            int ckey = (int)PYINT_ASLONG(key);
            if (PyObject_TypeCheck(value, &(Path::ToolPy::Type))) {
              Path::Tool &tool = *static_cast<Path::ToolPy*>(value)->getToolPtr();
              getTooltablePtr()->setTool(tool, ckey);
            } else {
              PyErr_Clear();
              Path::Tool *tool = new Path::Tool;
              // The 'pyTool' object must be created on the heap otherwise Python
              // will fail to properly track the reference counts and aborts
              // in debug mode.
              Path::ToolPy* pyTool = new Path::ToolPy(tool);
              PyObject* success = pyTool->setFromTemplate(value);
              if (!success) {
                Py_DECREF(pyTool);
                throw Py::Exception();
              }
              getTooltablePtr()->setTool(*tool, ckey);
              Py_DECREF(pyTool);
              Py_DECREF(success);
            }
        } else {
            throw Py::TypeError("The dictionary can only contain int:tool pairs");
        }
    }
}

// specific methods

PyObject* TooltablePy::copy(PyObject * args)
{
    if (PyArg_ParseTuple(args, "")) {
        return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
    }
    throw Py::TypeError("This method accepts no argument");
}

PyObject* TooltablePy::addTools(PyObject * args)
{
    PyObject* o;
    if (PyArg_ParseTuple(args, "O!", &(Path::ToolPy::Type), &o)) {
        Path::Tool &tool = *static_cast<Path::ToolPy*>(o)->getToolPtr();
        getTooltablePtr()->addTool(tool);
        //return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
        Py_INCREF(Py_None);
        return Py_None;
    }
    PyErr_Clear();
    if (PyArg_ParseTuple(args, "O!", &(PyList_Type), &o)) {
        Py::List list(o);
        for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
            if (PyObject_TypeCheck((*it).ptr(), &(Path::ToolPy::Type))) {
                Path::Tool &tool = *static_cast<Path::ToolPy*>((*it).ptr())->getToolPtr();
                getTooltablePtr()->addTool(tool);
            }
        }
        //return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
        Py_INCREF(Py_None);
        return Py_None;
    }
    Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - tool or list of tools expected");
}

PyObject* TooltablePy::setTool(PyObject * args)
{
    PyObject* o;
    int pos = -1;
    if (PyArg_ParseTuple(args, "iO!", &pos, &(Path::ToolPy::Type), &o)) {
        Path::Tool &tool = *static_cast<Path::ToolPy*>(o)->getToolPtr();
        getTooltablePtr()->setTool(tool,pos);
        //return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
        Py_INCREF(Py_None);
        return Py_None;
    }
    Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected tool and optional integer");
}

PyObject* TooltablePy::getTool(PyObject * args)
{
    int pos = -1;
    if (PyArg_ParseTuple(args, "i", &pos)) {
        if (getTooltablePtr()->hasTool(pos))
        {
            Path::Tool tool = getTooltablePtr()->getTool(pos);
            return new ToolPy(new Path::Tool(tool));
        }
        else
        {
            Py_INCREF(Py_None);
            return Py_None;
        }
    }
    Py_Error(Base::BaseExceptionFreeCADError, "Argument must be integer");
}

PyObject* TooltablePy::deleteTool(PyObject * args)
{
    int pos = -1;
    if (PyArg_ParseTuple(args, "|i", &pos)) {
        getTooltablePtr()->deleteTool(pos);
        //return new TooltablePy(new Path::Tooltable(*getTooltablePtr()));
        Py_INCREF(Py_None);
        return Py_None;
    }
    Py_Error(Base::BaseExceptionFreeCADError, "Wrong parameters - expected an integer (optional)");
}

// custom attributes get/set

PyObject *TooltablePy::getCustomAttributes(const char* /*attr*/) const
{
    return 0;
}

int TooltablePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
    return 0;
}

Py::Int TooltablePy::getVersion(void) const
{
    return Py::Int(getTooltablePtr()->Version);
}

void TooltablePy::setVersion(Py::Int version) {
    getTooltablePtr()->Version = version;
}

Py::String TooltablePy::getName(void) const
{
    return Py::String(getTooltablePtr()->Name.c_str());
}

void TooltablePy::setName(Py::String arg)
{
    std::string name = arg.as_std_string();
    getTooltablePtr()->Name = name;
}

PyObject* TooltablePy::setFromTemplate(PyObject * args)
{
    PyObject *dict = 0;
    if (PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict)) {
      Py::Dict d(dict);
      setTools(d);
      Py_Return ;
    }

    PyErr_SetString(PyExc_TypeError, "argument must be a dictionary returned from templateAttrs()");
    return 0;
}

PyObject* TooltablePy::templateAttrs(PyObject * args)
{
    (void)args;
    PyObject *dict = PyDict_New();
    for(std::map<int,Path::Tool*>::iterator i = getTooltablePtr()->Tools.begin(); i != getTooltablePtr()->Tools.end(); ++i) {
        // The 'tool' object must be created on the heap otherwise Python
        // will fail to properly track the reference counts and aborts
        // in debug mode.
        Path::ToolPy* tool = new Path::ToolPy(new Path::Tool(*i->second));
        PyObject *attrs = tool->templateAttrs(0);
        PyDict_SetItem(dict, PYINT_FROMLONG(i->first), attrs);
        Py_DECREF(tool);
    }
    return dict;
}

<|endoftext|>


<commit_before>/*
	Copyright (c) 2014, Madd Games.
	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.

	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 HOLDER 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.
*/

#include <Apoc/Math/Vector.h>

Vector::Vector()
{
	coords[0] = 0.0;
	coords[1] = 0.0;
	coords[2] = 0.0;
	coords[3] = 1.0;
};

Vector::Vector(float x, float y)
{
	coords[0] = x;
	coords[1] = y;
	coords[2] = 0.0;
	coords[3] = 1.0;
};

Vector::Vector(float x, float y, float z)
{
	coords[0] = x;
	coords[1] = y;
	coords[2] = z;
	coords[3] = 1.0;
};

Vector::Vector(float x, float y, float z, float w)
{
	coords[0] = x;
	coords[1] = y;
	coords[2] = z;
	coords[3] = w;
};

Vector::Vector(const Vector &vec)
{
	int i;
	for (i=0; i<4; i++)
	{
		coords[i] = vec.coords[i];
	};
};

float& Vector::x()
{
	return coords[0];
};

float& Vector::y()
{
	return coords[1];
};

float& Vector::z()
{
	return coords[2];
};

float& Vector::w()
{
	return coords[3];
};

float& Vector::operator[](int i)
{
	return coords[i];
};

Vector& Vector::operator=(Vector vec)
{
	int i;
	for (i=0; i<4; i++)
	{
		coords[i] = vec[i];
	};

	return *this;
};

Vector Vector::operator+(Vector b)
{
	Vector out;

	int i;
	for (i=0; i<4; i++)
	{
		out[i] = coords[i] + b[i];
	};

	return out;
};

Vector Vector::operator-(Vector b)
{
	Vector out;

	int i;
	for (i=0; i<4; i++)
	{
		out[i] = coords[i] - b[i];
	};

	return out;
};

Vector Vector::operator*(Vector b)
{
	Vector out;

	int i;
	for (i=0; i<4; i++)
	{
		out[i] = coords[i] * b[i];
	};

	return out;
};

Vector Vector::operator/(Vector b)
{
	Vector out;

	int i;
	for (i=0; i<4; i++)
	{
		out[i] = coords[i] / b[i];
	};

	return out;
};
<commit_msg>Update Vector.cpp<commit_after>/*
	Copyright (c) 2014, Madd Games.
	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.

	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 HOLDER 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.
*/

#include <Apoc/Math/Vector.h>

Vector::Vector()
{
	coords[0] = 0.0;
	coords[1] = 0.0;
	coords[2] = 0.0;
	coords[3] = 1.0;
};

Vector::Vector(float x, float y)
{
	coords[0] = x;
	coords[1] = y;
	coords[2] = 0.0;
	coords[3] = 1.0;
};

Vector::Vector(float x, float y, float z)
{
	coords[0] = x;
	coords[1] = y;
	coords[2] = z;
	coords[3] = 1.0;
};

Vector::Vector(float x, float y, float z, float w)
{
	coords[0] = x;
	coords[1] = y;
	coords[2] = z;
	coords[3] = w;
};

Vector::Vector(const Vector &vec)
{
	int i;
	for (i=0; i<4; i++)
	{
		coords[i] = vec.coords[i];
	};
};

float& Vector::x()
{
	return coords[0];
};

float& Vector::y()
{
	return coords[1];
};

float& Vector::z()
{
	return coords[2];
};

float& Vector::w()
{
	return coords[3];
};

float& Vector::operator[](int i)
{
	return coords[i];
};

Vector& Vector::operator=(Vector vec)
{
	int i;
	for (i=0; i<4; i++)
	{
		coords[i] = vec[i];
	};

	return *this;
};

Vector Vector::operator+(Vector b)
{
	Vector out;

	int i;
	for (i=0; i<4; i++)
	{
		out[i] = coords[i] + b[i];
	};

	return out;
};

Vector Vector::operator-(Vector b)
{
	Vector out;

	int i;
	for (i=0; i<4; i++)
	{
		out[i] = coords[i] - b[i];
	};

	return out;
};

Vector Vector::operator*(Vector b)
{
	Vector out;

	int i;
	for (i=0; i<4; i++)
	{
		out[i] = coords[i] * b[i];
	};

	return out;
};

Vector Vector::operator/(Vector b)
{
	Vector out;

	int i;
	for (i=0; i<4; i++)
	{
		out[i] = coords[i] / b[i];
	};

	return out;
};

float Vector::dot(Vector b)
{
	float out = 0.0;
	int i;
	for (i=0; i<4; i++)
	{
		out += coords[i] * b[i];
	};

	return out;
};

Vector Vector::cross(Vector b)
{
	Vector out;
	out[0] = coords[0]*b[2] - coords[2]*b[1];		// X
	out[1] = coords[2]*b[0] - coords[0]*b[2];		// Y
	out[2] = coords[0]*b[1] - coords[1]*b[0];		// Z
	out[3] = 1.0;						// W, is this right?
	return out;
};
<|endoftext|>


<commit_before>/***
Copyright (C) 2013 Aniket Deole <aniket.deole@gmail.com>
This program 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 program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranties of
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
***/

#include <iostream>
#include <vector>
#include "notedata.hh"

static std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

NoteData::NoteData (int p_key, std::string t, std::string b,int create_time, int modified_time, std::string g, std::string n_guid,
        std::string n_name) {
    primary_key = p_key;
    title = t;
    body = b;
    create_unix_time = create_time;
    modified_unix_time = modified_time;
    guid = g;
    notebook_guid = n_guid;
    notebookName = n_name;

    /* Create summary to display in the note list pane view. */

	    /* Removing HTML Tags */
    std::string strippedSummary = "";
    std::vector<std::string>    tags;
    std::vector<std::string>    text;

    for(;;)
    {
        std::string::size_type  startpos;

        startpos = b.find('<');
        if(startpos == std::string::npos)
        {
            // no tags left only text!
            text.push_back(b);
            break;
        }

        // handle the text before the tag
        if(0 != startpos)
        {
            text.push_back(b.substr(0, startpos));
            b = b.substr(startpos, b.size() - startpos);
            startpos = 0;
        }

        //  skip all the text in the html tag
        std::string::size_type endpos;
        for(endpos = startpos;
            endpos < b.size() && b[endpos] != '>';
            ++endpos)
        {
            // since '>' can appear inside of an attribute string we need
            // to make sure we process it properly.
            if(b[endpos] == '"')
            {
                endpos++;
                while(endpos < b.size() && b[endpos] != '"')
                {
                    endpos++;
                }
            }
        }

        //  Handle text and end of html that has beginning of tag but not the end
        if(endpos == b.size())
        {
            b = b.substr(endpos, b.size() - endpos);
            break;
        }
        else
        {
            //  handle the entire tag
            endpos++;
            tags.push_back(b.substr(startpos, endpos - startpos));
            b = b.substr(endpos, b.size() - endpos);
        }
    }

    // auto, iterators or range based for loop would probably be better but
    // this makes it a bit easier to read.
    for(size_t i = 0; i < tags.size(); i++)
    {
 //       std::cout << tags[i] << std::endl;
    }

    for(size_t i = 0; i < text.size(); i++)
    {
 //       std::cout << text[i] << std::endl;
        strippedSummary.append (text[i]);
    }

    /* Removing HTML Tags Over */

    /* Change special Characters. */
    strippedSummary = ReplaceString (strippedSummary, " ", " ");
    strippedSummary = ReplaceString (strippedSummary, "\n", " ");
    strippedSummary = ReplaceString (strippedSummary, "&", "&");

    summary = strippedSummary;
}<commit_msg>Note Descriptions in NotelistPaneView are now trimmed.<commit_after>/***
Copyright (C) 2013 Aniket Deole <aniket.deole@gmail.com>
This program 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 program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranties of
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
***/

#include <iostream>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <vector>
#include "notedata.hh"

static std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

// trim from start
static inline std::string &ltrim(std::string &s) {
        s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
        return s;
}

// trim from end
static inline std::string &rtrim(std::string &s) {
        s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
        return s;
}

// trim from both ends
static inline std::string &trim(std::string &s) {
        return ltrim(rtrim(s));
}

NoteData::NoteData (int p_key, std::string t, std::string b,int create_time, int modified_time, std::string g, std::string n_guid,
        std::string n_name) {
    primary_key = p_key;
    title = t;
    body = b;
    create_unix_time = create_time;
    modified_unix_time = modified_time;
    guid = g;
    notebook_guid = n_guid;
    notebookName = n_name;

    /* Create summary to display in the note list pane view. */

	    /* Removing HTML Tags */
    std::string strippedSummary = "";
    std::vector<std::string>    tags;
    std::vector<std::string>    text;

    for(;;)
    {
        std::string::size_type  startpos;

        startpos = b.find('<');
        if(startpos == std::string::npos)
        {
            // no tags left only text!
            text.push_back(b);
            break;
        }

        // handle the text before the tag
        if(0 != startpos)
        {
            text.push_back(b.substr(0, startpos));
            b = b.substr(startpos, b.size() - startpos);
            startpos = 0;
        }

        //  skip all the text in the html tag
        std::string::size_type endpos;
        for(endpos = startpos;
            endpos < b.size() && b[endpos] != '>';
            ++endpos)
        {
            // since '>' can appear inside of an attribute string we need
            // to make sure we process it properly.
            if(b[endpos] == '"')
            {
                endpos++;
                while(endpos < b.size() && b[endpos] != '"')
                {
                    endpos++;
                }
            }
        }

        //  Handle text and end of html that has beginning of tag but not the end
        if(endpos == b.size())
        {
            b = b.substr(endpos, b.size() - endpos);
            break;
        }
        else
        {
            //  handle the entire tag
            endpos++;
            tags.push_back(b.substr(startpos, endpos - startpos));
            b = b.substr(endpos, b.size() - endpos);
        }
    }

    // auto, iterators or range based for loop would probably be better but
    // this makes it a bit easier to read.
    for(size_t i = 0; i < tags.size(); i++)
    {
 //       std::cout << tags[i] << std::endl;
    }

    for(size_t i = 0; i < text.size(); i++)
    {
 //       std::cout << text[i] << std::endl;
        strippedSummary.append (text[i]);
    }

    /* Removing HTML Tags Over */

    /* Change special Characters. */
    strippedSummary = ReplaceString (strippedSummary, " ", " ");
    strippedSummary = ReplaceString (strippedSummary, "\n", " ");
    strippedSummary = ReplaceString (strippedSummary, "&", "&");

    summary = trim (strippedSummary);
}<|endoftext|>


<commit_before>#include <map>
#include "callbacks.h"
std::map<WinCallback*, WrappedCallback*> callbackHolder;

WrappedCallback::WrappedCallback(WinCallback *wc)
{
  TRACE("((WrappedCallback*)%p = wrapped[(WinCallback)%p])\n", this, wc);
  internal = wc;
  m_nCallbackFlags = wc->m_nCallbackFlags;
  m_iCallback = wc->m_iCallback;
}

#define ARGSBACK this->internal->m_nCallbackFlags = this->m_nCallbackFlags; this->internal->m_iCallback = this->m_iCallback;

void WrappedCallback::Run(void *pvParams)
{
  TRACE("((WrappedCallback*)%p, (void*)%p)\n", this, pvParams);
  ARGSBACK;
  this->internal->Run(pvParams);
}
void WrappedCallback::Run(void *pvParams, bool onIOFailure, SteamAPICall_t hSteamAPICall)
{
  TRACE("((WrappedCallback*)%p, (void*)%p), (bool)%d, (SteamAPICall_t)%p\n", this, pvParams, onIOFailure, hSteamAPICall);
  ARGSBACK;
  this->internal->Run(pvParams, onIOFailure, hSteamAPICall);
}
int WrappedCallback::GetCallbackSizeBytes()
{
  TRACE("((WrappedCallback)%p)\n", this);
  auto result = this->internal->GetCallbackSizeBytes();
  TRACE("() = %d\n", result);
  return result;
}
WrappedCallback *wrap(WinCallback *p)
{
  WrappedCallback *result= callbackHolder[p];
  if (result == NULL)
  {
    result = new WrappedCallback(p);
    callbackHolder[p] = result;
  }
  TRACE("Wrapper for (WinCallback*)%p is (WrappedCallback*)%p\n", p, result);
  return result;
}
#ifdef __cplusplus
extern "C" {
#endif
void SteamAPI_RegisterCallback_(class WinCallback * pCallback, int iCallback)
{
  TRACE("((class WinCallback *)%p, (int)%d)\n", pCallback, iCallback);
  WrappedCallback* cw = wrap(pCallback);
  SteamAPI_RegisterCallback(cw, iCallback);
}
void SteamAPI_UnregisterCallback_(class WinCallback * pCallback)
{
  TRACE("((class WinCallback *)%p)\n", pCallback);
  WrappedCallback* cw = wrap(pCallback);
  SteamAPI_UnregisterCallback(cw);
  callbackHolder.erase(pCallback);
  delete cw;
}
void SteamAPI_RegisterCallResult_(class WinCallback * pCallback, SteamAPICall_t hAPICall)
{
  TRACE("((class WinCallback *)%p, (SteamAPICall_t)%p)\n", pCallback, hAPICall);
  WrappedCallback* cw = wrap(pCallback);
  SteamAPI_RegisterCallResult(cw, hAPICall);
}
void SteamAPI_UnregisterCallResult_(class WinCallback * pCallback, SteamAPICall_t hAPICall)
{
  TRACE("((class WinCallback *)%p, (SteamAPICall_t)%p)\n", pCallback, hAPICall);
  WrappedCallback* cw = wrap(pCallback);
  SteamAPI_UnregisterCallResult(cw, hAPICall);
  callbackHolder.erase(pCallback);
  delete cw;
}
#ifdef __cplusplus
}
#endif
<commit_msg>Last missed fix for #6<commit_after>#include <map>
#include "callbacks.h"
std::map<WinCallback*, WrappedCallback*> callbackHolder;

WrappedCallback::WrappedCallback(WinCallback *wc)
{
  TRACE("((WrappedCallback*)%p = wrapped[(WinCallback)%p])\n", this, wc);
  internal = wc;
  m_nCallbackFlags = wc->m_nCallbackFlags;
  m_iCallback = wc->m_iCallback;
}

#define ARGSBACK this->internal->m_nCallbackFlags = this->m_nCallbackFlags; this->internal->m_iCallback = this->m_iCallback;

void WrappedCallback::Run(void *pvParams)
{
  TRACE("((WrappedCallback*)%p, (void*)%p)\n", this, pvParams);
  ARGSBACK;
  this->internal->Run(pvParams);
}
void WrappedCallback::Run(void *pvParams, bool onIOFailure, SteamAPICall_t hSteamAPICall)
{
  TRACE("((WrappedCallback*)%p, (void*)%p), (bool)%d, (SteamAPICall_t)%p\n", this, pvParams, onIOFailure, hSteamAPICall);
  ARGSBACK;
  this->internal->Run(pvParams, onIOFailure, hSteamAPICall);
}
int WrappedCallback::GetCallbackSizeBytes()
{
  TRACE("((WrappedCallback)%p)\n", this);
  int result = this->internal->GetCallbackSizeBytes();
  TRACE("() = %d\n", result);
  return result;
}
WrappedCallback *wrap(WinCallback *p)
{
  WrappedCallback *result= callbackHolder[p];
  if (result == NULL)
  {
    result = new WrappedCallback(p);
    callbackHolder[p] = result;
  }
  TRACE("Wrapper for (WinCallback*)%p is (WrappedCallback*)%p\n", p, result);
  return result;
}
#ifdef __cplusplus
extern "C" {
#endif
void SteamAPI_RegisterCallback_(class WinCallback * pCallback, int iCallback)
{
  TRACE("((class WinCallback *)%p, (int)%d)\n", pCallback, iCallback);
  WrappedCallback* cw = wrap(pCallback);
  SteamAPI_RegisterCallback(cw, iCallback);
}
void SteamAPI_UnregisterCallback_(class WinCallback * pCallback)
{
  TRACE("((class WinCallback *)%p)\n", pCallback);
  WrappedCallback* cw = wrap(pCallback);
  SteamAPI_UnregisterCallback(cw);
  callbackHolder.erase(pCallback);
  delete cw;
}
void SteamAPI_RegisterCallResult_(class WinCallback * pCallback, SteamAPICall_t hAPICall)
{
  TRACE("((class WinCallback *)%p, (SteamAPICall_t)%p)\n", pCallback, hAPICall);
  WrappedCallback* cw = wrap(pCallback);
  SteamAPI_RegisterCallResult(cw, hAPICall);
}
void SteamAPI_UnregisterCallResult_(class WinCallback * pCallback, SteamAPICall_t hAPICall)
{
  TRACE("((class WinCallback *)%p, (SteamAPICall_t)%p)\n", pCallback, hAPICall);
  WrappedCallback* cw = wrap(pCallback);
  SteamAPI_UnregisterCallResult(cw, hAPICall);
  callbackHolder.erase(pCallback);
  delete cw;
}
#ifdef __cplusplus
}
#endif
<|endoftext|>


<commit_before>/* This file is part of the KDE libraries
   Copyright (C) 2001-2003 Christoph Cullmann <cullmann@kde.org>

   Based on KHTML Factory from Simon Hausmann <hausmann@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 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
   Library General Public License for more details.

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

// $Id$

#include "katefactory.h"
#include "katefactory.moc"

#include "katedocument.h"
#include "kateview.h"
#include "katerenderer.h"
#include "katecmds.h"
#include "katecorecommands.h"
#include "katefiletype.h"
#include "kateschema.h"

#include "../interfaces/katecmd.h"

#include <klocale.h>
#include <kdirwatch.h>
#include <kstaticdeleter.h>

/**
 * dummy wrapper factory to be sure nobody external deletes our katefactory
 */
class KateFactoryPublic : public KParts::Factory
{
  public:
    KateFactoryPublic ()
    {
    }

    ~KateFactoryPublic ()
    {
    }

    KParts::Part *createPartObject ( QWidget *parentWidget, const char *widgetName, QObject *parent, const char *name, const char *classname, const QStringList &args )
    {
      return KateFactory::self()->createPartObject (parentWidget, widgetName, parent, name, classname, args);
    }
};

extern "C"
{
  void *init_libkatepart()
  {
    return new KateFactoryPublic ();
  }
}

KateFactory *KateFactory::s_self = 0;

KateFactory::KateFactory ()
 : m_aboutData ("katepart", I18N_NOOP("Kate Part"), "2.2",
             I18N_NOOP( "Embeddable editor component" ), KAboutData::License_LGPL_V2,
             I18N_NOOP( "(c) 2000-2003 The Kate Authors" ), 0, "http://kate.kde.org")
 , m_instance (&m_aboutData)
{
  //
  // fill about data
  //
  m_aboutData.addAuthor ("Christoph Cullmann", I18N_NOOP("Maintainer"), "cullmann@kde.org", "http://www.babylon2k.de");
  m_aboutData.addAuthor ("Anders Lund", I18N_NOOP("Core Developer"), "anders@alweb.dk", "http://www.alweb.dk");
  m_aboutData.addAuthor ("Joseph Wenninger", I18N_NOOP("Core Developer"), "jowenn@kde.org","http://stud3.tuwien.ac.at/~e9925371");
  m_aboutData.addAuthor ("Hamish Rodda",I18N_NOOP("Core Developer"), "rodda@kde.org");
  m_aboutData.addAuthor ("Waldo Bastian", I18N_NOOP( "The cool buffersystem" ), "bastian@kde.org" );
  m_aboutData.addAuthor ("Charles Samuels", I18N_NOOP("The Editing Commands"), "charles@kde.org");
  m_aboutData.addAuthor ("Matt Newell", I18N_NOOP("Testing, ..."), "newellm@proaxis.com");
  m_aboutData.addAuthor ("Michael Bartl", I18N_NOOP("Former Core Developer"), "michael.bartl1@chello.at");
  m_aboutData.addAuthor ("Michael McCallum", I18N_NOOP("Core Developer"), "gholam@xtra.co.nz");
  m_aboutData.addAuthor ("Jochen Wilhemly", I18N_NOOP( "KWrite Author" ), "digisnap@cs.tu-berlin.de" );
  m_aboutData.addAuthor ("Michael Koch",I18N_NOOP("KWrite port to KParts"), "koch@kde.org");
  m_aboutData.addAuthor ("Christian Gebauer", 0, "gebauer@kde.org" );
  m_aboutData.addAuthor ("Simon Hausmann", 0, "hausmann@kde.org" );
  m_aboutData.addAuthor ("Glen Parker",I18N_NOOP("KWrite Undo History, Kspell integration"), "glenebob@nwlink.com");
  m_aboutData.addAuthor ("Scott Manson",I18N_NOOP("KWrite XML Syntax highlighting support"), "sdmanson@alltel.net");
  m_aboutData.addAuthor ("John Firebaugh",I18N_NOOP("Patches and more"), "jfirebaugh@kde.org");

  m_aboutData.addCredit ("Matteo Merli",I18N_NOOP("Highlighting for RPM Spec-Files, Perl, Diff and more"), "merlim@libero.it");
  m_aboutData.addCredit ("Rocky Scaletta",I18N_NOOP("Highlighting for VHDL"), "rocky@purdue.edu");
  m_aboutData.addCredit ("Yury Lebedev",I18N_NOOP("Highlighting for SQL"),"");
  m_aboutData.addCredit ("Chris Ross",I18N_NOOP("Highlighting for Ferite"),"");
  m_aboutData.addCredit ("Nick Roux",I18N_NOOP("Highlighting for ILERPG"),"");
  m_aboutData.addCredit ("Carsten Niehaus", I18N_NOOP("Highlighting for LaTeX"),"");
  m_aboutData.addCredit ("Per Wigren", I18N_NOOP("Highlighting for Makefiles, Python"),"");
  m_aboutData.addCredit ("Jan Fritz", I18N_NOOP("Highlighting for Python"),"");
  m_aboutData.addCredit ("Daniel Naber","","");
  m_aboutData.addCredit ("Roland Pabel",I18N_NOOP("Highlighting for Scheme"),"");
  m_aboutData.addCredit ("Cristi Dumitrescu",I18N_NOOP("PHP Keyword/Datatype list"),"");
  m_aboutData.addCredit ("Carsten Presser", I18N_NOOP("Betatest"), "mord-slime@gmx.de");
  m_aboutData.addCredit ("Jens Haupert", I18N_NOOP("Betatest"), "al_all@gmx.de");
  m_aboutData.addCredit ("Carsten Pfeiffer", I18N_NOOP("Very nice help"), "");
  m_aboutData.addCredit (I18N_NOOP("All people who have contributed and I have forgotten to mention"),"","");

  m_aboutData.setTranslator(I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails"));

  //
  // plugins
  //
  m_plugins = KTrader::self()->query("KTextEditor/Plugin");

  //
  // dir watch
  //
  m_dirWatch = new KDirWatch (this);

  //
  // filetype man
  //
  m_fileTypeManager = new KateFileTypeManager ();

  //
  // schema man
  //
  m_schemaManager = new KateSchemaManager ();

  //
  // init the cmds
  //
  KateCmd::self()->registerCommand (new KateCommands::SedReplace ());
  KateCmd::self()->registerCommand (new KateCommands::Character ());
  KateCmd::self()->registerCommand (new KateCommands::Goto ());
  KateCmd::self()->registerCommand (new KateCommands::Date ());
  KateCmd::self()->registerCommand (new KateCoreCommands());
}

KateFactory::~KateFactory()
{
  delete m_fileTypeManager;
  delete m_schemaManager;
}

static KStaticDeleter<KateFactory> sdFactory;

KateFactory *KateFactory::self ()
{
  if (!s_self)
    sdFactory.setObject(s_self, new KateFactory ());

  return s_self;
}

KParts::Part *KateFactory::createPartObject ( QWidget *parentWidget, const char *widgetName, QObject *parent, const char *name, const char *classname, const QStringList & )
{
  bool bWantSingleView = !( classname == QString("KTextEditor::Document") );
  bool bWantBrowserView = ( classname == QString("Browser/View") );
  bool bWantReadOnly = (bWantBrowserView || ( classname == QString("KParts::ReadOnlyPart") ));

  KParts::ReadWritePart *part = new KateDocument (bWantSingleView, bWantBrowserView, bWantReadOnly, parentWidget, widgetName, parent, name);
  part->setReadWrite( !bWantReadOnly );

  return part;
}

void KateFactory::registerDocument ( KateDocument *doc )
{
  m_documents.append( doc );
}

void KateFactory::deregisterDocument ( KateDocument *doc )
{
  m_documents.removeRef( doc );
}

void KateFactory::registerView ( KateView *view )
{
  m_views.append( view );
}

void KateFactory::deregisterView ( KateView *view )
{
  m_views.removeRef( view );
}

void KateFactory::registerRenderer ( KateRenderer  *renderer )
{
  m_renderers.append( renderer );
}

void KateFactory::deregisterRenderer ( KateRenderer  *renderer )
{
  m_renderers.removeRef( renderer );
}

// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>Fix compile<commit_after>/* This file is part of the KDE libraries
   Copyright (C) 2001-2003 Christoph Cullmann <cullmann@kde.org>

   Based on KHTML Factory from Simon Hausmann <hausmann@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 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
   Library General Public License for more details.

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

// $Id$

#include "katefactory.h"

#include "katedocument.h"
#include "kateview.h"
#include "katerenderer.h"
#include "katecmds.h"
#include "katecorecommands.h"
#include "katefiletype.h"
#include "kateschema.h"

#include "../interfaces/katecmd.h"

#include <klocale.h>
#include <kdirwatch.h>
#include <kstaticdeleter.h>

/**
 * dummy wrapper factory to be sure nobody external deletes our katefactory
 */
class KateFactoryPublic : public KParts::Factory
{
  public:
    KateFactoryPublic ()
    {
    }

    ~KateFactoryPublic ()
    {
    }

    KParts::Part *createPartObject ( QWidget *parentWidget, const char *widgetName, QObject *parent, const char *name, const char *classname, const QStringList &args )
    {
      return KateFactory::self()->createPartObject (parentWidget, widgetName, parent, name, classname, args);
    }
};

extern "C"
{
  void *init_libkatepart()
  {
    return new KateFactoryPublic ();
  }
}

KateFactory *KateFactory::s_self = 0;

KateFactory::KateFactory ()
 : m_aboutData ("katepart", I18N_NOOP("Kate Part"), "2.2",
             I18N_NOOP( "Embeddable editor component" ), KAboutData::License_LGPL_V2,
             I18N_NOOP( "(c) 2000-2003 The Kate Authors" ), 0, "http://kate.kde.org")
 , m_instance (&m_aboutData)
{
  //
  // fill about data
  //
  m_aboutData.addAuthor ("Christoph Cullmann", I18N_NOOP("Maintainer"), "cullmann@kde.org", "http://www.babylon2k.de");
  m_aboutData.addAuthor ("Anders Lund", I18N_NOOP("Core Developer"), "anders@alweb.dk", "http://www.alweb.dk");
  m_aboutData.addAuthor ("Joseph Wenninger", I18N_NOOP("Core Developer"), "jowenn@kde.org","http://stud3.tuwien.ac.at/~e9925371");
  m_aboutData.addAuthor ("Hamish Rodda",I18N_NOOP("Core Developer"), "rodda@kde.org");
  m_aboutData.addAuthor ("Waldo Bastian", I18N_NOOP( "The cool buffersystem" ), "bastian@kde.org" );
  m_aboutData.addAuthor ("Charles Samuels", I18N_NOOP("The Editing Commands"), "charles@kde.org");
  m_aboutData.addAuthor ("Matt Newell", I18N_NOOP("Testing, ..."), "newellm@proaxis.com");
  m_aboutData.addAuthor ("Michael Bartl", I18N_NOOP("Former Core Developer"), "michael.bartl1@chello.at");
  m_aboutData.addAuthor ("Michael McCallum", I18N_NOOP("Core Developer"), "gholam@xtra.co.nz");
  m_aboutData.addAuthor ("Jochen Wilhemly", I18N_NOOP( "KWrite Author" ), "digisnap@cs.tu-berlin.de" );
  m_aboutData.addAuthor ("Michael Koch",I18N_NOOP("KWrite port to KParts"), "koch@kde.org");
  m_aboutData.addAuthor ("Christian Gebauer", 0, "gebauer@kde.org" );
  m_aboutData.addAuthor ("Simon Hausmann", 0, "hausmann@kde.org" );
  m_aboutData.addAuthor ("Glen Parker",I18N_NOOP("KWrite Undo History, Kspell integration"), "glenebob@nwlink.com");
  m_aboutData.addAuthor ("Scott Manson",I18N_NOOP("KWrite XML Syntax highlighting support"), "sdmanson@alltel.net");
  m_aboutData.addAuthor ("John Firebaugh",I18N_NOOP("Patches and more"), "jfirebaugh@kde.org");

  m_aboutData.addCredit ("Matteo Merli",I18N_NOOP("Highlighting for RPM Spec-Files, Perl, Diff and more"), "merlim@libero.it");
  m_aboutData.addCredit ("Rocky Scaletta",I18N_NOOP("Highlighting for VHDL"), "rocky@purdue.edu");
  m_aboutData.addCredit ("Yury Lebedev",I18N_NOOP("Highlighting for SQL"),"");
  m_aboutData.addCredit ("Chris Ross",I18N_NOOP("Highlighting for Ferite"),"");
  m_aboutData.addCredit ("Nick Roux",I18N_NOOP("Highlighting for ILERPG"),"");
  m_aboutData.addCredit ("Carsten Niehaus", I18N_NOOP("Highlighting for LaTeX"),"");
  m_aboutData.addCredit ("Per Wigren", I18N_NOOP("Highlighting for Makefiles, Python"),"");
  m_aboutData.addCredit ("Jan Fritz", I18N_NOOP("Highlighting for Python"),"");
  m_aboutData.addCredit ("Daniel Naber","","");
  m_aboutData.addCredit ("Roland Pabel",I18N_NOOP("Highlighting for Scheme"),"");
  m_aboutData.addCredit ("Cristi Dumitrescu",I18N_NOOP("PHP Keyword/Datatype list"),"");
  m_aboutData.addCredit ("Carsten Presser", I18N_NOOP("Betatest"), "mord-slime@gmx.de");
  m_aboutData.addCredit ("Jens Haupert", I18N_NOOP("Betatest"), "al_all@gmx.de");
  m_aboutData.addCredit ("Carsten Pfeiffer", I18N_NOOP("Very nice help"), "");
  m_aboutData.addCredit (I18N_NOOP("All people who have contributed and I have forgotten to mention"),"","");

  m_aboutData.setTranslator(I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails"));

  //
  // plugins
  //
  m_plugins = KTrader::self()->query("KTextEditor/Plugin");

  //
  // dir watch
  //
  m_dirWatch = new KDirWatch (this);

  //
  // filetype man
  //
  m_fileTypeManager = new KateFileTypeManager ();

  //
  // schema man
  //
  m_schemaManager = new KateSchemaManager ();

  //
  // init the cmds
  //
  KateCmd::self()->registerCommand (new KateCommands::SedReplace ());
  KateCmd::self()->registerCommand (new KateCommands::Character ());
  KateCmd::self()->registerCommand (new KateCommands::Goto ());
  KateCmd::self()->registerCommand (new KateCommands::Date ());
  KateCmd::self()->registerCommand (new KateCoreCommands());
}

KateFactory::~KateFactory()
{
  delete m_fileTypeManager;
  delete m_schemaManager;
}

static KStaticDeleter<KateFactory> sdFactory;

KateFactory *KateFactory::self ()
{
  if (!s_self)
    sdFactory.setObject(s_self, new KateFactory ());

  return s_self;
}

KParts::Part *KateFactory::createPartObject ( QWidget *parentWidget, const char *widgetName, QObject *parent, const char *name, const char *classname, const QStringList & )
{
  bool bWantSingleView = !( classname == QString("KTextEditor::Document") );
  bool bWantBrowserView = ( classname == QString("Browser/View") );
  bool bWantReadOnly = (bWantBrowserView || ( classname == QString("KParts::ReadOnlyPart") ));

  KParts::ReadWritePart *part = new KateDocument (bWantSingleView, bWantBrowserView, bWantReadOnly, parentWidget, widgetName, parent, name);
  part->setReadWrite( !bWantReadOnly );

  return part;
}

void KateFactory::registerDocument ( KateDocument *doc )
{
  m_documents.append( doc );
}

void KateFactory::deregisterDocument ( KateDocument *doc )
{
  m_documents.removeRef( doc );
}

void KateFactory::registerView ( KateView *view )
{
  m_views.append( view );
}

void KateFactory::deregisterView ( KateView *view )
{
  m_views.removeRef( view );
}

void KateFactory::registerRenderer ( KateRenderer  *renderer )
{
  m_renderers.append( renderer );
}

void KateFactory::deregisterRenderer ( KateRenderer  *renderer )
{
  m_renderers.removeRef( renderer );
}

// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|>


<commit_before>#include "l4engine.h"

#include <iostream>
#include <iomanip>
#include <assert.h>

using namespace std;

//a-file             0x0101010101010101
//h-file             0x8080808080808080
//1st rank           0x00000000000000FF
//8th rank           0xFF00000000000000
//a1-h8 diagonal     0x8040201008040201
//h1-a8 antidiagonal 0x0102040810204080
//light squares      0x55AA55AA55AA55AA
//dark squares       0xAA55AA55AA55AA55

const bitboard_t Rank[8] = {
    0x00000000000000FF,     // rank 1
    0x000000000000FF00,
    0x0000000000FF0000,
    0x00000000FF000000,
    0x000000FF00000000,
    0x0000FF0000000000,
    0x00FF000000000000,
    0xFF00000000000000,     // rank 8
};

const bitboard_t File[8] = {
    0x0101010101010101,     // a-file
    0x0202020202020202,
    0x0404040404040404,
    0x0808080808080808,
    0x1010101010101010,
    0x2020202020202020,
    0x4040404040404040,
    0x8080808080808080      //h-file
};

const bitboard_t Square[64] = {
    File[FILE_A] & Rank[RANK_1],
    File[FILE_B] & Rank[RANK_1],
    File[FILE_C] & Rank[RANK_1],
    File[FILE_D] & Rank[RANK_1],
    File[FILE_E] & Rank[RANK_1],
    File[FILE_F] & Rank[RANK_1],
    File[FILE_G] & Rank[RANK_1],
    File[FILE_H] & Rank[RANK_1],
    File[FILE_A] & Rank[RANK_2],
    File[FILE_B] & Rank[RANK_2],
    File[FILE_C] & Rank[RANK_2],
    File[FILE_D] & Rank[RANK_2],
    File[FILE_E] & Rank[RANK_2],
    File[FILE_F] & Rank[RANK_2],
    File[FILE_G] & Rank[RANK_2],
    File[FILE_H] & Rank[RANK_2],
    File[FILE_A] & Rank[RANK_3],
    File[FILE_B] & Rank[RANK_3],
    File[FILE_C] & Rank[RANK_3],
    File[FILE_D] & Rank[RANK_3],
    File[FILE_E] & Rank[RANK_3],
    File[FILE_F] & Rank[RANK_3],
    File[FILE_G] & Rank[RANK_3],
    File[FILE_H] & Rank[RANK_3],
    File[FILE_A] & Rank[RANK_4],
    File[FILE_B] & Rank[RANK_4],
    File[FILE_C] & Rank[RANK_4],
    File[FILE_D] & Rank[RANK_4],
    File[FILE_E] & Rank[RANK_4],
    File[FILE_F] & Rank[RANK_4],
    File[FILE_G] & Rank[RANK_4],
    File[FILE_H] & Rank[RANK_4],
    File[FILE_A] & Rank[RANK_5],
    File[FILE_B] & Rank[RANK_5],
    File[FILE_C] & Rank[RANK_5],
    File[FILE_D] & Rank[RANK_5],
    File[FILE_E] & Rank[RANK_5],
    File[FILE_F] & Rank[RANK_5],
    File[FILE_G] & Rank[RANK_5],
    File[FILE_H] & Rank[RANK_5],
    File[FILE_A] & Rank[RANK_6],
    File[FILE_B] & Rank[RANK_6],
    File[FILE_C] & Rank[RANK_6],
    File[FILE_D] & Rank[RANK_6],
    File[FILE_E] & Rank[RANK_6],
    File[FILE_F] & Rank[RANK_6],
    File[FILE_G] & Rank[RANK_6],
    File[FILE_H] & Rank[RANK_6],
    File[FILE_A] & Rank[RANK_7],
    File[FILE_B] & Rank[RANK_7],
    File[FILE_C] & Rank[RANK_7],
    File[FILE_D] & Rank[RANK_7],
    File[FILE_E] & Rank[RANK_7],
    File[FILE_F] & Rank[RANK_7],
    File[FILE_G] & Rank[RANK_7],
    File[FILE_H] & Rank[RANK_7],
    File[FILE_A] & Rank[RANK_8],
    File[FILE_B] & Rank[RANK_8],
    File[FILE_C] & Rank[RANK_8],
    File[FILE_D] & Rank[RANK_8],
    File[FILE_E] & Rank[RANK_8],
    File[FILE_F] & Rank[RANK_8],
    File[FILE_G] & Rank[RANK_8],
    File[FILE_H] & Rank[RANK_8]
};

const struct chessboard_t chess_initial_state = {
    rank_mask(RANK_2),      // w_pawns

    rank_mask(RANK_7),      // b_pawns
};

bitboard_t rank_mask(size_t rank)
{
    assert(rank <= 8);
    return Rank[rank];
}

bitboard_t file_mask(size_t file)
{
    assert(file <= 8);
    return File[file];
}

bitboard_t square_mask(size_t sq)
{
    assert(sq <= 63);
    return Square[sq];
}

void print_bitboard(bitboard_t b)
{
    cout << "\t    a   b   c   d   e   f   g   h  " << endl;
    cout << "\t  +---+---+---+---+---+---+---+---+" << endl;

    for (int i = 56; i >= 0; i -= 8) {
        int rank = (i / 8) + 1;
        cout << "\t" << rank << " ";

        for (int j = 0; j < 8; j++ ) {
            bitboard_t bit = b & square_mask(i+j);

            if (bit)
                cout << "| X ";
            else
                cout << "|   ";
        }

        cout << "| " << rank << endl;
        cout << "\t  +---+---+---+---+---+---+---+---+" << endl;
    }

    cout << "\t    a   b   c   d   e   f   g   h  " << endl;
}

// QKRBNP for white pieces, lowercase for black
// http://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
void print_chessboard(chessboard_t board)
{
    cout << "\t    a   b   c   d   e   f   g   h  " << endl;
    cout << "\t  +---+---+---+---+---+---+---+---+" << endl;

    for (int i = 56; i >= 0; i -= 8) {
        int rank = (i / 8) + 1;
        cout << "\t" << rank << " ";

        for (int j = 0; j < 8; j++ ) {
            bitboard_t mask = square_mask(i+j);

            if (board.w_pawns & mask)
                cout << "| X ";
            else
                cout << "|   ";
        }

        cout << "| " << rank << endl;
        cout << "\t  +---+---+---+---+---+---+---+---+" << endl;
    }

    cout << "\t    a   b   c   d   e   f   g   h  " << endl;
}

<commit_msg>wrote print_chessboard();<commit_after>#include "l4engine.h"

#include <iostream>
#include <iomanip>
#include <assert.h>

using namespace std;

//a-file             0x0101010101010101
//h-file             0x8080808080808080
//1st rank           0x00000000000000FF
//8th rank           0xFF00000000000000
//a1-h8 diagonal     0x8040201008040201
//h1-a8 antidiagonal 0x0102040810204080
//light squares      0x55AA55AA55AA55AA
//dark squares       0xAA55AA55AA55AA55

const bitboard_t Rank[8] = {
    0x00000000000000FF,     // rank 1
    0x000000000000FF00,
    0x0000000000FF0000,
    0x00000000FF000000,
    0x000000FF00000000,
    0x0000FF0000000000,
    0x00FF000000000000,
    0xFF00000000000000,     // rank 8
};

const bitboard_t File[8] = {
    0x0101010101010101,     // a-file
    0x0202020202020202,
    0x0404040404040404,
    0x0808080808080808,
    0x1010101010101010,
    0x2020202020202020,
    0x4040404040404040,
    0x8080808080808080      //h-file
};

const bitboard_t Square[64] = {
    File[FILE_A] & Rank[RANK_1],
    File[FILE_B] & Rank[RANK_1],
    File[FILE_C] & Rank[RANK_1],
    File[FILE_D] & Rank[RANK_1],
    File[FILE_E] & Rank[RANK_1],
    File[FILE_F] & Rank[RANK_1],
    File[FILE_G] & Rank[RANK_1],
    File[FILE_H] & Rank[RANK_1],
    File[FILE_A] & Rank[RANK_2],
    File[FILE_B] & Rank[RANK_2],
    File[FILE_C] & Rank[RANK_2],
    File[FILE_D] & Rank[RANK_2],
    File[FILE_E] & Rank[RANK_2],
    File[FILE_F] & Rank[RANK_2],
    File[FILE_G] & Rank[RANK_2],
    File[FILE_H] & Rank[RANK_2],
    File[FILE_A] & Rank[RANK_3],
    File[FILE_B] & Rank[RANK_3],
    File[FILE_C] & Rank[RANK_3],
    File[FILE_D] & Rank[RANK_3],
    File[FILE_E] & Rank[RANK_3],
    File[FILE_F] & Rank[RANK_3],
    File[FILE_G] & Rank[RANK_3],
    File[FILE_H] & Rank[RANK_3],
    File[FILE_A] & Rank[RANK_4],
    File[FILE_B] & Rank[RANK_4],
    File[FILE_C] & Rank[RANK_4],
    File[FILE_D] & Rank[RANK_4],
    File[FILE_E] & Rank[RANK_4],
    File[FILE_F] & Rank[RANK_4],
    File[FILE_G] & Rank[RANK_4],
    File[FILE_H] & Rank[RANK_4],
    File[FILE_A] & Rank[RANK_5],
    File[FILE_B] & Rank[RANK_5],
    File[FILE_C] & Rank[RANK_5],
    File[FILE_D] & Rank[RANK_5],
    File[FILE_E] & Rank[RANK_5],
    File[FILE_F] & Rank[RANK_5],
    File[FILE_G] & Rank[RANK_5],
    File[FILE_H] & Rank[RANK_5],
    File[FILE_A] & Rank[RANK_6],
    File[FILE_B] & Rank[RANK_6],
    File[FILE_C] & Rank[RANK_6],
    File[FILE_D] & Rank[RANK_6],
    File[FILE_E] & Rank[RANK_6],
    File[FILE_F] & Rank[RANK_6],
    File[FILE_G] & Rank[RANK_6],
    File[FILE_H] & Rank[RANK_6],
    File[FILE_A] & Rank[RANK_7],
    File[FILE_B] & Rank[RANK_7],
    File[FILE_C] & Rank[RANK_7],
    File[FILE_D] & Rank[RANK_7],
    File[FILE_E] & Rank[RANK_7],
    File[FILE_F] & Rank[RANK_7],
    File[FILE_G] & Rank[RANK_7],
    File[FILE_H] & Rank[RANK_7],
    File[FILE_A] & Rank[RANK_8],
    File[FILE_B] & Rank[RANK_8],
    File[FILE_C] & Rank[RANK_8],
    File[FILE_D] & Rank[RANK_8],
    File[FILE_E] & Rank[RANK_8],
    File[FILE_F] & Rank[RANK_8],
    File[FILE_G] & Rank[RANK_8],
    File[FILE_H] & Rank[RANK_8]
};

const struct chessboard_t chess_initial_state = {
    rank_mask(RANK_2),      // w_pawns

    rank_mask(RANK_7),      // b_pawns
};

bitboard_t rank_mask(size_t rank)
{
    assert(rank <= 8);
    return Rank[rank];
}

bitboard_t file_mask(size_t file)
{
    assert(file <= 8);
    return File[file];
}

bitboard_t square_mask(size_t sq)
{
    assert(sq <= 63);
    return Square[sq];
}

void print_bitboard(bitboard_t b)
{
    cout << "\t    a   b   c   d   e   f   g   h  " << endl;
    cout << "\t  +---+---+---+---+---+---+---+---+" << endl;

    for (int i = 56; i >= 0; i -= 8) {
        int rank = (i / 8) + 1;
        cout << "\t" << rank << " ";

        for (int j = 0; j < 8; j++ ) {
            bitboard_t bit = b & square_mask(i+j);

            if (bit)
                cout << "| X ";
            else
                cout << "|   ";
        }

        cout << "| " << rank << endl;
        cout << "\t  +---+---+---+---+---+---+---+---+" << endl;
    }

    cout << "\t    a   b   c   d   e   f   g   h  " << endl;
}

// QKRBNP for white pieces, lowercase for black
// http://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
void print_chessboard(chessboard_t board)
{
    cout << "\t    a   b   c   d   e   f   g   h  " << endl;
    cout << "\t  +---+---+---+---+---+---+---+---+" << endl;

    for (int i = 56; i >= 0; i -= 8) {
        int rank = (i / 8) + 1;
        cout << "\t" << rank << " ";

        for (int j = 0; j < 8; j++ ) {
            bitboard_t mask = square_mask(i+j);

            if (board.w_pawns & mask)
                cout << "| P ";
            else if (board.w_rooks & mask)
                cout << "| R ";
            else if (board.w_knights & mask)
                cout << "| N ";
            else if (board.w_bishops & mask)
                cout << "| B ";
            else if (board.w_queens & mask)
                cout << "| Q ";
            else if (board.w_king & mask)
                cout << "| K ";
            else if (board.b_pawns & mask)
                cout << "| p ";
            else if (board.b_rooks & mask)
                cout << "| r ";
            else if (board.b_knights & mask)
                cout << "| n ";
            else if (board.b_bishops & mask)
                cout << "| b ";
            else if (board.b_queens & mask)
                cout << "| q ";
            else if (board.b_king & mask)
                cout << "| k ";
            else
                cout << "|   ";
        }

        cout << "| " << rank << endl;
        cout << "\t  +---+---+---+---+---+---+---+---+" << endl;
    }

    cout << "\t    a   b   c   d   e   f   g   h  " << endl;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: externallock.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 12:21:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_toolkit.hxx"

#ifndef _TOOLKIT_HELPER_EXTERNALLOCK_HXX_
#include <toolkit/helper/externallock.hxx>
#endif

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

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

// -----------------------------------------------------------------------------
//  class VCLExternalSolarLock
// -----------------------------------------------------------------------------
void VCLExternalSolarLock::acquire()
{
    Application::GetSolarMutex().acquire();
}
// -----------------------------------------------------------------------------
void VCLExternalSolarLock::release()
{
    Application::GetSolarMutex().release();
}

<commit_msg>INTEGRATION: CWS changefileheader (1.3.210); FILE MERGED 2008/04/01 16:01:01 thb 1.3.210.3: #i85898# Stripping all external header guards 2008/04/01 12:56:54 thb 1.3.210.2: #i85898# Stripping all external header guards 2008/03/28 15:40:19 rt 1.3.210.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: externallock.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_toolkit.hxx"
#include <toolkit/helper/externallock.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>

// -----------------------------------------------------------------------------
//  class VCLExternalSolarLock
// -----------------------------------------------------------------------------
void VCLExternalSolarLock::acquire()
{
    Application::GetSolarMutex().acquire();
}
// -----------------------------------------------------------------------------
void VCLExternalSolarLock::release()
{
    Application::GetSolarMutex().release();
}

<|endoftext|>