<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: insctrl.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 13:04:36 $
 *
 *  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_svx.hxx"

// include ---------------------------------------------------------------

#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif

#define _SVX_INSCTRL_CXX

#include "dialogs.hrc"

#include "insctrl.hxx"
#include "dialmgr.hxx"

#define PAINT_OFFSET    5

SFX_IMPL_STATUSBAR_CONTROL(SvxInsertStatusBarControl, SfxBoolItem);

// class SvxInsertStatusBarControl ---------------------------------------

SvxInsertStatusBarControl::SvxInsertStatusBarControl( USHORT _nSlotId,
                                                      USHORT _nId,
                                                      StatusBar& rStb ) :

    SfxStatusBarControl( _nSlotId, _nId, rStb ),
    bInsert( TRUE )
{
    rStb.SetHelpId( _nId, _nSlotId );
}

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

SvxInsertStatusBarControl::~SvxInsertStatusBarControl()
{
}

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

void SvxInsertStatusBarControl::StateChanged( USHORT , SfxItemState eState,
                                              const SfxPoolItem* pState )
{
    if ( SFX_ITEM_AVAILABLE != eState )
        GetStatusBar().SetItemText( GetId(), String() );
    else
    {
        DBG_ASSERT( pState->ISA( SfxBoolItem ), "invalid item type" );
        SfxBoolItem* pItem = (SfxBoolItem*)pState;
        bInsert = pItem->GetValue();
        DrawItemText_Impl();
    }
}

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

void SvxInsertStatusBarControl::Click()
{
    if ( !GetStatusBar().GetItemText( GetId() ).Len() )
        return;
    bInsert = !bInsert;
    SfxBoolItem aIns( GetSlotId(), bInsert );

    ::com::sun::star::uno::Any a;
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs( 1 );
    aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "InsertMode" ));
    aIns.QueryValue( a );
    aArgs[0].Value = a;

    execute( aArgs );
}

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

void SvxInsertStatusBarControl::Paint( const UserDrawEvent& )
{
    DrawItemText_Impl();
}

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

void SvxInsertStatusBarControl::DrawItemText_Impl()
{
    USHORT _nId = RID_SVXSTR_OVERWRITE_TEXT;

    if ( bInsert )
        _nId = RID_SVXSTR_INSERT_TEXT;
    GetStatusBar().SetItemText( GetId(), SVX_RESSTR( _nId ) );
}

ULONG SvxInsertStatusBarControl::GetDefItemWidth(const StatusBar& rStb)
{
    long nWidth1 =  rStb.GetTextWidth(SVX_RESSTR(RID_SVXSTR_OVERWRITE_TEXT));
    long nWidth2 =  rStb.GetTextWidth(SVX_RESSTR(RID_SVXSTR_INSERT_TEXT));

    if(nWidth1<nWidth2)
        nWidth1=nWidth2;

    return nWidth1+PAINT_OFFSET;
}

<commit_msg>INTEGRATION: CWS vgbugs07 (1.6.320); FILE MERGED 2007/06/04 13:27:20 vg 1.6.320.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: insctrl.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 18:54:37 $
 *
 *  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_svx.hxx"

// include ---------------------------------------------------------------

#ifndef _SHL_HXX
#include <tools/shl.hxx>
#endif
#ifndef _STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif

#define _SVX_INSCTRL_CXX

#include <svx/dialogs.hrc>

#include "insctrl.hxx"
#include <svx/dialmgr.hxx>

#define PAINT_OFFSET    5

SFX_IMPL_STATUSBAR_CONTROL(SvxInsertStatusBarControl, SfxBoolItem);

// class SvxInsertStatusBarControl ---------------------------------------

SvxInsertStatusBarControl::SvxInsertStatusBarControl( USHORT _nSlotId,
                                                      USHORT _nId,
                                                      StatusBar& rStb ) :

    SfxStatusBarControl( _nSlotId, _nId, rStb ),
    bInsert( TRUE )
{
    rStb.SetHelpId( _nId, _nSlotId );
}

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

SvxInsertStatusBarControl::~SvxInsertStatusBarControl()
{
}

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

void SvxInsertStatusBarControl::StateChanged( USHORT , SfxItemState eState,
                                              const SfxPoolItem* pState )
{
    if ( SFX_ITEM_AVAILABLE != eState )
        GetStatusBar().SetItemText( GetId(), String() );
    else
    {
        DBG_ASSERT( pState->ISA( SfxBoolItem ), "invalid item type" );
        SfxBoolItem* pItem = (SfxBoolItem*)pState;
        bInsert = pItem->GetValue();
        DrawItemText_Impl();
    }
}

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

void SvxInsertStatusBarControl::Click()
{
    if ( !GetStatusBar().GetItemText( GetId() ).Len() )
        return;
    bInsert = !bInsert;
    SfxBoolItem aIns( GetSlotId(), bInsert );

    ::com::sun::star::uno::Any a;
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs( 1 );
    aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "InsertMode" ));
    aIns.QueryValue( a );
    aArgs[0].Value = a;

    execute( aArgs );
}

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

void SvxInsertStatusBarControl::Paint( const UserDrawEvent& )
{
    DrawItemText_Impl();
}

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

void SvxInsertStatusBarControl::DrawItemText_Impl()
{
    USHORT _nId = RID_SVXSTR_OVERWRITE_TEXT;

    if ( bInsert )
        _nId = RID_SVXSTR_INSERT_TEXT;
    GetStatusBar().SetItemText( GetId(), SVX_RESSTR( _nId ) );
}

ULONG SvxInsertStatusBarControl::GetDefItemWidth(const StatusBar& rStb)
{
    long nWidth1 =  rStb.GetTextWidth(SVX_RESSTR(RID_SVXSTR_OVERWRITE_TEXT));
    long nWidth2 =  rStb.GetTextWidth(SVX_RESSTR(RID_SVXSTR_INSERT_TEXT));

    if(nWidth1<nWidth2)
        nWidth1=nWidth2;

    return nWidth1+PAINT_OFFSET;
}

<|endoftext|>


<commit_before>#include <algorithm> // std::equal
#include <iostream>
#include <list>
#include <sstream>
#include <unordered_map>

#include "parsers/helpers.hh"
#include "parsers/parse_error.hh"
#include "parsers/prod.hh"

namespace pnmc { namespace parsers {

/*------------------------------------------------------------------------------------------------*/

namespace {

unsigned int
marking(std::string::const_iterator cit, std::string::const_iterator cend)
{
  const auto distance = std::distance(cit, cend);
  if (distance == 4)
  {
    static const std::string mk("<..>");
    if (std::equal(cit, cend, mk.cbegin()))
    {
      return 1;
    }
    else
    {
      throw parse_error("Invalid marking token :" + std::string(cit, cend));
    }
  }
  else if (distance > 4)
  {
    try
    {
      return std::stoi(std::string(cit, cend));
    }
    catch (const std::invalid_argument&)
    {
      throw parse_error("Expected a value, got " + std::string(cit, cend));
    }
  }
  else
  {
    throw parse_error("Invalid marking token :" + std::string(cit, cend));
  }
}

} // namespace anonymous

/*------------------------------------------------------------------------------------------------*/

std::shared_ptr<pn::net>
prod(std::istream& in)
{
  std::shared_ptr<pn::net> net_ptr = std::make_shared<pn::net>();
  auto& net = *net_ptr;

  std::string line, s0, s1, s2;
  line.reserve(1024);

  std::list<pn::module_node> modules;
  std::unordered_map<std::string, std::list<pn::module_node>::iterator> index;

  while (std::getline(in, line))
  {
    std::istringstream ss(line);

    ss >> s0;

    if (s0 == "#place")
    {
      // module, if any
      bool has_module = false;
      if (((ss >> std::ws).peek() == std::char_traits<char>::to_int_type('(')))
      {
        ss >> s0;
        if (*std::prev(s0.cend()) != ')')
        {
          throw parse_error("Expected a module specification got " + s0);
        }
        has_module = true;
      }

      // default marking
      unsigned int m = 0;
      if (not(ss >> s1))// place name
      {
        throw parse_error("Place with no identifier ");
      }
      if (ss >> s2) // have marking
      {
        static const std::string mk("mk(");
        if (  s2.size() < 8 or not std::equal(mk.cbegin(), mk.cend(), s2.cbegin())
            or *(s2.cend() - 1) != ')')
        {
          throw parse_error("Invalid marking, got " + s2);
        }
        m = marking(s2.cbegin() + 3, s2.cend() - 1);
      }

      const auto& p = net.add_place(s1, m);
      if (has_module)
      {
        const auto search = index.find(s0);
        if (search == index.cend())
        {
          modules.emplace_back(pn::module_node(s0));
          index[s0] = std::prev(modules.end());
        }
        index[s0]->add_module(pn::make_module(p));
      }
    }

    else if (s0 == "#trans")
    {
      if (not (ss >> s0))
      {
        throw parse_error("Transition with no identifier ");
      }

      net.add_transition(s0);

      // pre
      if (not std::getline(in,line))
      {
        throw parse_error("Incomplete transition.");
      }
      std::istringstream l0(line);
      if (not (l0 >> kw("in") >> s1))
      {
        throw parse_error("Invalid pre for transition " + s0 + " : " + s1);
      }

      if (not (*s1.cbegin() == '{' and *(s1.cend() - 1) == '}'))
      {
        throw parse_error("Missing '{' or '}' " + s1);
      }

      for (const auto& arc_str : split(s1.cbegin() + 1, s1.cend() - 1, ';'))
      {
        const auto arc = split(arc_str.cbegin(), arc_str.cend(), ':');
        if (arc.size() != 2)
        {
          throw parse_error("Incorrect arc " + arc_str);
        }
        net.add_pre_place(s0, arc[0], marking(arc[1].cbegin(), arc[1].cend()));
      }

      // post
      if (not std::getline(in,line))
      {
        throw parse_error("Incomplete transition.");
      }
      std::istringstream l1(line);
      if (not (l1 >> kw("out") >> s1))
      {
        throw parse_error("Invalid post for transition " + s0 + " : " + s1);
      }

      if (not (*s1.cbegin() == '{' and *(s1.cend() - 1) == '}'))
      {
        throw parse_error("Missing '{' or '}' " + s1);
      }

      for (const auto& arc_str : split(s1.cbegin() + 1, s1.cend() - 1, ';'))
      {
        const auto arc = split(arc_str.cbegin(), arc_str.cend(), ':');
        if (arc.size() != 2)
        {
          throw parse_error("Incorrect arc " + arc_str);
        }
        net.add_post_place(s0, arc[0], marking(arc[1].cbegin(), arc[1].cend()));
      }

      // end of transition
      if (not std::getline(in,line))
      {
        throw parse_error("Incomplete transition.");
      }
      std::istringstream l2(line);
      l2 >> kw("#endtr");
    }

    else
    {
      throw parse_error("Invalid line, got " + line);
    }
  }

  if (not modules.empty())
  {
    pn::module_node root("root");
    for (const auto& m : modules)
    {
      root.add_module(pn::make_module(m));
    }
    net.modules = pn::make_module(root);
  }

  return net_ptr;
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace pnmc::parsers
<commit_msg>PROD: Really use the order of the modules as declared in the model file.<commit_after>#include <algorithm> // std::equal
#include <iostream>
#include <list>
#include <sstream>
#include <unordered_map>

#include "parsers/helpers.hh"
#include "parsers/parse_error.hh"
#include "parsers/prod.hh"

namespace pnmc { namespace parsers {

/*------------------------------------------------------------------------------------------------*/

namespace {

unsigned int
marking(std::string::const_iterator cit, std::string::const_iterator cend)
{
  const auto distance = std::distance(cit, cend);
  if (distance == 4)
  {
    static const std::string mk("<..>");
    if (std::equal(cit, cend, mk.cbegin()))
    {
      return 1;
    }
    else
    {
      throw parse_error("Invalid marking token :" + std::string(cit, cend));
    }
  }
  else if (distance > 4)
  {
    try
    {
      return std::stoi(std::string(cit, cend));
    }
    catch (const std::invalid_argument&)
    {
      throw parse_error("Expected a value, got " + std::string(cit, cend));
    }
  }
  else
  {
    throw parse_error("Invalid marking token :" + std::string(cit, cend));
  }
}

} // namespace anonymous

/*------------------------------------------------------------------------------------------------*/

std::shared_ptr<pn::net>
prod(std::istream& in)
{
  std::shared_ptr<pn::net> net_ptr = std::make_shared<pn::net>();
  auto& net = *net_ptr;

  std::string line, s0, s1, s2;
  line.reserve(1024);

  std::list<pn::module_node> modules;
  std::unordered_map<std::string, std::list<pn::module_node>::iterator> index;

  while (std::getline(in, line))
  {
    std::istringstream ss(line);

    ss >> s0;

    if (s0 == "#place")
    {
      // module, if any
      bool has_module = false;
      if (((ss >> std::ws).peek() == std::char_traits<char>::to_int_type('(')))
      {
        ss >> s0;
        if (*std::prev(s0.cend()) != ')')
        {
          throw parse_error("Expected a module specification got " + s0);
        }
        has_module = true;
      }

      // default marking
      unsigned int m = 0;
      if (not(ss >> s1))// place name
      {
        throw parse_error("Place with no identifier ");
      }
      if (ss >> s2) // have marking
      {
        static const std::string mk("mk(");
        if (  s2.size() < 8 or not std::equal(mk.cbegin(), mk.cend(), s2.cbegin())
            or *(s2.cend() - 1) != ')')
        {
          throw parse_error("Invalid marking, got " + s2);
        }
        m = marking(s2.cbegin() + 3, s2.cend() - 1);
      }

      const auto& p = net.add_place(s1, m);
      if (has_module)
      {
        const auto search = index.find(s0);
        if (search == index.cend())
        {
          modules.emplace_back(pn::module_node(s0));
          index[s0] = std::prev(modules.end());
        }
        index[s0]->add_module(pn::make_module(p));
      }
    }

    else if (s0 == "#trans")
    {
      if (not (ss >> s0))
      {
        throw parse_error("Transition with no identifier ");
      }

      net.add_transition(s0);

      // pre
      if (not std::getline(in,line))
      {
        throw parse_error("Incomplete transition.");
      }
      std::istringstream l0(line);
      if (not (l0 >> kw("in") >> s1))
      {
        throw parse_error("Invalid pre for transition " + s0 + " : " + s1);
      }

      if (not (*s1.cbegin() == '{' and *(s1.cend() - 1) == '}'))
      {
        throw parse_error("Missing '{' or '}' " + s1);
      }

      for (const auto& arc_str : split(s1.cbegin() + 1, s1.cend() - 1, ';'))
      {
        const auto arc = split(arc_str.cbegin(), arc_str.cend(), ':');
        if (arc.size() != 2)
        {
          throw parse_error("Incorrect arc " + arc_str);
        }
        net.add_pre_place(s0, arc[0], marking(arc[1].cbegin(), arc[1].cend()));
      }

      // post
      if (not std::getline(in,line))
      {
        throw parse_error("Incomplete transition.");
      }
      std::istringstream l1(line);
      if (not (l1 >> kw("out") >> s1))
      {
        throw parse_error("Invalid post for transition " + s0 + " : " + s1);
      }

      if (not (*s1.cbegin() == '{' and *(s1.cend() - 1) == '}'))
      {
        throw parse_error("Missing '{' or '}' " + s1);
      }

      for (const auto& arc_str : split(s1.cbegin() + 1, s1.cend() - 1, ';'))
      {
        const auto arc = split(arc_str.cbegin(), arc_str.cend(), ':');
        if (arc.size() != 2)
        {
          throw parse_error("Incorrect arc " + arc_str);
        }
        net.add_post_place(s0, arc[0], marking(arc[1].cbegin(), arc[1].cend()));
      }

      // end of transition
      if (not std::getline(in,line))
      {
        throw parse_error("Incomplete transition.");
      }
      std::istringstream l2(line);
      l2 >> kw("#endtr");
    }

    else
    {
      throw parse_error("Invalid line, got " + line);
    }
  }

  if (not modules.empty())
  {
    pn::module_node root("root");
    for (auto rcit = modules.rbegin(); rcit != modules.rend(); ++rcit)
    {
      root.add_module(pn::make_module(*rcit));
    }
    net.modules = pn::make_module(root);
  }

  return net_ptr;
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace pnmc::parsers
<|endoftext|>


<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#include <hpp/core/path-planner.hh>

#include <hpp/util/debug.hh>

#include <hpp/core/roadmap.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/problem-target.hh>
#include <hpp/core/node.hh>
#include <hpp/core/edge.hh>
#include <hpp/core/path.hh>
#include <hpp/core/path-validation.hh>
#include <hpp/core/path-projector.hh>
#include <hpp/core/steering-method.hh>
#include "astar.hh"
#include <hpp/util/timer.hh>

namespace hpp {
  namespace core {

    PathPlanner::PathPlanner (const Problem& problem) :
      problem_ (problem), roadmap_ (Roadmap::create (problem.distance (),
						     problem.robot())),
      interrupt_ (false),
      maxIterations_ (std::numeric_limits <unsigned long int>::infinity ()),
      timeOut_ (std::numeric_limits <double>::infinity ())
    {
    }

    PathPlanner::PathPlanner (const Problem& problem,
			      const RoadmapPtr_t& roadmap) :
      problem_ (problem), roadmap_ (roadmap),
      interrupt_ (false),
      maxIterations_ (std::numeric_limits <unsigned long int>::infinity ()),
      timeOut_ (std::numeric_limits <double>::infinity ())
    {
    }

    void PathPlanner::init (const PathPlannerWkPtr_t& weak)
    {
      weakPtr_ = weak;
    }

    const RoadmapPtr_t& PathPlanner::roadmap () const
    {
      return roadmap_;
    }

    const Problem& PathPlanner::problem () const
    {
      return problem_;
    }

    void PathPlanner::startSolve ()
    {
      problem_.checkProblem ();
      // Tag init and goal configurations in the roadmap
      roadmap()->resetGoalNodes ();
      roadmap()->initNode (problem_.initConfig ());
      const Configurations_t goals (problem_.goalConfigs ());
      for (Configurations_t::const_iterator itGoal = goals.begin ();
          itGoal != goals.end (); ++itGoal) {
        roadmap()->addGoalNode (*itGoal);
      }

      problem_.target()->check(roadmap());
    }

    PathVectorPtr_t PathPlanner::solve ()
    {
      interrupt_ = false;
      bool solved = false;
      unsigned long int nIter (0);
      boost::posix_time::ptime timeStart(boost::posix_time::microsec_clock::universal_time());
      startSolve ();
      tryDirectPath ();
      solved = problem_.target()->reached (roadmap());
      if (solved ) {
	hppDout (info, "tryDirectPath succeeded");
      }
      if (interrupt_) throw std::runtime_error ("Interruption");
      while (!solved) {
	std::ostringstream oss;
    if (maxIterations_ !=  std::numeric_limits <unsigned long int>::infinity () && nIter >= maxIterations_) {
	  oss << "Maximal number of iterations reached: " << maxIterations_;
	  throw std::runtime_error (oss.str ().c_str ());
    }
    if(((boost::posix_time::microsec_clock::universal_time() - timeStart).total_milliseconds()) > timeOut_*1000.){
      oss << "time out reached : " << timeOut_<<" s";
      throw std::runtime_error (oss.str ().c_str ());
    }
    hppStartBenchmark(ONE_STEP);
	oneStep ();
    hppStopBenchmark(ONE_STEP);
    hppDisplayBenchmark(ONE_STEP);

	++nIter;
        solved = problem_.target()->reached (roadmap());
	if (interrupt_) throw std::runtime_error ("Interruption");
      }
      PathVectorPtr_t planned =  computePath ();
      return finishSolve (planned);
    }

    void PathPlanner::interrupt ()
    {
      interrupt_ = true;
    }

    void PathPlanner::maxIterations (const unsigned long int& n)
    {
      maxIterations_ = n;
    }

    PathVectorPtr_t PathPlanner::computePath () const
    {
      return problem_.target()->computePath(roadmap());
    }

    PathVectorPtr_t PathPlanner::finishSolve (const PathVectorPtr_t& path)
    {
      return path;
    }

    void PathPlanner::tryDirectPath ()
    {
      // call steering method here to build a direct conexion
      const SteeringMethodPtr_t& sm (problem ().steeringMethod ());
      PathValidationPtr_t pathValidation (problem ().pathValidation ());
      PathProjectorPtr_t pathProjector (problem ().pathProjector ());
      PathPtr_t validPath, projPath, path;
      NodePtr_t initNode = roadmap ()->initNode();
      for (NodeVector_t::const_iterator itn = roadmap ()->goalNodes ().begin();
	   itn != roadmap ()->goalNodes ().end (); ++itn) {
	ConfigurationPtr_t q1 ((initNode)->configuration ());
	ConfigurationPtr_t q2 ((*itn)->configuration ());
	assert (*q1 != *q2);
	path = (*sm) (*q1, *q2);
        if (!path) continue;
        if (pathProjector) {
          if (!pathProjector->apply (path, projPath)) continue;
        } else {
          projPath = path;
        }
        if (projPath) {
	  PathValidationReportPtr_t report;
          bool pathValid = pathValidation->validate (projPath, false, validPath,
						     report);
          if (pathValid && validPath->timeRange ().second !=
              path->timeRange ().first) {
            roadmap ()->addEdge (initNode, *itn, projPath);
            roadmap ()->addEdge (*itn, initNode, projPath->reverse());
          }
        }
      }
    }
  } //   namespace core
} // namespace hpp
<commit_msg>[Minor] use path->length instead of interval.second - interval.first<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#include <hpp/core/path-planner.hh>

#include <hpp/util/debug.hh>

#include <hpp/core/roadmap.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/problem-target.hh>
#include <hpp/core/node.hh>
#include <hpp/core/edge.hh>
#include <hpp/core/path.hh>
#include <hpp/core/path-validation.hh>
#include <hpp/core/path-projector.hh>
#include <hpp/core/steering-method.hh>
#include "astar.hh"
#include <hpp/util/timer.hh>

namespace hpp {
  namespace core {

    PathPlanner::PathPlanner (const Problem& problem) :
      problem_ (problem), roadmap_ (Roadmap::create (problem.distance (),
						     problem.robot())),
      interrupt_ (false),
      maxIterations_ (std::numeric_limits <unsigned long int>::infinity ()),
      timeOut_ (std::numeric_limits <double>::infinity ())
    {
    }

    PathPlanner::PathPlanner (const Problem& problem,
			      const RoadmapPtr_t& roadmap) :
      problem_ (problem), roadmap_ (roadmap),
      interrupt_ (false),
      maxIterations_ (std::numeric_limits <unsigned long int>::infinity ()),
      timeOut_ (std::numeric_limits <double>::infinity ())
    {
    }

    void PathPlanner::init (const PathPlannerWkPtr_t& weak)
    {
      weakPtr_ = weak;
    }

    const RoadmapPtr_t& PathPlanner::roadmap () const
    {
      return roadmap_;
    }

    const Problem& PathPlanner::problem () const
    {
      return problem_;
    }

    void PathPlanner::startSolve ()
    {
      problem_.checkProblem ();
      // Tag init and goal configurations in the roadmap
      roadmap()->resetGoalNodes ();
      roadmap()->initNode (problem_.initConfig ());
      const Configurations_t goals (problem_.goalConfigs ());
      for (Configurations_t::const_iterator itGoal = goals.begin ();
          itGoal != goals.end (); ++itGoal) {
        roadmap()->addGoalNode (*itGoal);
      }

      problem_.target()->check(roadmap());
    }

    PathVectorPtr_t PathPlanner::solve ()
    {
      interrupt_ = false;
      bool solved = false;
      unsigned long int nIter (0);
      boost::posix_time::ptime timeStart(boost::posix_time::microsec_clock::universal_time());
      startSolve ();
      tryDirectPath ();
      solved = problem_.target()->reached (roadmap());
      if (solved ) {
	hppDout (info, "tryDirectPath succeeded");
      }
      if (interrupt_) throw std::runtime_error ("Interruption");
      while (!solved) {
	std::ostringstream oss;
    if (maxIterations_ !=  std::numeric_limits <unsigned long int>::infinity () && nIter >= maxIterations_) {
	  oss << "Maximal number of iterations reached: " << maxIterations_;
	  throw std::runtime_error (oss.str ().c_str ());
    }
    if(((boost::posix_time::microsec_clock::universal_time() - timeStart).total_milliseconds()) > timeOut_*1000.){
      oss << "time out reached : " << timeOut_<<" s";
      throw std::runtime_error (oss.str ().c_str ());
    }
    hppStartBenchmark(ONE_STEP);
	oneStep ();
    hppStopBenchmark(ONE_STEP);
    hppDisplayBenchmark(ONE_STEP);

	++nIter;
        solved = problem_.target()->reached (roadmap());
	if (interrupt_) throw std::runtime_error ("Interruption");
      }
      PathVectorPtr_t planned =  computePath ();
      return finishSolve (planned);
    }

    void PathPlanner::interrupt ()
    {
      interrupt_ = true;
    }

    void PathPlanner::maxIterations (const unsigned long int& n)
    {
      maxIterations_ = n;
    }

    PathVectorPtr_t PathPlanner::computePath () const
    {
      return problem_.target()->computePath(roadmap());
    }

    PathVectorPtr_t PathPlanner::finishSolve (const PathVectorPtr_t& path)
    {
      return path;
    }

    void PathPlanner::tryDirectPath ()
    {
      // call steering method here to build a direct conexion
      const SteeringMethodPtr_t& sm (problem ().steeringMethod ());
      PathValidationPtr_t pathValidation (problem ().pathValidation ());
      PathProjectorPtr_t pathProjector (problem ().pathProjector ());
      PathPtr_t validPath, projPath, path;
      NodePtr_t initNode = roadmap ()->initNode();
      for (NodeVector_t::const_iterator itn = roadmap ()->goalNodes ().begin();
	   itn != roadmap ()->goalNodes ().end (); ++itn) {
	ConfigurationPtr_t q1 ((initNode)->configuration ());
	ConfigurationPtr_t q2 ((*itn)->configuration ());
	assert (*q1 != *q2);
	path = (*sm) (*q1, *q2);
        if (!path) continue;
        if (pathProjector) {
          if (!pathProjector->apply (path, projPath)) continue;
        } else {
          projPath = path;
        }
        if (projPath) {
	  PathValidationReportPtr_t report;
          bool pathValid = pathValidation->validate (projPath, false, validPath,
						     report);
          if (pathValid && validPath->length() > 0) {
            roadmap ()->addEdge (initNode, *itn, projPath);
            roadmap ()->addEdge (*itn, initNode, projPath->reverse());
          }
        }
      }
    }
  } //   namespace core
} // namespace hpp
<|endoftext|>


<commit_before>#include "path_tracer.h"
#include "util.h"
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <memory>

using std::cerr;
using std::queue;
using std::mutex;
using std::lock_guard;
using std::make_shared;
using std::shared_ptr;
using std::thread;

PathTracerIntegrator::Options::Options()
  : russian_roulette(true), rr_kill_prob(0.1), min_rr_depth(4),
    max_depth(10), samples_per_pixel(16), num_threads(1)
{
  assert( 0.0 <= rr_kill_prob && rr_kill_prob <= 1.0 );
}

PathTracerIntegrator::PathTracerIntegrator(const PathTracerIntegrator::Options& opt_)
  : rays_traced(0), primary_rays_traced(0), opt(opt_)
{
}

void PathTracerIntegrator::render(const Camera* cam, const Scene* scene, Film& film)
{
  int num_threads = opt.num_threads;
  if (num_threads == 0)
  {
    num_threads = num_system_procs();
  }

  TaskQueue queue;

  if (num_threads == 1)
  {
    queue.emplace(Film::Rect{0, 0, film.width, film.height}, opt.samples_per_pixel);
    auto temp_film = make_shared<Film>(film.width, film.height, film.filter);
    render_thread(queue, cam, scene, temp_film);
    film.merge( *temp_film.get() );
    return;
  }

  const uint PER_SIDE = 2;
  const int SAMPLES_PER_TASK = 16;

  int samples_left = opt.samples_per_pixel;

  // Populate the task queue.
  while (samples_left > 0)
  {
    int task_samples = min(samples_left, SAMPLES_PER_TASK);
    samples_left -= SAMPLES_PER_TASK;
    for (uint i = 0; i < PER_SIDE; ++i)
    {
      uint x = film.width * i / PER_SIDE;
      uint w = film.width * (i+1) / PER_SIDE - film.width * i / PER_SIDE;

      for (uint j = 0; j < PER_SIDE; ++j)
      {
        uint y = film.height * j / PER_SIDE;
        uint h = film.height * (j+1) / PER_SIDE - film.height * j / PER_SIDE;

        queue.emplace(Film::Rect{x, y, w, h}, static_cast<uint>(task_samples));
      }
    }
  }

  // Create adn run the threads.
  vector<shared_ptr<Film>> films;
  vector<thread> threads;
  for (int i = 0; i < num_threads; ++i)
  {
    films.push_back(make_shared<Film>(film.width, film.height, film.filter));
    threads.push_back(thread(&PathTracerIntegrator::render_thread,
                             this, std::ref(queue), cam, scene, films[i]));
  }

  // Merge and join the results.
  for (auto& th: threads)
    th.join();

  for (const auto& f: films)
    film.merge(*f.get());
}

spectrum PathTracerIntegrator::trace_ray(const Scene* scene, const Ray& ray,
                                         Sampler& sampler, int depth) const
{
  ++rays_traced;
  if (depth == 1)
    ++primary_rays_traced;

  Intersection isect = scene->intersect(ray);
  const Vec3 ray_dir_origin = -ray.direction.normal();
  if (!isect.valid())
    return scene->environment_light_emission(-ray_dir_origin);
  if (isect.is_emissive())
    return isect.emission();

  spectrum total{0};
  scalar VN = ray_dir_origin.dot(isect.normal);

  // direct lighting: randomly choose a light or emissive shape, and contribute
  // the light from that shape if appropriate, but only if we're not 'behind'
  // the intersection point
  if (VN > 0)
  {
    scalar light_prob;

    const Light* light = scene->sample_light(sampler.sample_1d(), light_prob);

    if (light_prob > 0)
    {
      LightSample ls = light->sample_emission(isect, sampler);

      if (ls)
      {
        if (!ls.is_occluded(scene))
        {
          scalar NL = max<scalar>(ls.direction().dot(isect.normal), 0.0);
          scalar ca = isect.reflectance(ls.direction(), ray_dir_origin);

          auto light_contrib = ls.emission() * spectrum{NL * ca / light_prob};
          total += light_contrib;
        }
      }
    }
  }

  // Decide whether or not to continue trace and, if so, what the multiplier
  // should be.
  bool continue_trace = true;
  scalar p_mult = 1.0;
  if (opt.max_depth > 0 && depth >= opt.max_depth)
    continue_trace = false;
  else if (opt.russian_roulette && depth >= opt.min_rr_depth)
  {
    if (sampler.sample_1d() < opt.rr_kill_prob)
    {
      continue_trace = false;
    }
    else
    {
      p_mult /= (1 - opt.rr_kill_prob);
    }
  }

  if (continue_trace)
  {
    scalar brdf_p = 0;
    scalar brdf_reflectance;
    Vec3 brdf_dir = isect.sample_bsdf(ray_dir_origin, sampler,
                                      brdf_p, brdf_reflectance);

    scalar nl = fabs(brdf_dir.dot(isect.normal));// max<scalar>(brdf_dir.dot(isect.normal), 0);
    if (brdf_p > 0 && nl > 0)
    {
      total += trace_ray(scene, Ray{isect.position, brdf_dir}.nudge(),
                         sampler, depth + 1) *
        spectrum{p_mult / brdf_p * nl * brdf_reflectance};
    }
  }

  return total * isect.texture_at_point();
}

void PathTracerIntegrator::render_thread(TaskQueue& queue, const Camera* cam,
                                         const Scene* scene, shared_ptr<Film> film) const
{
  auto sampler = make_shared<UniformSampler>();

  while (true)
  {
    Task task;

    {
      lock_guard<mutex> lock(render_queue_mutex);
      if (queue.empty())
        break;
      task = queue.front();
      queue.pop();
    }

    if (task.samples_per_pixel == 0)
      break;

    for (uint x = 0; x < task.rect.width; ++x)
    {
      for (uint y = 0; y < task.rect.height; ++y)
      {
        for (uint d = 0; d < task.samples_per_pixel; ++d)
        {
          int px = x + task.rect.x;
          int py = y + task.rect.y;

          PixelSample ps = cam->sample_pixel(*film, px, py, *sampler);

          spectrum s = trace_ray(scene, ps.ray, *sampler, 1);

          film->add_sample(ps, s);
        }
      }
    }
  }
}

<commit_msg>Removes dot(v, n) filter from direct lighting in path tracer<commit_after>#include "path_tracer.h"
#include "util.h"
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <memory>

using std::cerr;
using std::queue;
using std::mutex;
using std::lock_guard;
using std::make_shared;
using std::shared_ptr;
using std::thread;

PathTracerIntegrator::Options::Options()
  : russian_roulette(true), rr_kill_prob(0.1), min_rr_depth(4),
    max_depth(10), samples_per_pixel(16), num_threads(1)
{
  assert( 0.0 <= rr_kill_prob && rr_kill_prob <= 1.0 );
}

PathTracerIntegrator::PathTracerIntegrator(const PathTracerIntegrator::Options& opt_)
  : rays_traced(0), primary_rays_traced(0), opt(opt_)
{
}

void PathTracerIntegrator::render(const Camera* cam, const Scene* scene, Film& film)
{
  int num_threads = opt.num_threads;
  if (num_threads == 0)
  {
    num_threads = num_system_procs();
  }

  TaskQueue queue;

  if (num_threads == 1)
  {
    queue.emplace(Film::Rect{0, 0, film.width, film.height}, opt.samples_per_pixel);
    auto temp_film = make_shared<Film>(film.width, film.height, film.filter);
    render_thread(queue, cam, scene, temp_film);
    film.merge( *temp_film.get() );
    return;
  }

  const uint PER_SIDE = 2;
  const int SAMPLES_PER_TASK = 16;

  int samples_left = opt.samples_per_pixel;

  // Populate the task queue.
  while (samples_left > 0)
  {
    int task_samples = min(samples_left, SAMPLES_PER_TASK);
    samples_left -= SAMPLES_PER_TASK;
    for (uint i = 0; i < PER_SIDE; ++i)
    {
      uint x = film.width * i / PER_SIDE;
      uint w = film.width * (i+1) / PER_SIDE - film.width * i / PER_SIDE;

      for (uint j = 0; j < PER_SIDE; ++j)
      {
        uint y = film.height * j / PER_SIDE;
        uint h = film.height * (j+1) / PER_SIDE - film.height * j / PER_SIDE;

        queue.emplace(Film::Rect{x, y, w, h}, static_cast<uint>(task_samples));
      }
    }
  }

  // Create adn run the threads.
  vector<shared_ptr<Film>> films;
  vector<thread> threads;
  for (int i = 0; i < num_threads; ++i)
  {
    films.push_back(make_shared<Film>(film.width, film.height, film.filter));
    threads.push_back(thread(&PathTracerIntegrator::render_thread,
                             this, std::ref(queue), cam, scene, films[i]));
  }

  // Merge and join the results.
  for (auto& th: threads)
    th.join();

  for (const auto& f: films)
    film.merge(*f.get());
}

spectrum PathTracerIntegrator::trace_ray(const Scene* scene, const Ray& ray,
                                         Sampler& sampler, int depth) const
{
  ++rays_traced;
  if (depth == 1)
    ++primary_rays_traced;

  Intersection isect = scene->intersect(ray);
  const Vec3 ray_dir_origin = -ray.direction.normal();
  if (!isect.valid())
    return scene->environment_light_emission(-ray_dir_origin);
  if (isect.is_emissive())
    return isect.emission();

  // direct lighting: randomly choose a light or emissive shape, and contribute
  // the light from that shape if appropriate
  scalar light_prob;
  const Light* light = scene->sample_light(sampler.sample_1d(), light_prob);

  spectrum total(0);

  if (light_prob > 0)
  {
    LightSample ls = light->sample_emission(isect, sampler);
    if (ls)
    {
      if (!ls.is_occluded(scene))
      {
        scalar NL = max<scalar>(ls.direction().dot(isect.normal), 0.0);
        scalar ca = isect.reflectance(ls.direction(), ray_dir_origin);

        auto light_contrib = ls.emission() * spectrum{NL * ca / light_prob};
        total += light_contrib;
      }
    }
  }

  // Decide whether or not to continue trace and, if so, what the multiplier
  // should be.
  bool continue_trace = true;
  scalar p_mult = 1.0;
  if (opt.max_depth > 0 && depth >= opt.max_depth)
    continue_trace = false;
  else if (opt.russian_roulette && depth >= opt.min_rr_depth)
  {
    if (sampler.sample_1d() < opt.rr_kill_prob)
    {
      continue_trace = false;
    }
    else
    {
      p_mult /= (1 - opt.rr_kill_prob);
    }
  }

  if (continue_trace)
  {
    scalar brdf_p = 0;
    scalar brdf_reflectance;
    Vec3 brdf_dir = isect.sample_bsdf(ray_dir_origin, sampler,
                                      brdf_p, brdf_reflectance);

    scalar nl = fabs(brdf_dir.dot(isect.normal));// max<scalar>(brdf_dir.dot(isect.normal), 0);
    if (brdf_p > 0 && nl > 0)
    {
      total += trace_ray(scene, Ray{isect.position, brdf_dir}.nudge(),
                         sampler, depth + 1) *
        spectrum{p_mult / brdf_p * nl * brdf_reflectance};
    }
  }

  return total * isect.texture_at_point();
}

void PathTracerIntegrator::render_thread(TaskQueue& queue, const Camera* cam,
                                         const Scene* scene, shared_ptr<Film> film) const
{
  auto sampler = make_shared<UniformSampler>();

  while (true)
  {
    Task task;

    {
      lock_guard<mutex> lock(render_queue_mutex);
      if (queue.empty())
        break;
      task = queue.front();
      queue.pop();
    }

    if (task.samples_per_pixel == 0)
      break;

    for (uint x = 0; x < task.rect.width; ++x)
    {
      for (uint y = 0; y < task.rect.height; ++y)
      {
        for (uint d = 0; d < task.samples_per_pixel; ++d)
        {
          int px = x + task.rect.x;
          int py = y + task.rect.y;

          PixelSample ps = cam->sample_pixel(*film, px, py, *sampler);

          spectrum s = trace_ray(scene, ps.ray, *sampler, 1);

          film->add_sample(ps, s);
        }
      }
    }
  }
}

<|endoftext|>


<commit_before><commit_msg>pdn: correct debug statement in via sort<commit_after><|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2010 Miklos Vajna.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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 _CPPUHELPER_IMPLEMENTATIONENTRY_
#include <cppuhelper/implementationentry.hxx>
#endif
#include <osl/module.hxx>
#include <tools/solar.h>
#include <RtfFilter.hxx>
#include <comphelper/mediadescriptor.hxx>
#include <dmapper/DomainMapper.hxx>
#include <rtftok/RTFDocument.hxx>
#include <com/sun/star/frame/XFrame.hpp>
#include <svtools/miscopt.hxx>

using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star;
using ::comphelper::MediaDescriptor;

RtfFilter::RtfFilter( const uno::Reference< uno::XComponentContext >& rxContext)  :
    m_xContext( rxContext )
{
}

RtfFilter::~RtfFilter()
{
}

sal_Bool RtfFilter::filter( const uno::Sequence< beans::PropertyValue >& aDescriptor )
   throw (uno::RuntimeException)
{
    OSL_TRACE("%s", OSL_THIS_FUNC);
    if( m_xSrcDoc.is() )
    {
        uno::Reference< lang::XMultiServiceFactory > xMSF(m_xContext->getServiceManager(), uno::UNO_QUERY_THROW);
        uno::Reference< uno::XInterface > xIfc( xMSF->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.RtfExport" ))), uno::UNO_QUERY_THROW);
        if (!xIfc.is())
            return sal_False;
        uno::Reference< document::XExporter > xExprtr(xIfc, uno::UNO_QUERY_THROW);
        uno::Reference< document::XFilter > xFltr(xIfc, uno::UNO_QUERY_THROW);
        if (!xExprtr.is() || !xFltr.is())
            return sal_False;
        xExprtr->setSourceDocument(m_xSrcDoc);
        return xFltr->filter(aDescriptor);
    }

    SvtMiscOptions aMiscOptions;
    if (aMiscOptions.IsExperimentalMode())
    {
        MediaDescriptor aMediaDesc( aDescriptor );
#ifdef DEBUG_IMPORT
        OUString sURL = aMediaDesc.getUnpackedValueOrDefault( MediaDescriptor::PROP_URL(), OUString() );
        ::std::string sURLc = OUStringToOString(sURL, RTL_TEXTENCODING_ASCII_US).getStr();

        writerfilter::TagLogger::Pointer_t dmapperLogger
            (writerfilter::TagLogger::getInstance("DOMAINMAPPER"));
        dmapperLogger->setFileName(sURLc);
        dmapperLogger->startDocument();
#endif
        uno::Reference< io::XInputStream > xInputStream;

        aMediaDesc.addInputStream();
        aMediaDesc[ MediaDescriptor::PROP_INPUTSTREAM() ] >>= xInputStream;

        uno::Reference<frame::XFrame> xFrame = aMediaDesc.getUnpackedValueOrDefault(MediaDescriptor::PROP_FRAME(),
                uno::Reference<frame::XFrame>());

        writerfilter::Stream::Pointer_t pStream(
                new writerfilter::dmapper::DomainMapper(m_xContext, xInputStream, m_xDstDoc, writerfilter::dmapper::DOCUMENT_RTF));
        writerfilter::rtftok::RTFDocument::Pointer_t const pDocument(
                writerfilter::rtftok::RTFDocumentFactory::createDocument(m_xContext, xInputStream, m_xDstDoc, xFrame));
        pDocument->resolve(*pStream);
#ifdef DEBUG_IMPORT
        dmapperLogger->endDocument();
#endif
        return sal_True;
    }

    // if not, then use the old importer
    uno::Reference< lang::XMultiServiceFactory > xMSF(m_xContext->getServiceManager(), uno::UNO_QUERY_THROW);
    uno::Reference< uno::XInterface > xIfc( xMSF->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.RtfImport" ))), uno::UNO_QUERY_THROW);
    if (!xIfc.is())
        return sal_False;
    uno::Reference< document::XImporter > xImprtr(xIfc, uno::UNO_QUERY_THROW);
    uno::Reference< document::XFilter > xFltr(xIfc, uno::UNO_QUERY_THROW);
    if (!xImprtr.is() || !xFltr.is())
        return sal_False;
    xImprtr->setTargetDocument(m_xDstDoc);
    return xFltr->filter(aDescriptor);
}

void RtfFilter::cancel(  ) throw (uno::RuntimeException)
{
}

void RtfFilter::setSourceDocument( const uno::Reference< lang::XComponent >& xDoc )
   throw (lang::IllegalArgumentException, uno::RuntimeException)
{
   m_xSrcDoc = xDoc;
}

void RtfFilter::setTargetDocument( const uno::Reference< lang::XComponent >& xDoc )
   throw (lang::IllegalArgumentException, uno::RuntimeException)
{
   m_xDstDoc = xDoc;
}

void RtfFilter::initialize( const uno::Sequence< uno::Any >& /*aArguments*/ ) throw (uno::Exception, uno::RuntimeException)
{
    // The DOCX exporter here extracts 'type' of the filter, ie 'Word' or
    // 'Word Template' but we don't need it for RTF.
}

OUString RtfFilter::getImplementationName(  ) throw (uno::RuntimeException)
{
   return RtfFilter_getImplementationName();
}

#define SERVICE_NAME1 "com.sun.star.document.ImportFilter"
#define SERVICE_NAME2 "com.sun.star.document.ExportFilter"
sal_Bool RtfFilter::supportsService( const OUString& rServiceName ) throw (uno::RuntimeException)
{
    return (rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ) ||
            rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME2 ) ));
}

uno::Sequence< OUString > RtfFilter::getSupportedServiceNames(  ) throw (uno::RuntimeException)
{
    return RtfFilter_getSupportedServiceNames();
}

/* Helpers, used by shared lib exports. */

OUString RtfFilter_getImplementationName () throw (uno::RuntimeException)
{
   return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.RtfFilter" ) );
}

uno::Sequence< OUString > RtfFilter_getSupportedServiceNames(  ) throw (uno::RuntimeException)
{
   uno::Sequence < OUString > aRet(2);
   OUString* pArray = aRet.getArray();
   pArray[0] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) );
   pArray[1] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME2 ) );
   return aRet;
}
#undef SERVICE_NAME1
#undef SERVICE_NAME2

uno::Reference< uno::XInterface > RtfFilter_createInstance( const uno::Reference< uno::XComponentContext >& xContext)
                throw( uno::Exception )
{
   return (cppu::OWeakObject*) new RtfFilter( xContext );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>the old filter does not support parsing without a destination document<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2010 Miklos Vajna.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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 _CPPUHELPER_IMPLEMENTATIONENTRY_
#include <cppuhelper/implementationentry.hxx>
#endif
#include <osl/module.hxx>
#include <tools/solar.h>
#include <RtfFilter.hxx>
#include <comphelper/mediadescriptor.hxx>
#include <dmapper/DomainMapper.hxx>
#include <rtftok/RTFDocument.hxx>
#include <com/sun/star/frame/XFrame.hpp>
#include <svtools/miscopt.hxx>

using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star;
using ::comphelper::MediaDescriptor;

RtfFilter::RtfFilter( const uno::Reference< uno::XComponentContext >& rxContext)  :
    m_xContext( rxContext )
{
}

RtfFilter::~RtfFilter()
{
}

sal_Bool RtfFilter::filter( const uno::Sequence< beans::PropertyValue >& aDescriptor )
   throw (uno::RuntimeException)
{
    OSL_TRACE("%s", OSL_THIS_FUNC);
    if( m_xSrcDoc.is() )
    {
        uno::Reference< lang::XMultiServiceFactory > xMSF(m_xContext->getServiceManager(), uno::UNO_QUERY_THROW);
        uno::Reference< uno::XInterface > xIfc( xMSF->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.RtfExport" ))), uno::UNO_QUERY_THROW);
        if (!xIfc.is())
            return sal_False;
        uno::Reference< document::XExporter > xExprtr(xIfc, uno::UNO_QUERY_THROW);
        uno::Reference< document::XFilter > xFltr(xIfc, uno::UNO_QUERY_THROW);
        if (!xExprtr.is() || !xFltr.is())
            return sal_False;
        xExprtr->setSourceDocument(m_xSrcDoc);
        return xFltr->filter(aDescriptor);
    }

    SvtMiscOptions aMiscOptions;
    if (aMiscOptions.IsExperimentalMode() || !m_xDstDoc.is() )
    {
        MediaDescriptor aMediaDesc( aDescriptor );
#ifdef DEBUG_IMPORT
        OUString sURL = aMediaDesc.getUnpackedValueOrDefault( MediaDescriptor::PROP_URL(), OUString() );
        ::std::string sURLc = OUStringToOString(sURL, RTL_TEXTENCODING_ASCII_US).getStr();

        writerfilter::TagLogger::Pointer_t dmapperLogger
            (writerfilter::TagLogger::getInstance("DOMAINMAPPER"));
        dmapperLogger->setFileName(sURLc);
        dmapperLogger->startDocument();
#endif
        uno::Reference< io::XInputStream > xInputStream;

        aMediaDesc.addInputStream();
        aMediaDesc[ MediaDescriptor::PROP_INPUTSTREAM() ] >>= xInputStream;

        uno::Reference<frame::XFrame> xFrame = aMediaDesc.getUnpackedValueOrDefault(MediaDescriptor::PROP_FRAME(),
                uno::Reference<frame::XFrame>());

        writerfilter::Stream::Pointer_t pStream(
                new writerfilter::dmapper::DomainMapper(m_xContext, xInputStream, m_xDstDoc, writerfilter::dmapper::DOCUMENT_RTF));
        writerfilter::rtftok::RTFDocument::Pointer_t const pDocument(
                writerfilter::rtftok::RTFDocumentFactory::createDocument(m_xContext, xInputStream, m_xDstDoc, xFrame));
        pDocument->resolve(*pStream);
#ifdef DEBUG_IMPORT
        dmapperLogger->endDocument();
#endif
        return sal_True;
    }

    // if not, then use the old importer
    uno::Reference< lang::XMultiServiceFactory > xMSF(m_xContext->getServiceManager(), uno::UNO_QUERY_THROW);
    uno::Reference< uno::XInterface > xIfc( xMSF->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.RtfImport" ))), uno::UNO_QUERY_THROW);
    if (!xIfc.is())
        return sal_False;
    uno::Reference< document::XImporter > xImprtr(xIfc, uno::UNO_QUERY_THROW);
    uno::Reference< document::XFilter > xFltr(xIfc, uno::UNO_QUERY_THROW);
    if (!xImprtr.is() || !xFltr.is())
        return sal_False;
    xImprtr->setTargetDocument(m_xDstDoc);
    return xFltr->filter(aDescriptor);
}

void RtfFilter::cancel(  ) throw (uno::RuntimeException)
{
}

void RtfFilter::setSourceDocument( const uno::Reference< lang::XComponent >& xDoc )
   throw (lang::IllegalArgumentException, uno::RuntimeException)
{
   m_xSrcDoc = xDoc;
}

void RtfFilter::setTargetDocument( const uno::Reference< lang::XComponent >& xDoc )
   throw (lang::IllegalArgumentException, uno::RuntimeException)
{
   m_xDstDoc = xDoc;
}

void RtfFilter::initialize( const uno::Sequence< uno::Any >& /*aArguments*/ ) throw (uno::Exception, uno::RuntimeException)
{
    // The DOCX exporter here extracts 'type' of the filter, ie 'Word' or
    // 'Word Template' but we don't need it for RTF.
}

OUString RtfFilter::getImplementationName(  ) throw (uno::RuntimeException)
{
   return RtfFilter_getImplementationName();
}

#define SERVICE_NAME1 "com.sun.star.document.ImportFilter"
#define SERVICE_NAME2 "com.sun.star.document.ExportFilter"
sal_Bool RtfFilter::supportsService( const OUString& rServiceName ) throw (uno::RuntimeException)
{
    return (rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ) ||
            rServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME2 ) ));
}

uno::Sequence< OUString > RtfFilter::getSupportedServiceNames(  ) throw (uno::RuntimeException)
{
    return RtfFilter_getSupportedServiceNames();
}

/* Helpers, used by shared lib exports. */

OUString RtfFilter_getImplementationName () throw (uno::RuntimeException)
{
   return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.RtfFilter" ) );
}

uno::Sequence< OUString > RtfFilter_getSupportedServiceNames(  ) throw (uno::RuntimeException)
{
   uno::Sequence < OUString > aRet(2);
   OUString* pArray = aRet.getArray();
   pArray[0] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) );
   pArray[1] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME2 ) );
   return aRet;
}
#undef SERVICE_NAME1
#undef SERVICE_NAME2

uno::Reference< uno::XInterface > RtfFilter_createInstance( const uno::Reference< uno::XComponentContext >& xContext)
                throw( uno::Exception )
{
   return (cppu::OWeakObject*) new RtfFilter( xContext );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


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

#ifdef PRECOMPILED
#include "filt_pch.hxx"
#endif

#pragma hdrstop

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _XMLOFF_XMLKYWD_HXX
#include <xmloff/xmlkywd.hxx>
#endif

#ifndef _SFXDOCFILE_HXX //autogen wg. SfxMedium
#include <sfx2/docfile.hxx>
#endif
#ifndef _PAM_HXX //autogen wg. SwPaM
#include <pam.hxx>
#endif
#ifndef _DOC_HXX //autogen wg. SwDoc
#include <doc.hxx>
#endif
#ifndef _DOCSH_HXX //autogen wg. SwDoc
#include <docsh.hxx>
#endif

#ifndef _ERRHDL_HXX //autogen wg. ASSERT
#include <errhdl.hxx>
#endif
#ifndef _SWSWERROR_H
#include <swerror.h>
#endif
#ifndef _WRTXML_HXX
#include <wrtxml.hxx>
#endif
#ifndef _XMLEXP_HXX
#include <xmlexp.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

SwXMLWriter::SwXMLWriter()
{
}

__EXPORT SwXMLWriter::~SwXMLWriter()
{
}

sal_uInt32 SwXMLWriter::WriteStream()
{
    ASSERT( !this, "SwXMLWriter::WriteStream: use Write!" );

    return ERR_SWG_WRITE_ERROR;
}

sal_uInt32 SwXMLWriter::Write( SwPaM& rPaM, SfxMedium& rMed,
                               const String* pFileName )
{
    Reference< lang::XMultiServiceFactory > xServiceFactory =
            comphelper::getProcessServiceFactory();
    ASSERT( xServiceFactory.is(),
            "SwXMLWriter::Write: got no service manager" );
    if( !xServiceFactory.is() )
        return ERR_SWG_WRITE_ERROR;

    Reference< XInterface > xWriter = xServiceFactory->createInstance(
            OUString::createFromAscii("com.sun.star.xml.sax.Writer") );
    ASSERT( xWriter.is(),
            "SwXMLWriter::Write: com.sun.star.xml.sax.Writer service missing" );
    if(!xWriter.is())
        return ERR_SWG_WRITE_ERROR;

    Reference< frame::XModel > xModel = rPaM.GetDoc()->GetDocShell()->GetModel();
    ASSERT( xModel.is(),
            "XMLWriter::Write: got no model" );
    if( !xModel.is() )
        return ERR_SWG_WRITE_ERROR;

    pDoc = rPaM.GetDoc();
//  PutNumFmtFontsInAttrPool();
//  PutEditEngFontsInAttrPool();

    Reference< io::XOutputStream > xOut = rMed.GetDataSink();
    Reference< io::XActiveDataSource > xSrc( xWriter, UNO_QUERY );
    xSrc->setOutputStream( xOut );

    Reference< xml::sax::XDocumentHandler > xHandler( xWriter, UNO_QUERY );

    SwXMLExport *pExp = new SwXMLExport( xModel, rPaM, *pFileName, xHandler,
                                         bWriteAll, bWriteOnlyFirstTable,
                                         bShowProgress );

    sal_uInt32 nRet = pExp->exportDoc( sXML_text );

    delete pExp;

    ResetWriter();

    return nRet;
}

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

void GetXMLWriter( const String&, WriterRef& xRet )
{
    xRet = new SwXMLWriter;
}

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

/*************************************************************************

      Source Code Control System - Header

      $Header: /zpool/svn/migration/cvs_rep_09_09_08/code/sw/source/filter/xml/wrtxml.cxx,v 1.4 2000-11-20 09:18:37 jp Exp $

      Source Code Control System - Update

      $Log: not supported by cvs2svn $
      Revision 1.3  2000/11/14 08:03:32  mib
      Adding of EditEngine- and Bullet-Font-Items temporarily removed

      Revision 1.2  2000/11/13 08:44:24  mib
      font declarations and asian/complex font properties

      Revision 1.1.1.1  2000/09/18 17:14:59  hr
      initial import

      Revision 1.17  2000/09/18 16:05:04  willem.vandorp
      OpenOffice header added.

      Revision 1.16  2000/07/21 12:55:15  mib
      text import/export using StarOffice API

      Revision 1.15  2000/06/08 09:45:54  aw
      changed to use functionality from xmloff project now

      Revision 1.14  2000/05/03 12:08:05  mib
      unicode

      Revision 1.13  2000/03/21 15:10:56  os
      UNOIII

      Revision 1.12  2000/03/13 14:33:44  mib
      UNO3

      Revision 1.11  2000/03/03 16:07:54  pl
      #73771# workaround for c50 intel compiler

      Revision 1.10  2000/02/11 14:40:52  hr
      #70473# changes for unicode ( patched by automated patchtool )

      Revision 1.9  1999/11/26 11:09:47  mib
      progress, export-flags

      Revision 1.8  1999/11/19 16:40:21  os
      modules renamed

      Revision 1.7  1999/10/26 13:34:30  mib
      removed 'using namespace' from header files

      Revision 1.6  1999/10/25 10:41:48  mib
      Using new OUString ASCII methods

      Revision 1.5  1999/10/15 14:48:25  hr
      export() -> exportDoc()

      Revision 1.4  1999/10/15 12:36:39  mib
      added document class attribute

      Revision 1.3  1999/10/08 11:47:06  mib
      moved some file to SVTOOLS/SVX

      Revision 1.2  1999/09/22 11:56:36  mib
      string -> wstring

      Revision 1.1  1999/08/12 10:28:26  MIB
      Initial revision.

      Rev 1.0   12 Aug 1999 12:28:26   MIB
   Initial revision.

*************************************************************************/

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

#ifdef PRECOMPILED
#include "filt_pch.hxx"
#endif

#pragma hdrstop

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _XMLOFF_XMLKYWD_HXX
#include <xmloff/xmlkywd.hxx>
#endif

#ifndef _SFXDOCFILE_HXX //autogen wg. SfxMedium
#include <sfx2/docfile.hxx>
#endif
#ifndef _PAM_HXX //autogen wg. SwPaM
#include <pam.hxx>
#endif
#ifndef _DOC_HXX //autogen wg. SwDoc
#include <doc.hxx>
#endif
#ifndef _DOCSH_HXX //autogen wg. SwDoc
#include <docsh.hxx>
#endif

#ifndef _ERRHDL_HXX //autogen wg. ASSERT
#include <errhdl.hxx>
#endif
#ifndef _SWSWERROR_H
#include <swerror.h>
#endif
#ifndef _WRTXML_HXX
#include <wrtxml.hxx>
#endif
#ifndef _XMLEXP_HXX
#include <xmlexp.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

SwXMLWriter::SwXMLWriter()
{
}

__EXPORT SwXMLWriter::~SwXMLWriter()
{
}

sal_uInt32 SwXMLWriter::WriteStream()
{
    ASSERT( !this, "SwXMLWriter::WriteStream: use Write!" );

    return ERR_SWG_WRITE_ERROR;
}

sal_uInt32 SwXMLWriter::Write( SwPaM& rPaM, SfxMedium& rMed,
                               const String* pFileName )
{
    Reference< lang::XMultiServiceFactory > xServiceFactory =
            comphelper::getProcessServiceFactory();
    ASSERT( xServiceFactory.is(),
            "SwXMLWriter::Write: got no service manager" );
    if( !xServiceFactory.is() )
        return ERR_SWG_WRITE_ERROR;

    Reference< XInterface > xWriter = xServiceFactory->createInstance(
            OUString::createFromAscii("com.sun.star.xml.sax.Writer") );
    ASSERT( xWriter.is(),
            "SwXMLWriter::Write: com.sun.star.xml.sax.Writer service missing" );
    if(!xWriter.is())
        return ERR_SWG_WRITE_ERROR;

    Reference< frame::XModel > xModel = rPaM.GetDoc()->GetDocShell()->GetModel();
    ASSERT( xModel.is(),
            "XMLWriter::Write: got no model" );
    if( !xModel.is() )
        return ERR_SWG_WRITE_ERROR;

    pDoc = rPaM.GetDoc();
    PutNumFmtFontsInAttrPool();
    PutEditEngFontsInAttrPool();

    Reference< io::XOutputStream > xOut = rMed.GetDataSink();
    Reference< io::XActiveDataSource > xSrc( xWriter, UNO_QUERY );
    xSrc->setOutputStream( xOut );

    Reference< xml::sax::XDocumentHandler > xHandler( xWriter, UNO_QUERY );

    SwXMLExport *pExp = new SwXMLExport( xModel, rPaM, *pFileName, xHandler,
                                         bWriteAll, bWriteOnlyFirstTable,
                                         bShowProgress );

    sal_uInt32 nRet = pExp->exportDoc( sXML_text );

    delete pExp;

    ResetWriter();

    return nRet;
}

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

void GetXMLWriter( const String&, WriterRef& xRet )
{
    xRet = new SwXMLWriter;
}

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

/*************************************************************************

      Source Code Control System - Header

      $Header: /zpool/svn/migration/cvs_rep_09_09_08/code/sw/source/filter/xml/wrtxml.cxx,v 1.5 2000-11-20 11:17:53 mib Exp $

      Source Code Control System - Update

      $Log: not supported by cvs2svn $
      Revision 1.4  2000/11/20 09:18:37  jp
      must change: processfactory moved

      Revision 1.3  2000/11/14 08:03:32  mib
      Adding of EditEngine- and Bullet-Font-Items temporarily removed

      Revision 1.2  2000/11/13 08:44:24  mib
      font declarations and asian/complex font properties

      Revision 1.1.1.1  2000/09/18 17:14:59  hr
      initial import

      Revision 1.17  2000/09/18 16:05:04  willem.vandorp
      OpenOffice header added.

      Revision 1.16  2000/07/21 12:55:15  mib
      text import/export using StarOffice API

      Revision 1.15  2000/06/08 09:45:54  aw
      changed to use functionality from xmloff project now

      Revision 1.14  2000/05/03 12:08:05  mib
      unicode

      Revision 1.13  2000/03/21 15:10:56  os
      UNOIII

      Revision 1.12  2000/03/13 14:33:44  mib
      UNO3

      Revision 1.11  2000/03/03 16:07:54  pl
      #73771# workaround for c50 intel compiler

      Revision 1.10  2000/02/11 14:40:52  hr
      #70473# changes for unicode ( patched by automated patchtool )

      Revision 1.9  1999/11/26 11:09:47  mib
      progress, export-flags

      Revision 1.8  1999/11/19 16:40:21  os
      modules renamed

      Revision 1.7  1999/10/26 13:34:30  mib
      removed 'using namespace' from header files

      Revision 1.6  1999/10/25 10:41:48  mib
      Using new OUString ASCII methods

      Revision 1.5  1999/10/15 14:48:25  hr
      export() -> exportDoc()

      Revision 1.4  1999/10/15 12:36:39  mib
      added document class attribute

      Revision 1.3  1999/10/08 11:47:06  mib
      moved some file to SVTOOLS/SVX

      Revision 1.2  1999/09/22 11:56:36  mib
      string -> wstring

      Revision 1.1  1999/08/12 10:28:26  MIB
      Initial revision.

      Rev 1.0   12 Aug 1999 12:28:26   MIB
   Initial revision.

*************************************************************************/

<|endoftext|>


<commit_before>#ifndef SRC_PORTS_PORTS_HPP_
#define SRC_PORTS_PORTS_HPP_

#include "event_ports.hpp"
#include "stream_ports.hpp"

#include "core/connection.hpp"

namespace fc
{

/**
 * \brief contains connections of streams during creation.
 *
 * stream_proxy is used to store the intermediate objects created,
 * when a connection of streams is build up.
 * Until the stream source is connected to a proper stream_sink,
 * the connection is not complete and no value can be pulled through.
 * Nonetheless, the connection needs to be stored to allow further connections.
 * the stream_storage stores these temporary objects.
 *
 *
 * \tparam source_t the source of the connection, either a connectable or a stream_source
 * \tparam sink_t the stream_sink, which serves as the active part of the connection.
 *
 * ToDo merge this with the expected code duplication, when we make the proxy for events.
 */
template<class source_t, class sink_t>
struct stream_proxy
{
	stream_proxy(source_t source, sink_t sink_) :
			stored_source(source), sink(sink_)
	{
	}

	/**
	 * \brief connects a connectable, which is not a source_port to the stream_proxy.
	 *
	 * connects the new_source to the current stored source
	 *
	 * \pre new_source_t needs to be connectable
	 * \post new_source is connected to the old source.
	 * \returns a stream_proxy, which contains the new_source as the source.
	 */
	template<class new_source_t, class = typename std::enable_if<
	        !is_stream_source<new_source_t>::value>::type>
	auto connect(new_source_t new_source)
	{
		auto connection = fc::connect(new_source, stored_source);
		return stream_proxy<decltype(connection), sink_t>(connection, sink);
	}

	/**
	 * \brief connects a source_port to the stream_proxy.
	 *
	 * connects the new_source to the current stored source
	 * then connects this connection to the sink which completes the connection
	 *
	 * \pre new_source_t needs to a source_port
	 * \post new_source is now connected to sink via the connection stored in the proxy.
	 * \returns nothing, the connection is complete now
	 */
	template<class new_source_t, class enable = void>
	typename std::enable_if<is_stream_source<new_source_t>::value, void>::type
	connect(new_source_t new_source)
	{
		auto tmp = fc::connect(new_source, stored_source);
		sink.connect(tmp);
		return;
	}

	source_t stored_source;
	//access to connect method of sink port
	sink_t sink;
};

namespace detail
{

template<class T>
struct is_stream_proxy: std::false_type
{
};

template<class source_t, class sink_t>
struct is_stream_proxy<fc::stream_proxy<source_t, sink_t>> : std::true_type
{
};

/// Specialization of connect to call member connect of stream_proxy.
template<class sink_t, class source_t>
struct connect_impl<sink_t, source_t,
        typename std::enable_if<is_stream_proxy<sink_t>::value>::type>
{
	auto operator()(source_t source, sink_t sink)
	{
		return sink.connect(source);
	}
};

}  // namespace detail
}  // namespace fc

#endif /* SRC_PORTS_PORTS_HPP_ */
<commit_msg>Fix comment for stream_ports in ports.hpp.<commit_after>#ifndef SRC_PORTS_PORTS_HPP_
#define SRC_PORTS_PORTS_HPP_

#include "event_ports.hpp"
#include "stream_ports.hpp"

#include "core/connection.hpp"

namespace fc
{

/**
 * \brief contains connections of streams during creation.
 *
 * stream_proxy is used to store the intermediate objects created,
 * when a connection of streams is build up.
 * Until the stream source is connected to a proper stream_sink,
 * the connection is not complete and no value can be pulled through.
 * Nonetheless, the connection needs to be stored to allow further connections.
 * the stream_proxy stores these temporary objects.
 *
 *
 * \tparam source_t the source of the connection, either a connectable or a stream_source
 * \tparam sink_t the stream_sink, which serves as the active part of the connection.
 *
 * ToDo merge this with the expected code duplication, when we make the proxy for events.
 */
template<class source_t, class sink_t>
struct stream_proxy
{
	stream_proxy(source_t source, sink_t sink_) :
			stored_source(source), sink(sink_)
	{
	}

	/**
	 * \brief connects a connectable, which is not a source_port to the stream_proxy.
	 *
	 * connects the new_source to the current stored source
	 *
	 * \pre new_source_t needs to be connectable
	 * \post new_source is connected to the old source.
	 * \returns a stream_proxy, which contains the new_source as the source.
	 */
	template<class new_source_t, class = typename std::enable_if<
	        !is_stream_source<new_source_t>::value>::type>
	auto connect(new_source_t new_source)
	{
		auto connection = fc::connect(new_source, stored_source);
		return stream_proxy<decltype(connection), sink_t>(connection, sink);
	}

	/**
	 * \brief connects a source_port to the stream_proxy.
	 *
	 * connects the new_source to the current stored source
	 * then connects this connection to the sink which completes the connection
	 *
	 * \pre new_source_t needs to a source_port
	 * \post new_source is now connected to sink via the connection stored in the proxy.
	 * \returns nothing, the connection is complete now
	 */
	template<class new_source_t, class enable = void>
	typename std::enable_if<is_stream_source<new_source_t>::value, void>::type
	connect(new_source_t new_source)
	{
		auto tmp = fc::connect(new_source, stored_source);
		sink.connect(tmp);
		return;
	}

	source_t stored_source;
	//access to connect method of sink port
	sink_t sink;
};

namespace detail
{

template<class T>
struct is_stream_proxy: std::false_type
{
};

template<class source_t, class sink_t>
struct is_stream_proxy<fc::stream_proxy<source_t, sink_t>> : std::true_type
{
};

/// Specialization of connect to call member connect of stream_proxy.
template<class sink_t, class source_t>
struct connect_impl<sink_t, source_t,
        typename std::enable_if<is_stream_proxy<sink_t>::value>::type>
{
	auto operator()(source_t source, sink_t sink)
	{
		return sink.connect(source);
	}
};

}  // namespace detail
}  // namespace fc

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


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

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#pragma hdrstop

//CHINA001 #ifndef _SVX_BACKGRND_HXX //autogen
//CHINA001 #include <svx/backgrnd.hxx>
//CHINA001 #endif
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001
#include "swtypes.hxx"
#include "pattern.hxx"
#include "frmui.hrc"

/****************************************************************************
Ctor
****************************************************************************/

SwBackgroundDlg::SwBackgroundDlg(Window* pParent, const SfxItemSet& rSet) :

    SfxSingleTabDialog(pParent, rSet, 0)

{
    SetText(SW_RESSTR(STR_FRMUI_PATTERN));
    //CHINA001 SetTabPage(SvxBackgroundTabPage::Create(this, rSet));
    SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
    DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
    ::CreateTabPage fnCreatePage = pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND );
    if ( fnCreatePage )
    {
        SfxTabPage* pPage = (*fnCreatePage)( this, rSet );
        SetTabPage(pPage);
    }

}

/****************************************************************************
Dtor
****************************************************************************/

SwBackgroundDlg::~SwBackgroundDlg()
{
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.5.596); FILE MERGED 2005/09/05 13:44:50 rt 1.5.596.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pattern.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 07:54:00 $
 *
 *  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
 *
 ************************************************************************/

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#pragma hdrstop

//CHINA001 #ifndef _SVX_BACKGRND_HXX //autogen
//CHINA001 #include <svx/backgrnd.hxx>
//CHINA001 #endif
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001
#include "swtypes.hxx"
#include "pattern.hxx"
#include "frmui.hrc"

/****************************************************************************
Ctor
****************************************************************************/

SwBackgroundDlg::SwBackgroundDlg(Window* pParent, const SfxItemSet& rSet) :

    SfxSingleTabDialog(pParent, rSet, 0)

{
    SetText(SW_RESSTR(STR_FRMUI_PATTERN));
    //CHINA001 SetTabPage(SvxBackgroundTabPage::Create(this, rSet));
    SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
    DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
    ::CreateTabPage fnCreatePage = pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND );
    if ( fnCreatePage )
    {
        SfxTabPage* pPage = (*fnCreatePage)( this, rSet );
        SetTabPage(pPage);
    }

}

/****************************************************************************
Dtor
****************************************************************************/

SwBackgroundDlg::~SwBackgroundDlg()
{
}

<|endoftext|>


<commit_before>/*
 * ============================================================================
 *
 *       Filename:  trimmit.cc
 *    Description:  Just merges and quality trims interleaved reads.
 *        License:  LGPL-3+
 *         Author:  Kevin Murray, spam@kdmurray.id.au
 *
 * ============================================================================
 *
 * Copyright 2015- Kevin Murray <spam@kdmurray.id.au>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <fstream>
#include <string>
#include <chrono>
#include <iomanip>

#include <getopt.h>

#include "qcpp.hh"

#include "qc-measure.hh"
#include "qc-length.hh"
#include "qc-qualtrim.hh"
#include "qc-gbs.hh"
#include "qc-adaptor.hh"

using std::chrono::system_clock;

inline void
progress(size_t n, system_clock::time_point start)
{
    std::chrono::duration<double> tdiff = system_clock::now() - start;
    double secs = tdiff.count();
    double k_reads = n / 1000.0;
    double rate = k_reads / secs;
    std::cerr << "\33[2K" << "Kept " << std::setprecision(3) << k_reads
              << "K read pairs in " << (int)secs << "s (" << (int)rate
              << "K RP/sec)\r";
}

int
usage_err()
{
    using std::cerr;
    using std::endl;
    cerr << "USAGE: trimit [options] <read_file>" << std::endl
         << std::endl;
    cerr << "OPTIONS:" << endl;
    cerr << " -q QUAL    Minimum acceptable PHRED score. [default: 25]" << endl;
    cerr << " -l LEN      Fix read lengths to LEN [default: off]" << endl;
    cerr << " -y YAML    YAML report file. [default: none]" << endl;
    cerr << " -o OUTPUT  Output file. [default: stdout]" << endl;
    cerr << " -s         Single ended mode (no trim-merge). [default: false]" << endl;
    cerr << " -b         Use broken-paired output (don't keep read pairing) [default: false]" << endl;
    cerr << " -h         Show this help message." << endl;
    cerr << endl;
    cerr << "By default, reads from stdin and spits out good reads on stdout." <<  endl;
    return EXIT_FAILURE;
}

const char *cli_opts = "q:y:o:l:bsh";

int
main (int argc, char *argv[])
{
    using namespace qcpp;

    std::string             yaml_fname;
    bool                    broken_paired = false;
    bool                    single_end = false;
    std::ofstream           read_output;
    std::string             outfile = "/dev/stdout";
    std::string             infile = "/dev/stdin";
    size_t                  fix_length = 0;
    int                     qual_threshold = 25;

    int c = 0;
    while ((c = getopt(argc, argv, cli_opts)) > 0) {
        switch (c) {
            case 'y':
                yaml_fname = optarg;
                break;
            case 'o':
                outfile = optarg;
                break;
            case 'b':
                broken_paired = true;
                break;
            case 's':
                single_end = true;
                break;
            case 'q':
                qual_threshold = atoi(optarg);
                break;
            case 'l':
                fix_length = atoi(optarg);
                break;
            case 'h':
                usage_err();
                return EXIT_SUCCESS;
            default:
                std::cerr << "Bad arg '" << std::string(1, optopt) << "'"
                          << std::endl << std::endl;
                return usage_err();
        }
    }

    read_output.open(outfile);

    if (optind + 1 > argc) {
        std::cerr << "Reading from stdin! (Use -h for help)" << std::endl;
    } else {
        infile = argv[optind];
    }

    ProcessedReadStream     stream;
    uint64_t                n_pairs = 0;
    bool                    measure_qual = yaml_fname.size() > 0;

    if (measure_qual) {
        stream.append_processor<PerBaseQuality>("before qc");
    }
    if (!single_end) {
        stream.append_processor<AdaptorTrimPE>("trim or merge reads", 10);
    }
    stream.append_processor<WindowedQualTrim>("QC", SangerEncoding, qual_threshold, 1);
    if (fix_length > 0) {
        stream.append_processor<ReadTruncator>("Fix Length", SangerEncoding,
                                               fix_length);
    }
    if (measure_qual) {
        stream.append_processor<PerBaseQuality>("after qc");
    }

    try {
        stream.open(infile);
    } catch (qcpp::IOError  &e) {
        std::cerr << "Error opening input file:" << std::endl;
        std::cerr << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    system_clock::time_point start = system_clock::now();
    if (single_end) {
        Read rd;
        while (stream.parse_read(rd)) {
            read_output << rd.str();
            if (n_pairs % 10000 == 0) {
                progress(n_pairs, start);
            }
            n_pairs++;
        }
    } else {
        ReadPair rp;
        while (stream.parse_read_pair(rp)) {
            std::string rp_str = "";

            if (broken_paired) {
                if (rp.first.size() >= 64) {
                    rp_str = rp.first.str();
                }
                if (rp.second.size() >= 64) {
                    rp_str += rp.second.str();
                }
            } else {
                rp_str = rp.str();
            }

            if (n_pairs % 10000 == 0) {
                progress(n_pairs, start);
            }
            n_pairs++;

            read_output << rp_str;
        }
    }
    progress(n_pairs, start);
    std::cerr << std::endl;
    if (yaml_fname.size() > 0) {
        std::ofstream yml_output(yaml_fname);
        yml_output << stream.report();
    }
    return EXIT_SUCCESS;
}
<commit_msg>trimit: Remove default reading from stdin<commit_after>/*
 * ============================================================================
 *
 *       Filename:  trimmit.cc
 *    Description:  Just merges and quality trims interleaved reads.
 *        License:  LGPL-3+
 *         Author:  Kevin Murray, spam@kdmurray.id.au
 *
 * ============================================================================
 *
 * Copyright 2015- Kevin Murray <spam@kdmurray.id.au>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <fstream>
#include <string>
#include <chrono>
#include <iomanip>

#include <getopt.h>

#include "qcpp.hh"

#include "qc-measure.hh"
#include "qc-length.hh"
#include "qc-qualtrim.hh"
#include "qc-gbs.hh"
#include "qc-adaptor.hh"

using std::chrono::system_clock;

inline void
progress(size_t n, system_clock::time_point start)
{
    std::chrono::duration<double> tdiff = system_clock::now() - start;
    double secs = tdiff.count();
    double k_reads = n / 1000.0;
    double rate = k_reads / secs;
    std::cerr << "\33[2K" << "Kept " << std::setprecision(3) << k_reads
              << "K read pairs in " << (int)secs << "s (" << (int)rate
              << "K RP/sec)\r";
}

int
usage_err()
{
    using std::cerr;
    using std::endl;
    cerr << "USAGE: trimit [options] <read_file>" << endl
         << endl;
    cerr << "OPTIONS:" << endl;
    cerr << " -q QUAL    Minimum acceptable PHRED score. [default: 25]" << endl;
    cerr << " -l LEN      Fix read lengths to LEN [default: off]" << endl;
    cerr << " -y YAML    YAML report file. [default: none]" << endl;
    cerr << " -o OUTPUT  Output file. [default: stdout]" << endl;
    cerr << " -s         Single ended mode (no trim-merge). [default: false]" << endl;
    cerr << " -b         Use broken-paired output (don't keep read pairing) [default: false]" << endl;
    cerr << " -h         Show this help message." << endl;
    cerr << endl;
    cerr << "By default good reads are printed to stdout." <<  endl;
    return EXIT_FAILURE;
}

const char *cli_opts = "q:y:o:l:bsh";

int
main (int argc, char *argv[])
{
    using namespace qcpp;

    std::string             yaml_fname;
    bool                    broken_paired = false;
    bool                    single_end = false;
    std::ofstream           read_output;
    std::string             outfile = "/dev/stdout";
    std::string             infile = "";
    size_t                  fix_length = 0;
    int                     qual_threshold = 25;

    int c = 0;
    while ((c = getopt(argc, argv, cli_opts)) > 0) {
        switch (c) {
            case 'y':
                yaml_fname = optarg;
                break;
            case 'o':
                outfile = optarg;
                break;
            case 'b':
                broken_paired = true;
                break;
            case 's':
                single_end = true;
                break;
            case 'q':
                qual_threshold = atoi(optarg);
                break;
            case 'l':
                fix_length = atoi(optarg);
                break;
            case 'h':
                usage_err();
                return EXIT_SUCCESS;
            default:
                std::cerr << "Bad arg '" << std::string(1, optopt) << "'"
                          << std::endl << std::endl;
                return usage_err();
        }
    }

    if (optind == argc) {
        std::cerr << "Must give input file!" << std::endl << std::endl;
        usage_err();
        return EXIT_SUCCESS;
    }

    infile = argv[optind];
    read_output.open(outfile);

    ProcessedReadStream     stream;
    uint64_t                n_pairs = 0;
    bool                    measure_qual = yaml_fname.size() > 0;

    if (measure_qual) {
        stream.append_processor<PerBaseQuality>("before qc");
    }
    if (!single_end) {
        stream.append_processor<AdaptorTrimPE>("trim or merge reads", 10);
    }
    stream.append_processor<WindowedQualTrim>("QC", SangerEncoding, qual_threshold, 1);
    if (fix_length > 0) {
        stream.append_processor<ReadTruncator>("Fix Length", SangerEncoding,
                                               fix_length);
    }
    if (measure_qual) {
        stream.append_processor<PerBaseQuality>("after qc");
    }

    try {
        stream.open(infile);
    } catch (qcpp::IOError  &e) {
        std::cerr << "Error opening input file:" << std::endl;
        std::cerr << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    system_clock::time_point start = system_clock::now();
    if (single_end) {
        Read rd;
        while (stream.parse_read(rd)) {
            read_output << rd.str();
            if (n_pairs % 10000 == 0) {
                progress(n_pairs, start);
            }
            n_pairs++;
        }
    } else {
        ReadPair rp;
        while (stream.parse_read_pair(rp)) {
            std::string rp_str = "";

            if (broken_paired) {
                if (rp.first.size() >= 64) {
                    rp_str = rp.first.str();
                }
                if (rp.second.size() >= 64) {
                    rp_str += rp.second.str();
                }
            } else {
                rp_str = rp.str();
            }

            if (n_pairs % 10000 == 0) {
                progress(n_pairs, start);
            }
            n_pairs++;

            read_output << rp_str;
        }
    }
    progress(n_pairs, start);
    std::cerr << std::endl;
    if (yaml_fname.size() > 0) {
        std::ofstream yml_output(yaml_fname);
        yml_output << stream.report();
    }
    return EXIT_SUCCESS;
}
<|endoftext|>