text:
#include "temoto_visualization_manager/visualization_manager.h"
#include <boost/filesystem/operations.hpp>
#include <yaml-cpp/yaml.h>
#include <fstream>

namespace temoto_visualization_manager
{
VisualizationManager::VisualizationManager(const std::string& config_base_path)
: resource_registrar_(srv_name::RVIZ_MANAGER)
{
  /*
   * Configure the RR catalog backup routine
   */
  std::string home_path = std::getenv("HOME");
  std::string rr_catalog_backup_path = home_path + "/.temoto/" + srv_name::RVIZ_MANAGER + ".rrcat";
  rr_catalog_config_.setName(srv_name::RVIZ_MANAGER);
  rr_catalog_config_.setLocation(rr_catalog_backup_path);
  rr_catalog_config_.setSaveOnModify(true);
  rr_catalog_config_.setEraseOnDestruct(true);
  resource_registrar_.updateConfiguration(rr_catalog_config_);

  /*
   * Add the LoadRvizPlugin server to the resource registrar
   */
  auto server = std::make_unique<Ros1Server<LoadRvizPlugin>>(srv_name::RVIZ_SERVER
  , std::bind(&VisualizationManager::loadRvizPluginCb, this, std::placeholders::_1, std::placeholders::_2)
  , std::bind(&VisualizationManager::unloadRvizPluginCb, this, std::placeholders::_1, std::placeholders::_2));
  resource_registrar_.registerServer(std::move(server));
  resource_registrar_.init();

  /*
   * Load rviz_plugin_manager service clients
   */
  load_plugin_client_ = nh_.serviceClient<rviz_plugin_manager::PluginLoad>("rviz_plugin_load");
  unload_plugin_client_ = nh_.serviceClient<rviz_plugin_manager::PluginUnload>("rviz_plugin_unload");
  get_plugin_config_client_ = nh_.serviceClient<rviz_plugin_manager::PluginGetConfig>("rviz_plugin_get_config");
  set_plugin_config_client_ = nh_.serviceClient<rviz_plugin_manager::PluginSetConfig>("rviz_plugin_set_config");

  findPluginDescriptionFiles(config_base_path);

  TEMOTO_INFO_STREAM_("Visualization Manager is good to go.");
}

/* * * * * * * * * * * * * * * * *
 *  runRviz
 * * * * * * * * * * * * * * * * */

void VisualizationManager::runRviz()
try
{
  // Create the message and fill out the request part
  temoto_er_manager::LoadExtResource load_er_msg;
  load_er_msg.request.action = temoto_er_manager::action::ROS_EXECUTE;
  load_er_msg.request.package_name = "rviz_plugin_manager";
  load_er_msg.request.executable = "rviz_plugin_manager.launch";

  TEMOTO_DEBUG_("Requesting to launch rviz ...");

  resource_registrar_.call<temoto_er_manager::LoadExtResource>(temoto_er_manager::srv_name::MANAGER
  , temoto_er_manager::srv_name::SERVER
  , load_er_msg
  , std::bind(&VisualizationManager::erStatusCb, this, std::placeholders::_1, std::placeholders::_2));

  TEMOTO_DEBUG_("Rviz launched");

  // Wait until rviz_plugin_manager clients become active or throw an error on timeout
  ros::Time timeout = ros::Time::now() + ros::Duration(10);
  while ((!load_plugin_client_.exists() || !unload_plugin_client_.exists() ||
          !set_plugin_config_client_.exists() || !get_plugin_config_client_.exists()) &&
          ros::Time::now() < timeout)
  {
    ros::Duration diff = timeout - ros::Time::now();
    TEMOTO_DEBUG_("Waiting for rviz to start (timeout in %.1f sec).", diff.toSec());
    ros::Duration(1).sleep();
  }

  if (ros::Time::now() >= timeout)
  {
    throw TEMOTO_ERRSTACK("Failed to launch rviz plugin manager: Timeout reached.");
  }
  TEMOTO_DEBUG_("All rviz_plugin_manager services connected.");
}
catch (...)
{
  throw TEMOTO_ERRSTACK("Failed to start RViz");
}

/* * * * * * * * * * * * * * * * *
 *  Load process status callback
 * * * * * * * * * * * * * * * * */

void VisualizationManager::erStatusCb(temoto_er_manager::LoadExtResource srv_msg
, temoto_resource_registrar::Status status_msg)
{
  TEMOTO_WARN_STREAM_("Received a resource status message: " << status_msg.message_);
}

/* * * * * * * * * * * * * * * * *
 *  loadPluginRequest
 * * * * * * * * * * * * * * * * */

bool VisualizationManager::loadPluginRequest(rviz_plugin_manager::PluginLoad& load_plugin_srv)
{
  // Send the plugin request
  if (load_plugin_client_.call(load_plugin_srv))
  {
    if (load_plugin_srv.response.code == 0)
    {
      TEMOTO_INFO_("Request successful: %s", load_plugin_srv.response.message.c_str());
      return true;
    }
    else
    {
      throw TEMOTO_ERRSTACK("Failed to load rviz plugin: " + load_plugin_srv.response.message);
    }
  }
  else
  {
    throw TEMOTO_ERRSTACK("Failed to call service /rviz_plugin_load");
  }
}

/* * * * * * * * * * * * * * * * *
 *  unloadPluginRequest
 * * * * * * * * * * * * * * * * */

bool VisualizationManager::unloadPluginRequest(rviz_plugin_manager::PluginUnload& unload_plugin_srv)
{
  // Send the plugin request
  if (unload_plugin_client_.call(unload_plugin_srv))
  {
    if (unload_plugin_srv.response.code == 0)
    {
      TEMOTO_INFO_("Request successful: %s", unload_plugin_srv.response.message.c_str());
      return true;
    }
    else
    {
      throw TEMOTO_ERRSTACK("Failed to unload rviz plugin: " + unload_plugin_srv.response.message);
    }
  }
  else
  {
    throw TEMOTO_ERRSTACK("Failed to call service /rviz_plugin_unload");
  }
}

/* * * * * * * * * * * * * * * * *
 *  getPluginConfigRequest
 * * * * * * * * * * * * * * * * */

bool VisualizationManager::getPluginConfigRequest(
  rviz_plugin_manager::PluginGetConfig& get_plugin_config_srv)
{
  // Send the plugin request
  if (get_plugin_config_client_.call(get_plugin_config_srv))
  {
    if (get_plugin_config_srv.response.code == 0)
    {
      TEMOTO_INFO_("Request successful: %s", get_plugin_config_srv.response.message.c_str());
      return true;
    }
    else
    {
      throw TEMOTO_ERRSTACK("Failed to get rviz plugin config: " + get_plugin_config_srv.response.message);
    }
  }
  else
  {
    throw TEMOTO_ERRSTACK("Failed to call service /rviz_plugin_get_config");
  }
}

/* * * * * * * * * * * * * * * * *
 *  setPluginConfigRequest
 * * * * * * * * * * * * * * * * */

bool VisualizationManager::setPluginConfigRequest(
    rviz_plugin_manager::PluginSetConfig& set_plugin_config_srv)
{
  // Send the plugin request
  if (set_plugin_config_client_.call(set_plugin_config_srv))
  {
    if (set_plugin_config_srv.response.code == 0)
    {
      TEMOTO_INFO_("Request successful: %s", set_plugin_config_srv.response.message.c_str());
      return true;
    }
    else
    {
      throw TEMOTO_ERRSTACK("Failed to set rviz plugin config: " + set_plugin_config_srv.response.message);
    }
  }
  else
  {
    throw TEMOTO_ERRSTACK("Failed to call service /rviz_plugin_set_config");
  }
}

/* * * * * * * * * * * * * * * * *
 *  loadPluginCb
 * * * * * * * * * * * * * * * * */

void VisualizationManager::loadRvizPluginCb(temoto_visualization_manager::LoadRvizPlugin::Request& req,
                                   temoto_visualization_manager::LoadRvizPlugin::Response& res)
try
{ START_SPAN
  TEMOTO_INFO_STREAM_("Received a request to load a RViz plugin: " << req);
  runRviz();

  // Check the class_name of the requested display plugin and run if found
  PluginInfo plugin_info;

  // Create the message and fill out the request part
  if (plugin_info_handler_.findPlugin(req.class_name, plugin_info))
  {
    rviz_plugin_manager::PluginLoad load_plugin_srv;
    load_plugin_srv.request.plugin_class = plugin_info.getClassName();
    load_plugin_srv.request.plugin_topic = req.topic;
    load_plugin_srv.request.plugin_config = req.config;
    load_plugin_srv.request.plugin_data_type = plugin_info.getDataType();
    load_plugin_srv.request.plugin_name = plugin_info.getRvizName();

    loadPluginRequest(load_plugin_srv);

    // Add the request and ID into the active_requests_
    active_requests_.emplace(res.temoto_metadata.request_id, load_plugin_srv.response.plugin_uid);
  }
  else
  {
    throw TEMOTO_ERRSTACK("Did not find any appropriate display plugins");
  }
}
catch(resource_registrar::TemotoErrorStack e)
{
  throw FWD_TEMOTO_ERRSTACK(e);
}

/* * * * * * * * * * * * * * * * *
 *  unloadRvizPluginCb
 * * * * * * * * * * * * * * * * */

void VisualizationManager::unloadRvizPluginCb(temoto_visualization_manager::LoadRvizPlugin::Request& req,
                                     temoto_visualization_manager::LoadRvizPlugin::Response& res)
try
{
  TEMOTO_INFO_STREAM_("Unloading RViz display: " << req);

  // Go through the  and "active_requests_" list, look for the plugin_uid
  auto it = active_requests_.find(res.temoto_metadata.request_id);
  if (it != active_requests_.end())
  {
    rviz_plugin_manager::PluginUnload plugin_unload_srv;
    plugin_unload_srv.request.plugin_uid = it->second;

    unloadPluginRequest(plugin_unload_srv);
    active_requests_.erase(it);
  }
  else
  {
    throw TEMOTO_ERRSTACK("No allocated resources were found");
  }
}
catch (resource_registrar::TemotoErrorStack e)
{
  throw FWD_TEMOTO_ERRSTACK(e);
}

void VisualizationManager::findPluginDescriptionFiles(const std::string& current_dir)
{
  boost::filesystem::directory_iterator end_itr;
  for ( boost::filesystem::directory_iterator itr( current_dir ); itr != end_itr; ++itr )
  {
    if (boost::filesystem::is_regular_file(*itr) && (itr->path().filename() == description_file_))
    {
      TEMOTO_INFO_STREAM_("NEW PLUGIN FILE FOUND");
      TEMOTO_INFO_STREAM_(itr->path().string());
      readPluginDescription(itr->path().string());
    }
    else if ( boost::filesystem::is_directory(*itr) )
    {
      findPluginDescriptionFiles(itr->path().string());
    }
  }
}

void VisualizationManager::readPluginDescription(const std::string& path_to_plugin_description)
{
  std::ifstream in(path_to_plugin_description);
  YAML::Node yaml_config = YAML::Load(in);

  if (yaml_config["Plugins"])
  {
    YAML::Node plugins_config = yaml_config["Plugins"];

    if (!plugins_config.IsSequence())
    {
      TEMOTO_WARN_("The given config does not contain sequence of plugins.");
    }

    for (YAML::const_iterator node_it = plugins_config.begin(); node_it != plugins_config.end(); ++node_it)
    {
      if (!node_it->IsMap())
      {
        TEMOTO_ERROR_("Unable to parse the plugins config. Parameters in YAML have to be specified in "
                    "key-value pairs.");
        continue;
      }
      const YAML::Node& plugin = *node_it;
      std::string rviz_name;
      std::string data_type;
      if (!plugin["class_name"])
      {
        TEMOTO_WARN_("Invalid description of plugin, It does not contain a class_name");
      }
      else
      {
        if(plugin["rviz_name"])
        {
          rviz_name = plugin["rviz_name"].as<std::string>();
        }

        if(plugin["data_type"])
        {
          data_type = plugin["data_type"].as<std::string>();
        }
        else
        {
          data_type = "";
        }
        plugin_info_handler_.plugins_.emplace_back(plugin["class_name"].as<std::string>(),
                                                  rviz_name,
                                                  data_type);
      }
    }
  }
  else
  {
    TEMOTO_INFO_STREAM_("No plugings defined");
  }
}

}  // namespace visualization_manager


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

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

#include "DrawViewShell.hxx"
#include <cppuhelper/implbase1.hxx>
#include <comphelper/processfactory.hxx>
#ifndef _SVX_SIZEITEM
#include <editeng/sizeitem.hxx>
#endif
#include <svx/svdlayer.hxx>
#ifndef _SVX_ZOOMITEM
#include <svx/zoomitem.hxx>
#endif
#include <svx/svdpagv.hxx>
#include <svl/ptitem.hxx>
#include <svl/stritem.hxx>
#include <sfx2/request.hxx>
#include <sfx2/dispatch.hxx>
#include <svx/svdopath.hxx>
#include <sfx2/docfile.hxx>
#include <svx/zoomslideritem.hxx>
#include <svl/eitem.hxx>

#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif
#include <svx/extrusionbar.hxx>
#include <svx/fontworkbar.hxx>
#include <svx/clipfmtitem.hxx>

#include <sfx2/viewfrm.hxx>
#include <svx/fmshell.hxx>
#include <sfx2/dispatch.hxx>
#include <svtools/cliplistener.hxx>
#include <svx/float3d.hxx>
#include <svx/sidebar/SelectionAnalyzer.hxx>
#include "helpids.h"

#include "view/viewoverlaymanager.hxx"
#include "app.hrc"
#include "helpids.h"
#include "strings.hrc"
#include "res_bmp.hrc"
#include "sdpage.hxx"
#include "FrameView.hxx"
#include "drawdoc.hxx"
#include "sdresid.hxx"
#include "DrawDocShell.hxx"
#include "Window.hxx"
#include "fupoor.hxx"
#include "fusel.hxx"
#include "drawview.hxx"
#include "SdUnoDrawView.hxx"
#include "ViewShellBase.hxx"
#include "SdUnoDrawView.hxx"
#include "slideshow.hxx"
#include "ToolBarManager.hxx"
#include "annotationmanager.hxx"

#include <boost/bind.hpp>

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using sfx2::sidebar::EnumContext;

namespace {
static const ::rtl::OUString MASTER_VIEW_TOOL_BAR_NAME(
    ::rtl::OUString::createFromAscii("masterviewtoolbar"));
}

namespace sd {

sal_Bool DrawViewShell::mbPipette = sal_False;

// ------------------------
// - ScannerEventListener -
// ------------------------

class ScannerEventListener : public ::cppu::WeakImplHelper1< ::com::sun::star::lang::XEventListener >
{
private:

	DrawViewShell*		mpParent;

public:

							ScannerEventListener( DrawViewShell* pParent ) : mpParent( pParent )  {};
							~ScannerEventListener();

	// XEventListener
	virtual void SAL_CALL 	disposing( const ::com::sun::star::lang::EventObject& rEventObject ) throw (::com::sun::star::uno::RuntimeException);

	void					ParentDestroyed() { mpParent = NULL; }
};

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

ScannerEventListener::~ScannerEventListener()
{
}

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

void SAL_CALL ScannerEventListener::disposing( const ::com::sun::star::lang::EventObject& rEventObject ) throw (::com::sun::star::uno::RuntimeException)
{
	if( mpParent )
		mpParent->ScannerEvent( rEventObject );
}

/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/

DrawViewShell::DrawViewShell( SfxViewFrame* pFrame, ViewShellBase& rViewShellBase, ::Window* pParentWindow, PageKind ePageKind, FrameView* pFrameViewArgument )
: ViewShell (pFrame, pParentWindow, rViewShellBase)
, maTabControl(this, pParentWindow)
, mbIsInSwitchPage(false),
  mpSelectionChangeHandler(new svx::sidebar::SelectionChangeHandler(
          ::boost::bind(&DrawViewShell::GetSidebarContextName, this),
          uno::Reference<frame::XController>(&rViewShellBase.GetDrawController()),
          sfx2::sidebar::EnumContext::Context_Default))

{
	if (pFrameViewArgument != NULL)
		mpFrameView = pFrameViewArgument;
	else
        mpFrameView = new FrameView(GetDoc());
    Construct(GetDocSh(), ePageKind);

    mpSelectionChangeHandler->Connect();

    SetContextName(GetSidebarContextName());
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

DrawViewShell::~DrawViewShell()
{
    mpSelectionChangeHandler->Disconnect();

    mpAnnotationManager.reset();
    mpViewOverlayManager.reset();

    OSL_ASSERT (GetViewShell()!=NULL);

    if( mxScannerListener.is() )
		static_cast< ScannerEventListener* >( mxScannerListener.get() )->ParentDestroyed();

    // #96642# Remove references to items within Svx3DWin
    // (maybe do a listening sometime in Svx3DWin)
    sal_uInt16 nId = Svx3DChildWindow::GetChildWindowId();
    SfxChildWindow* pWindow = GetViewFrame() ? GetViewFrame()->GetChildWindow(nId) : NULL;
    if(pWindow)
    {
        Svx3DWin* p3DWin = static_cast< Svx3DWin* > (pWindow->GetWindow());
        if(p3DWin)
            p3DWin->DocumentReload();
    }

    EndListening (*GetDoc());
    EndListening (*GetDocSh());

	if( SlideShow::IsRunning(*this) )
        StopSlideShow(false);

	DisposeFunctions();

	SdPage* pPage;
	sal_uInt16 aPageCnt = GetDoc()->GetSdPageCount(mePageKind);

	for (sal_uInt16 i = 0; i < aPageCnt; i++)
	{
		pPage = GetDoc()->GetSdPage(i, mePageKind);

		if (pPage == mpActualPage)
		{
			GetDoc()->SetSelected(pPage, sal_True);
		}
		else
		{
			GetDoc()->SetSelected(pPage, sal_False);
		}
	}

	if ( mpClipEvtLstnr )
	{
		mpClipEvtLstnr->AddRemoveListener( GetActiveWindow(), sal_False );
		mpClipEvtLstnr->ClearCallbackLink();		// #103849# prevent callback if another thread is waiting
		mpClipEvtLstnr->release();
	}

	delete mpDrawView;
    // Set mpView to NULL so that the destructor of the ViewShell base class
    // does not access it.
	mpView = mpDrawView = NULL;

	mpFrameView->Disconnect();
	delete [] mpSlotArray;
}

/*************************************************************************
|*
|* gemeinsamer Initialisierungsanteil der beiden Konstruktoren
|*
\************************************************************************/

void DrawViewShell::Construct(DrawDocShell* pDocSh, PageKind eInitialPageKind)
{
	mpActualPage = 0;
	mbMousePosFreezed = sal_False;
	mbReadOnly = GetDocSh()->IsReadOnly();
	mpSlotArray = 0;
	mpClipEvtLstnr = 0;
	mbPastePossible = sal_False;
	mbIsLayerModeActive = false;

	mpFrameView->Connect();

    OSL_ASSERT (GetViewShell()!=NULL);

	// Array fuer Slot-/ImageMapping:
	// Gerader Eintrag: Haupt-/ToolboxSlot
	// Ungerader Eintrag: gemappter Slot
	// Achtung: Anpassen von GetIdBySubId() !!!
	// Reihenfolge (insbesondere Zoom) darf nicht geaendert werden !!!
	mpSlotArray = new sal_uInt16[ SLOTARRAY_COUNT ];
	mpSlotArray[ 0 ]  = SID_OBJECT_CHOOSE_MODE;
	mpSlotArray[ 1 ]  = SID_OBJECT_ROTATE;
	mpSlotArray[ 2 ]  = SID_OBJECT_ALIGN;
	mpSlotArray[ 3 ]  = SID_OBJECT_ALIGN_LEFT;
	mpSlotArray[ 4 ]  = SID_ZOOM_TOOLBOX;
	mpSlotArray[ 5 ]  = SID_ZOOM_TOOLBOX;
	mpSlotArray[ 6 ]  = SID_DRAWTBX_TEXT;
	mpSlotArray[ 7 ]  = SID_ATTR_CHAR;
	mpSlotArray[ 8 ]  = SID_DRAWTBX_RECTANGLES;
	mpSlotArray[ 9 ]  = SID_DRAW_RECT;
	mpSlotArray[ 10 ] = SID_DRAWTBX_ELLIPSES;
	mpSlotArray[ 11 ] = SID_DRAW_ELLIPSE;
	mpSlotArray[ 12 ] = SID_DRAWTBX_LINES;
	mpSlotArray[ 13 ] = SID_DRAW_FREELINE_NOFILL;
	mpSlotArray[ 14 ] = SID_DRAWTBX_3D_OBJECTS;
	mpSlotArray[ 15 ] = SID_3D_CUBE;
	mpSlotArray[ 16 ] = SID_DRAWTBX_INSERT;
	mpSlotArray[ 17 ] = SID_INSERT_DIAGRAM;
	mpSlotArray[ 18 ] = SID_POSITION;
	mpSlotArray[ 19 ] = SID_FRAME_TO_TOP;
	mpSlotArray[ 20 ] = SID_DRAWTBX_CONNECTORS;
	mpSlotArray[ 21 ] = SID_TOOL_CONNECTOR;
	mpSlotArray[ 22 ] = SID_DRAWTBX_ARROWS;
	mpSlotArray[ 23 ] = SID_LINE_ARROW_END;

	SetPool( &GetDoc()->GetPool() );

	GetDoc()->CreateFirstPages();

	mpDrawView = new DrawView(pDocSh, GetActiveWindow(), this);
	mpView = mpDrawView;			 // Pointer der Basisklasse ViewShell
	mpDrawView->SetSwapAsynchron(sal_True); // Asynchrones Laden von Graphiken

    // We do not read the page kind from the frame view anymore so we have
    // to set it in order to resync frame view and this view.
    mpFrameView->SetPageKind(eInitialPageKind);
	mePageKind = eInitialPageKind;
	meEditMode = EM_PAGE;
	DocumentType eDocType = GetDoc()->GetDocumentType(); // RTTI fasst hier noch nicht
    switch (mePageKind)
    {
        case PK_STANDARD:
            meShellType = ST_IMPRESS;
            break;

        case PK_NOTES:
            meShellType = ST_NOTES;
            break;

        case PK_HANDOUT:
            meShellType = ST_HANDOUT;
            break;
    }

	Size aPageSize( GetDoc()->GetSdPage(0, mePageKind)->GetSize() );
	Point aPageOrg( aPageSize.Width(), aPageSize.Height() / 2);
	Size aSize(aPageSize.Width() * 3, aPageSize.Height() * 2);
	InitWindows(aPageOrg, aSize, Point(-1, -1));

	Point aVisAreaPos;

	if ( pDocSh->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
	{
		aVisAreaPos = pDocSh->GetVisArea(ASPECT_CONTENT).TopLeft();
	}

	mpDrawView->SetWorkArea(Rectangle(Point() - aVisAreaPos - aPageOrg, aSize));

	// Objekte koennen max. so gross wie die ViewSize werden
	GetDoc()->SetMaxObjSize(aSize);

	// Split-Handler fuer TabControls
	maTabControl.SetSplitHdl( LINK( this, DrawViewShell, TabSplitHdl ) );

	// Damit der richtige EditMode von der FrameView komplett eingestellt
	// werden kann, wird hier ein aktuell anderer gewaehlt (kleiner Trick)
	if (mpFrameView->GetViewShEditMode(mePageKind) == EM_PAGE)
	{
		meEditMode = EM_MASTERPAGE;
	}
	else
	{
		meEditMode = EM_PAGE;
	}

	// Einstellungen der FrameView uebernehmen
	ReadFrameViewData(mpFrameView);

	if( eDocType == DOCUMENT_TYPE_DRAW )
	{
		SetHelpId( SD_IF_SDGRAPHICVIEWSHELL );
		GetActiveWindow()->SetHelpId( HID_SDGRAPHICVIEWSHELL );
		GetActiveWindow()->SetUniqueId( HID_SDGRAPHICVIEWSHELL );
	}
	else
	{
		if (mePageKind == PK_NOTES)
		{
			SetHelpId( SID_NOTESMODE );
			GetActiveWindow()->SetHelpId( CMD_SID_NOTESMODE );
			GetActiveWindow()->SetUniqueId( CMD_SID_NOTESMODE );

			// AutoLayouts muessen erzeugt sein
			GetDoc()->StopWorkStartupDelay();
		}
		else if (mePageKind == PK_HANDOUT)
		{
			SetHelpId( SID_HANDOUTMODE );
			GetActiveWindow()->SetHelpId( CMD_SID_HANDOUTMODE );
			GetActiveWindow()->SetUniqueId( CMD_SID_HANDOUTMODE );

			// AutoLayouts muessen erzeugt sein
			GetDoc()->StopWorkStartupDelay();
		}
		else
		{
			SetHelpId( SD_IF_SDDRAWVIEWSHELL );
			GetActiveWindow()->SetHelpId( HID_SDDRAWVIEWSHELL );
			GetActiveWindow()->SetUniqueId( HID_SDDRAWVIEWSHELL );
		}
	}

	// Selektionsfunktion starten
	SfxRequest aReq(SID_OBJECT_SELECT, 0, GetDoc()->GetItemPool());
	FuPermanent(aReq);
	mpDrawView->SetFrameDragSingles(sal_True);

	if (pDocSh->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED)
	{
		mbZoomOnPage = sal_False;
	}
	else
	{
		mbZoomOnPage = sal_True;
	}

	mbIsRulerDrag = sal_False;

	String aName( RTL_CONSTASCII_USTRINGPARAM("DrawViewShell"));
	SetName (aName);

	mnLockCount = 0UL;

	::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xMgr( ::comphelper::getProcessServiceFactory() );

	if( xMgr.is() )
	{
		mxScannerManager = ::com::sun::star::uno::Reference< ::com::sun::star::scanner::XScannerManager >(
						   xMgr->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.scanner.ScannerManager" ) ),
						   ::com::sun::star::uno::UNO_QUERY );

		if( mxScannerManager.is() )
		{
			mxScannerListener = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >(
								static_cast< ::cppu::OWeakObject* >( new ScannerEventListener( this ) ),
								::com::sun::star::uno::UNO_QUERY );
		}
	}

    mpAnnotationManager.reset( new AnnotationManager( GetViewShellBase() ) );
    mpViewOverlayManager.reset( new ViewOverlayManager( GetViewShellBase() ) );
}

void DrawViewShell::Init (bool bIsMainViewShell)
{
    ViewShell::Init(bIsMainViewShell);

    StartListening (*GetDocSh());
}

void DrawViewShell::Shutdown (void)
{
    ViewShell::Shutdown();

	if(SlideShow::IsRunning( GetViewShellBase() ) )
    {
        // Turn off effects.
        GetDrawView()->SetAnimationMode(SDR_ANIMATION_DISABLE);
    }
}

css::uno::Reference<css::drawing::XDrawSubController> DrawViewShell::CreateSubController (void)
{
    css::uno::Reference<css::drawing::XDrawSubController> xSubController;

    if (IsMainViewShell())
    {
        // Create uno sub controller for the main view shell.
        xSubController = css::uno::Reference<css::drawing::XDrawSubController>(
            new SdUnoDrawView (
                GetViewShellBase().GetDrawController(),
                *this,
                *GetView()));
    }

    return xSubController;
}

bool DrawViewShell::RelocateToParentWindow (::Window* pParentWindow)
{
    // DrawViewShells can not be relocated to a new parent window at the
    // moment, so return <FALSE/> except when the given parent window is the
    // parent window that is already in use.
    return pParentWindow==GetParentWindow();
}

/*************************************************************************
|*
|* pruefe ob linienzuege gezeichnet werden muessen
|*
\************************************************************************/

/*
	linienzuege werden ueber makros als folge von
		MoveTo (x, y)
		LineTo (x, y)	[oder BezierTo (x, y)]
		LineTo (x, y)
			:
	dargestellt. einen endbefehl fuer die linienzuege
	gibt es nicht, also muessen alle befehle in den
	requests nach LineTo (BezierTo) abgetestet und die
	punktparameter gesammelt werden.
	der erste nicht-LineTo fuehrt dann dazu, dass aus
	den gesammelten punkten der linienzug erzeugt wird
*/

void DrawViewShell::CheckLineTo(SfxRequest& rReq)
{
	(void)rReq;
#ifdef DBG_UTIL
	if(rReq.IsAPI())
	{
		if(SID_LINETO == rReq.GetSlot() || SID_BEZIERTO == rReq.GetSlot() || SID_MOVETO == rReq.GetSlot() )
		{
			DBG_ERROR("DrawViewShell::CheckLineTo: slots SID_LINETO, SID_BEZIERTO, SID_MOVETO no longer supported.");
		}
	}
#endif

	rReq.Ignore ();
}

/*************************************************************************
|*
|* veraendere die seitemparameter, wenn SID_PAGESIZE oder SID_PAGEMARGIN
|*
\************************************************************************/

void DrawViewShell::SetupPage (Size &rSize,
								 long nLeft,
								 long nRight,
								 long nUpper,
								 long nLower,
								 sal_Bool bSize,
								 sal_Bool bMargin,
								 sal_Bool bScaleAll)
{
	sal_uInt16 nPageCnt = GetDoc()->GetMasterSdPageCount(mePageKind);
	sal_uInt16 i;

	for (i = 0; i < nPageCnt; i++)
	{
		/**********************************************************************
		* Erst alle MasterPages bearbeiten
		**********************************************************************/
		SdPage *pPage = GetDoc()->GetMasterSdPage(i, mePageKind);

		if( pPage )
		{
			if( bSize )
			{
				Rectangle aBorderRect(nLeft, nUpper, nRight, nLower);
				pPage->ScaleObjects(rSize, aBorderRect, bScaleAll);
				pPage->SetSize(rSize);

			}
			if( bMargin )
			{
				pPage->SetLftBorder(nLeft);
				pPage->SetRgtBorder(nRight);
				pPage->SetUppBorder(nUpper);
				pPage->SetLwrBorder(nLower);
			}

			if ( mePageKind == PK_STANDARD )
			{
				GetDoc()->GetMasterSdPage(i, PK_NOTES)->CreateTitleAndLayout();
			}

			pPage->CreateTitleAndLayout();
		}
	}

	nPageCnt = GetDoc()->GetSdPageCount(mePageKind);

	for (i = 0; i < nPageCnt; i++)
	{
		/**********************************************************************
		* Danach alle Pages bearbeiten
		**********************************************************************/
		SdPage *pPage = GetDoc()->GetSdPage(i, mePageKind);

		if( pPage )
		{
			if( bSize )
			{
				Rectangle aBorderRect(nLeft, nUpper, nRight, nLower);
				pPage->ScaleObjects(rSize, aBorderRect, bScaleAll);
				pPage->SetSize(rSize);
			}
			if( bMargin )
			{
				pPage->SetLftBorder(nLeft);
				pPage->SetRgtBorder(nRight);
				pPage->SetUppBorder(nUpper);
				pPage->SetLwrBorder(nLower);
			}

			if ( mePageKind == PK_STANDARD )
			{
				SdPage* pNotesPage = GetDoc()->GetSdPage(i, PK_NOTES);
				pNotesPage->SetAutoLayout( pNotesPage->GetAutoLayout() );
			}

			pPage->SetAutoLayout( pPage->GetAutoLayout() );
		}
	}

	if ( mePageKind == PK_STANDARD )
	{
		SdPage* pHandoutPage = GetDoc()->GetSdPage(0, PK_HANDOUT);
		pHandoutPage->CreateTitleAndLayout(sal_True);
	}

	long nWidth = mpActualPage->GetSize().Width();
	long nHeight = mpActualPage->GetSize().Height();

	Point aPageOrg(nWidth, nHeight / 2);
	Size aSize( nWidth * 3, nHeight * 2);

	InitWindows(aPageOrg, aSize, Point(-1, -1), sal_True);

	Point aVisAreaPos;

	if ( GetDocSh()->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
	{
		aVisAreaPos = GetDocSh()->GetVisArea(ASPECT_CONTENT).TopLeft();
	}

	GetView()->SetWorkArea(Rectangle(Point() - aVisAreaPos - aPageOrg, aSize));

	UpdateScrollBars();

	Point aNewOrigin(mpActualPage->GetLftBorder(), mpActualPage->GetUppBorder());
	GetView()->GetSdrPageView()->SetPageOrigin(aNewOrigin);

	GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET);

	// auf (neue) Seitengroesse zoomen
	GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE,
						SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
}

/*************************************************************************
|*
|* Statuswerte der Statusbar zurueckgeben
|*
\************************************************************************/

void DrawViewShell::GetStatusBarState(SfxItemSet& rSet)
{
	// Zoom-Item
	// Hier sollte der entsprechende Wert (Optimal ?, Seitenbreite oder
	// Seite) mit Hilfe des ZoomItems weitergegeben werden !!!
	if( SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_ATTR_ZOOM ) )
	{
		if (GetDocSh()->IsUIActive() || (SlideShow::IsRunning(GetViewShellBase())) )
		{
			rSet.DisableItem( SID_ATTR_ZOOM );
		}
		else
		{
			SvxZoomItem* pZoomItem;
			sal_uInt16 nZoom = (sal_uInt16) GetActiveWindow()->GetZoom();

			if( mbZoomOnPage )
				pZoomItem = new SvxZoomItem( SVX_ZOOM_WHOLEPAGE, nZoom );
			else
				pZoomItem = new SvxZoomItem( SVX_ZOOM_PERCENT, nZoom );

			// Bereich einschraenken
			sal_uInt16 nZoomValues = SVX_ZOOM_ENABLE_ALL;
			SdrPageView* pPageView = mpDrawView->GetSdrPageView();

			if( ( pPageView && pPageView->GetObjList()->GetObjCount() == 0 ) )
				// || ( mpDrawView->GetMarkedObjectList().GetMarkCount() == 0 ) )
			{
				nZoomValues &= ~SVX_ZOOM_ENABLE_OPTIMAL;
			}

			pZoomItem->SetValueSet( nZoomValues );
			rSet.Put( *pZoomItem );
			delete pZoomItem;
		}
	}
	if( SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_ATTR_ZOOMSLIDER ) )
	{
        rtl::Reference< sd::SlideShow > xSlideshow( SlideShow::GetSlideShow( GetDoc() ) );
		if (GetDocSh()->IsUIActive() || (xSlideshow.is() && xSlideshow->isRunning()) || !GetActiveWindow() )
		{
			rSet.DisableItem( SID_ATTR_ZOOMSLIDER );
		}
		else
		{
			sd::Window * pActiveWindow = GetActiveWindow();
			SvxZoomSliderItem aZoomItem( (sal_uInt16) pActiveWindow->GetZoom(), (sal_uInt16)pActiveWindow->GetMinZoom(), (sal_uInt16)pActiveWindow->GetMaxZoom() ) ;

            SdrPageView* pPageView = mpDrawView->GetSdrPageView();
            if( pPageView )
            {
                Point aPagePos(0, 0);
				Size aPageSize = pPageView->GetPage()->GetSize();

				aPagePos.X() += aPageSize.Width()  / 2;
                aPageSize.Width() = (long) (aPageSize.Width() * 1.03);

				aPagePos.Y() += aPageSize.Height() / 2;
                aPageSize.Height() = (long) (aPageSize.Height() * 1.03);
				aPagePos.Y() -= aPageSize.Height() / 2;

				aPagePos.X() -= aPageSize.Width()  / 2;

                Rectangle aFullPageZoomRect( aPagePos, aPageSize );
                aZoomItem.AddSnappingPoint( pActiveWindow->GetZoomForRect( aFullPageZoomRect ) );
            }
			aZoomItem.AddSnappingPoint(100);
			rSet.Put( aZoomItem );
		}
	}

	Point aPos = GetActiveWindow()->PixelToLogic(maMousePos);
	mpDrawView->GetSdrPageView()->LogicToPagePos(aPos);
	Fraction aUIScale(GetDoc()->GetUIScale());
	aPos.X() = Fraction(aPos.X()) / aUIScale;
	aPos.Y() = Fraction(aPos.Y()) / aUIScale;

	// Position- und Groesse-Items
	if ( mpDrawView->IsAction() )
	{
		Rectangle aRect;
		mpDrawView->TakeActionRect( aRect );

		if ( aRect.IsEmpty() )
			rSet.Put( SfxPointItem(SID_ATTR_POSITION, aPos) );
		else
		{
			mpDrawView->GetSdrPageView()->LogicToPagePos(aRect);
			aPos = aRect.TopLeft();
			aPos.X() = Fraction(aPos.X()) / aUIScale;
			aPos.Y() = Fraction(aPos.Y()) / aUIScale;
			rSet.Put( SfxPointItem( SID_ATTR_POSITION, aPos) );
			Size aSize( aRect.Right() - aRect.Left(), aRect.Bottom() - aRect.Top() );
			aSize.Height() = Fraction(aSize.Height()) / aUIScale;
			aSize.Width()  = Fraction(aSize.Width())  / aUIScale;
			rSet.Put( SvxSizeItem( SID_ATTR_SIZE, aSize) );
		}
	}
	else
	{
		if ( mpDrawView->AreObjectsMarked() )
		{
			Rectangle aRect = mpDrawView->GetAllMarkedRect();
			mpDrawView->GetSdrPageView()->LogicToPagePos(aRect);

            // Show the position of the selected shape(s)
            Point aShapePosition (aRect.TopLeft());
            aShapePosition.X() = Fraction(aShapePosition.X()) / aUIScale;
            aShapePosition.Y() = Fraction(aShapePosition.Y()) / aUIScale;
            rSet.Put (SfxPointItem(SID_ATTR_POSITION, aShapePosition));

			Size aSize( aRect.Right() - aRect.Left(), aRect.Bottom() - aRect.Top() );
			aSize.Height() = Fraction(aSize.Height()) / aUIScale;
			aSize.Width()  = Fraction(aSize.Width())  / aUIScale;
			rSet.Put( SvxSizeItem( SID_ATTR_SIZE, aSize) );
		}
		else
        {
            rSet.Put( SfxPointItem(SID_ATTR_POSITION, aPos) );
			rSet.Put( SvxSizeItem( SID_ATTR_SIZE, Size( 0, 0 ) ) );
        }
	}

	// Display of current page and layer.
	if( SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_STATUS_PAGE ) )
	{
        // Always show the slide/page number.
		String aString (SdResId( STR_SD_PAGE ));
        aString += sal_Unicode(' ');
        aString += UniString::CreateFromInt32( maTabControl.GetCurPageId() );
        aString.AppendAscii( RTL_CONSTASCII_STRINGPARAM( " / " ));
        aString += UniString::CreateFromInt32( GetDoc()->GetSdPageCount( mePageKind ) );

        // If in layer mode additionally show the layer that contains all
        // selected shapes of the page.  If the shapes are distributed on
        // more than one layer, no layer name is shown.
		if (IsLayerModeActive())
		{
			SdrLayerAdmin& rLayerAdmin = GetDoc()->GetLayerAdmin();
			SdrLayerID nLayer = 0, nOldLayer = 0;
			SdrLayer*  pLayer = NULL;
			SdrObject* pObj = NULL;
			const SdrMarkList& rMarkList = mpDrawView->GetMarkedObjectList();
			sal_uLong nMarkCount = rMarkList.GetMarkCount();
			FASTBOOL bOneLayer = sal_True;

            // Use the first ten selected shapes as a (hopefully
            // representative) sample of all shapes of the current page.
            // Detect whether they belong to the same layer.
			for( sal_uLong j = 0; j < nMarkCount && bOneLayer && j < 10; j++ )
			{
				pObj = rMarkList.GetMark( j )->GetMarkedSdrObj();
				if( pObj )
				{
					nLayer = pObj->GetLayer();

					if( j != 0 && nLayer != nOldLayer )
						bOneLayer = sal_False;

					nOldLayer = nLayer;
				}
			}

            // Append the layer name to the current page number.
			if( bOneLayer && nMarkCount )
			{
				pLayer = rLayerAdmin.GetLayerPerID( nLayer );
				if( pLayer )
                {
                    aString.AppendAscii( RTL_CONSTASCII_STRINGPARAM( " (" ));
					aString += pLayer->GetName();
                    aString += sal_Unicode(')');
                }
			}
		}

		rSet.Put (SfxStringItem (SID_STATUS_PAGE, aString));
	}
	// Layout
	if( SFX_ITEM_AVAILABLE == rSet.GetItemState( SID_STATUS_LAYOUT ) )
	{
		String aString = mpActualPage->GetLayoutName();
		aString.Erase( aString.SearchAscii( SD_LT_SEPARATOR ) );
		rSet.Put( SfxStringItem( SID_STATUS_LAYOUT, aString ) );
	}
}

void DrawViewShell::Notify (SfxBroadcaster&, const SfxHint& rHint)
{
	const SfxSimpleHint* pSimple = dynamic_cast< const SfxSimpleHint* >(&rHint);
	if (pSimple!=NULL && pSimple->GetId()==SFX_HINT_MODECHANGED)
	{
        // Change to selection when turning on read-only mode.
		if(GetDocSh()->IsReadOnly() && dynamic_cast< FuSelection* >( GetCurrentFunction().get() ) )
		{
			SfxRequest aReq(SID_OBJECT_SELECT, 0, GetDoc()->GetItemPool());
			FuPermanent(aReq);
		}

        // Turn on design mode when document is not read-only.
		if (GetDocSh()->IsReadOnly() != mbReadOnly )
		{
			mbReadOnly = GetDocSh()->IsReadOnly();

			SfxBoolItem aItem( SID_FM_DESIGN_MODE, !mbReadOnly );
			GetViewFrame()->GetDispatcher()->Execute( SID_FM_DESIGN_MODE,
                SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aItem, 0L );
		}
	}

}

void DrawViewShell::ExecuteAnnotation (SfxRequest& rRequest)
{
    if( mpAnnotationManager.get() )
        mpAnnotationManager->ExecuteAnnotation( rRequest );
}

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

void DrawViewShell::GetAnnotationState (SfxItemSet& rItemSet )
{
    if( mpAnnotationManager.get() )
        mpAnnotationManager->GetAnnotationState( rItemSet );
}

::rtl::OUString DrawViewShell::GetSidebarContextName (void) const
{
    ::svx::sidebar::SelectionAnalyzer::ViewType eViewType (::svx::sidebar::SelectionAnalyzer::VT_Standard);
    switch (mePageKind)
    {
        case PK_HANDOUT:
            eViewType = ::svx::sidebar::SelectionAnalyzer::VT_Handout;
            break;
        case PK_NOTES:
            eViewType = ::svx::sidebar::SelectionAnalyzer::VT_Notes;
            break;
        case PK_STANDARD:
            if (meEditMode == EM_MASTERPAGE)
                eViewType = ::svx::sidebar::SelectionAnalyzer::VT_Master;
            else
                eViewType = ::svx::sidebar::SelectionAnalyzer::VT_Standard;
            break;
    }
    return EnumContext::GetContextName(
        ::svx::sidebar::SelectionAnalyzer::GetContextForSelection_SD(
            mpDrawView->GetMarkedObjectList(),
            eViewType));
}

} // end of namespace sd

ext: cxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
// maya
// Copyright (c) 2012-2016, Joshua Scoggins
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
extern "C" {
#include "clips.h"
}
#include "mayasetup.h"
#include "boost.h"
#include <string>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/math/common_factor.hpp>
#include <boost/filesystem.hpp>
#include <boost/system/error_code.hpp>
#include <boost/algorithm/clamp.hpp>

#if BOOST_EXTENSIONS
void HasPrefix(Environment*, UDFContext*, UDFValue*);
void HasSuffix(Environment*, UDFContext*, UDFValue*);
void TrimString(Environment*, UDFContext*, UDFValue*);
void TrimStringFront(Environment*, UDFContext*, UDFValue*);
void TrimStringBack(Environment*, UDFContext*, UDFValue*);
void NewUUID(Environment*, UDFContext*, UDFValue*);
void gcdFunction(Environment*, UDFContext*, UDFValue*);
void lcmFunction(Environment*, UDFContext*, UDFValue*);
void FileExists(Environment*, UDFContext*, UDFValue*);
void IsDirectory(Environment*, UDFContext*, UDFValue*);
void IsRegularFile(Environment*, UDFContext*, UDFValue*);
void ClampValue(Environment*, UDFContext*, UDFValue*);
#endif

extern "C" void InstallBoostExtensions(Environment* theEnv) {
#if BOOST_EXTENSIONS
	AddUDF(theEnv, "has-prefix", "b", 2, 2, "sy;sy;sy", HasPrefix, "HasPrefix",  NULL);
	AddUDF(theEnv, "has-suffix", "b", 2, 2, "sy;sy;sy", HasSuffix, "HasSuffix",  NULL);
	AddUDF(theEnv, "string-trim", "y", 1, 1, "s", TrimString, "TrimString", NULL);
	AddUDF(theEnv, "string-trim-front", "y", 1, 1, "s", TrimStringFront, "TrimStringFront", NULL);
	AddUDF(theEnv, "string-trim-back", "y",  1, 1, "s", TrimStringBack, "TrimStringBack", NULL);
	AddUDF(theEnv, "new-uuid", "s", 0, 0, "", NewUUID, "NewUUID", NULL);
	AddUDF(theEnv, "gcd", "l",  2, 2, "l;l;l", gcdFunction, "gcdFunction", NULL);
	AddUDF(theEnv, "lcm", "l",  2, 2, "l;l;l", lcmFunction, "lcmFunction", NULL);
	AddUDF(theEnv, "path-exists",   "b", 1, 1, "sy", FileExists, "FileExists", NULL);
	AddUDF(theEnv, "directoryp",    "b", 1, 1, "sy", IsDirectory, "IsDirectory", NULL);
	AddUDF(theEnv, "regular-filep", "b", 1, 1, "sy", IsRegularFile, "IsRegularFile", NULL);
	AddUDF(theEnv, "clamp", "l",  3, 3, "l;l;l;l", ClampValue, "ClampValue", NULL);
#endif
}

#if BOOST_EXTENSIONS
void ClampValue(Environment* env, UDFContext* context, UDFValue* ret) {
	UDFValue v, lo, hi;
	if (!UDFFirstArgument(context, INTEGER_BIT,  &v)) {
		ret->lexemeValue = FalseSymbol(env);
	} else if (!UDFNextArgument(context, INTEGER_BIT, &lo)) {
		ret->lexemeValue = FalseSymbol(env);
	} else if (!UDFNextArgument(context, INTEGER_BIT, &hi)) {
		ret->lexemeValue = FalseSymbol(env);
	} else {
		ret->integerValue = CreateInteger(env, boost::algorithm::clamp(CVCoerceToInteger(&v), CVCoerceToInteger(&lo), CVCoerceToInteger(&hi)));
	}
}

void FileExists(Environment* env, UDFContext* context, UDFValue* ret) {
	UDFValue path;
	if (!UDFFirstArgument(context, LEXEME_BITS, &path)) {
		ret->lexemeValue = FalseSymbol(env);
	} else {
		std::string p(path.lexemeValue->contents);
		ret->lexemeValue = boost::filesystem::exists(p) ? TrueSymbol(env) : FalseSymbol(env);
	}
}

void IsDirectory(Environment* env, UDFContext* context, UDFValue* ret) {
	UDFValue path;
	if (!UDFFirstArgument(context, LEXEME_BITS, &path)) {
		ret->lexemeValue = FalseSymbol(env);
	} else {
		std::string p(path.lexemeValue->contents);
		ret->lexemeValue = boost::filesystem::is_directory(p) ? TrueSymbol(env) : FalseSymbol(env);
	}
}

void IsRegularFile(Environment* env, UDFContext* context, UDFValue* ret) {
	UDFValue path;
	if (!UDFFirstArgument(context, LEXEME_BITS, &path)) {
		ret->lexemeValue = FalseSymbol(env);
	} else {
		std::string p(path.lexemeValue->contents);
		ret->lexemeValue = boost::filesystem::is_regular_file(p) ? TrueSymbol(env) : FalseSymbol(env);
	}
}

void gcdFunction(Environment* env, UDFContext* context, UDFValue* ret) {
	UDFValue first, second;
	if (!UDFFirstArgument(context, INTEGER_BIT, &first)) {
		ret->lexemeValue = FalseSymbol(env);
	} else if (!UDFNextArgument(context, INTEGER_BIT, &second)) {
		ret->lexemeValue = FalseSymbol(env);
	} else {
		ret->integerValue = CreateInteger(env, boost::math::gcd(CVCoerceToInteger(&first), CVCoerceToInteger(&second)));
	}
}
void lcmFunction(Environment* env, UDFContext* context, UDFValue* ret) {
	UDFValue first, second;
	if (!UDFFirstArgument(context, INTEGER_BIT, &first)) {
		ret->lexemeValue = FalseSymbol(env);
	} else if (!UDFNextArgument(context, INTEGER_BIT, &second)) {
		ret->lexemeValue = FalseSymbol(env);
	} else {
		ret->integerValue = CreateInteger(env, boost::math::lcm(CVCoerceToInteger(&first), CVCoerceToInteger(&second)));
	}
}
void NewUUID(Environment* env, UDFContext* context, UDFValue* ret) {
	boost::uuids::random_generator rgen;
	boost::uuids::uuid theUUID(rgen());
	const std::string tmp = boost::lexical_cast<std::string>(theUUID);
	ret->value = CreateSymbol(env, tmp.c_str());
}
void HasPrefix(Environment* env, UDFContext* context, UDFValue* ret) {
	UDFValue data, prefix;
	if (!UDFFirstArgument(context, LEXEME_BITS, &data)) {
		ret->lexemeValue = FalseSymbol(env);
		return;
	} else if (!UDFNextArgument(context, LEXEME_BITS, &prefix)) {
		ret->lexemeValue = FalseSymbol(env);
		return;
	}
	std::string dataStr(data.lexemeValue->contents);
	std::string prefixStr(prefix.lexemeValue->contents);
	ret->lexemeValue = boost::starts_with(dataStr, prefixStr) ? TrueSymbol(env) : FalseSymbol(env);
}

void HasSuffix(Environment* env, UDFContext* context, UDFValue* ret) {
	UDFValue data, suffix;
	if (!UDFFirstArgument(context, LEXEME_BITS, &data)) {
		ret->lexemeValue = FalseSymbol(env);
		return;
	} else if (!UDFNextArgument(context, LEXEME_BITS, &suffix)) {
		ret->lexemeValue = FalseSymbol(env);
		return;
	}
	std::string dataStr(data.lexemeValue->contents);
	std::string suffixStr(suffix.lexemeValue->contents);
	ret->lexemeValue = boost::ends_with(dataStr, suffixStr) ? TrueSymbol(env) : FalseSymbol(env);
}
void TrimString(Environment* env, UDFContext* context, UDFValue* ret) {
	UDFValue str;
	if (!UDFFirstArgument(context, STRING_BIT, &str)) {
		ret->lexemeValue = FalseSymbol(env);
	} else {
		std::string tmp(str.lexemeValue->contents);
		boost::algorithm::trim(tmp);
		ret->value = CreateString(env, tmp.c_str());
	}
}
void TrimStringFront(Environment* env, UDFContext* context, UDFValue* ret) {
	UDFValue str;
	if (!UDFFirstArgument(context, STRING_BIT, &str)) {
		ret->lexemeValue = FalseSymbol(env);
	} else {
		std::string tmp(str.lexemeValue->contents);
		boost::algorithm::trim_left(tmp);
		ret->value = CreateString(env, tmp.c_str());
	}
}
void TrimStringBack(Environment* env, UDFContext* context, UDFValue* ret) {
	UDFValue str;
	if (!UDFFirstArgument(context, STRING_BIT, &str)) {
		ret->lexemeValue = FalseSymbol(env);
	} else {
		std::string tmp(str.lexemeValue->contents);
		boost::algorithm::trim_right(tmp);
		ret->value = CreateString(env, tmp.c_str());
	}
}
#endif

ext: cc

max_stars_repo_name: DrItanium/syn

max_issues_repo_name: DrItanium/syn

max_forks_repo_name: DrItanium/syn


text:
// exact C++ implementation of lowe's sift program
// Copyright (C) zerofrog(@gmail.com), 2008-2009
//
// This program 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.
//
//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
//Lesser GNU General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.
#define BOOST_ENABLE_ASSERT_HANDLER

#include <vector>

#define PY_ARRAY_UNIQUE_SYMBOL PyArrayHandle
#include <boost/python.hpp>
#include <boost/python/exception_translator.hpp>
#include <pyconfig.h>
#include <numpy/arrayobject.h>

#include <boost/format.hpp>

#include "siftfast.h"

#define CHECK_POINTER(p) { \
    if( (p) == NULL ) throw siftfast_exception("invalid pointer"); \
}

using namespace boost::python;
using namespace std;

extern int DoubleImSize;
extern int Scales;
extern float InitSigma;
extern float PeakThresh;

struct siftfast_exception : std::exception
{
    siftfast_exception() : std::exception(), _s("unknown exception") {}
    siftfast_exception(const string& s) : std::exception() { _s = "siftfast: " + s; }
    virtual ~siftfast_exception() noexcept {}
    char const* what() noexcept const { return _s.c_str(); }
    string _s;
};

#if defined(BOOST_ENABLE_ASSERT_HANDLER)
namespace boost
{
inline void assertion_failed(char const * expr, char const * function, char const * file, long line)
{
    throw siftfast_exception(str(boost::format("[%s:%d] -> %s, expr: %s")%file%line%function%expr));
}
}
#endif

void translate_siftfast_exception(siftfast_exception const& e)
{
    // Use the Python 'C' API to set up an exception object
    PyErr_SetString(PyExc_RuntimeError, e.what());
}

inline object toPyArrayN(const float* pvalues, int N)
{
    npy_intp dims[] = {N};
    PyObject *pyvalues = PyArray_SimpleNew(1,dims, PyArray_FLOAT);
    if( pvalues != NULL )
        memcpy(PyArray_DATA(pyvalues),pvalues,N*sizeof(float));
    return static_cast<numeric::array>(handle<>(pyvalues));
}

template <typename T>
inline vector<T> ExtractArray(object o)
{
    vector<T> v(len(o));
    for(size_t i = 0; i < v.size(); ++i)
        v[i] = extract<T>(o[i]);
    return v;
}

inline vector<float> ExtractFloatArray(object oraw)
{
    object o = oraw.attr("flat");

    // check the types of o
    extract<float> xr(o[0]);
    if( xr.check() )
        return ExtractArray<float>(o);

    vector<float> v(len(o));
    object onew = ((numeric::array)oraw).astype("f8").attr("flat");
    for(size_t i = 0; i < v.size(); ++i)
        v[i] = (float)(extract<double>(onew[i]));
    return v;
}

class PyImage
{
public:
    PyImage(int width, int height) : width(width), height(height)
    {
        BOOST_ASSERT(width>0&&height>0);
        stride = (width+3)&~3;
        vimage.resize(height*stride);
    }
    PyImage(object oimage)
    {
        object shape = oimage.attr("shape");
        BOOST_ASSERT(len(shape)==2);
        width = extract<int>(shape[1]);
        height = extract<int>(shape[0]);
        stride = (width+3)&~3;
        vimage.resize(height*stride);
        SetData(oimage);
    }

    void SetData(object arr)
    {
        object shape = arr.attr("shape");
        if( len(shape) != 2 )
            throw siftfast_exception("array needs 2 dimensions");
        if( height != extract<int>(shape[0]) )
            throw siftfast_exception("array rows do not match height");
        if( width != extract<int>(shape[1]) )
            throw siftfast_exception("array columns do not match width");

        string dtype = extract<string>(arr.attr("dtype").attr("name"));
        if( (dtype.size() >= 3 && dtype[0] == 'i' && dtype[1] == 'n' && dtype[2] == 't') ||
            (dtype.size() >= 4 && dtype[1] == 'i' && dtype[2] == 'n' && dtype[3] == 't') ) {
            extract<int> xi(arr[0][0]);
            if( xi.check() ) {
                for(int i = 0; i < height; ++i)
                    for(int j = 0; j < width; ++j)
                        vimage[i*stride+j] = extract<int>(arr[i][j])*(1.0f/255.0f);
                return;
            }
        }

        extract<float> xr(arr[0][0]);
        if( xr.check() ) {
            for(int i = 0; i < height; ++i)
                for(int j = 0; j < width; ++j)
                    vimage[i*stride+j] = extract<float>(arr[i][j]);
            return;
        }
        extract<double> xd(arr[0][0]);
        if( xd.check() ) {
            for(int i = 0; i < height; ++i)
                for(int j = 0; j < width; ++j)
                    vimage[i*stride+j] = extract<double>(arr[i][j]);
            return;
        }

        throw siftfast_exception("array not in correct format");
    }

    int width,height,stride;
    vector<float> vimage;
};

class Image_pickle_suite : public pickle_suite
{
public:
    static tuple getinitargs(const PyImage& im)
    {
        return make_tuple(im.width,im.height,im.stride,toPyArrayN(&im.vimage[0],im.vimage.size()));
    }
};

object PyGetKeypoints(PyImage& im)
{
    struct ImageSt siftimage;
    siftimage.rows = im.height;
    siftimage.cols = im.width;
    siftimage.pixels = &im.vimage[0];
    siftimage.stride = im.stride;

    Keypoint keypts = GetKeypoints(&siftimage);

    int numkeys = 0;
    Keypoint key = keypts;
    while(key) {
        numkeys++;
        key = key->next;
    }

    npy_intp dims[2] = {numkeys,4};
    PyObject *pyframes = PyArray_SimpleNew(2,dims, PyArray_FLOAT);
    float* pframes = (float*)PyArray_DATA(pyframes);

    dims[1] = 128;
    PyObject *pydesc = PyArray_SimpleNew(2,dims, PyArray_FLOAT);
    float* pdesc = (float*)PyArray_DATA(pydesc);

    int index = 0;
    key = keypts;
    while(key) {

        for(int j = 0; j < 128; ++j)
            pdesc[128*index+j] = key->descrip[j];

        pframes[4*index+0] = key->col;
        pframes[4*index+1] = key->row;
        pframes[4*index+2] = key->ori;
        pframes[4*index+3] = key->scale;

        key = key->next;
        ++index;
    }

    FreeKeypoints(keypts);
    DestroyAllImages();

    return make_tuple(static_cast<numeric::array>(handle<>(pyframes)),static_cast<numeric::array>(handle<>(pydesc)));
}

object PyGetKeypoints(numeric::array oarray)
{
    PyImage pimage(oarray);
    return PyGetKeypoints(pimage);
}

struct DummyStruct {};

struct int_from_int
{
    int_from_int()
    {
        converter::registry::push_back(&convertible, &construct, type_id<int>());
    }

    static void* convertible( PyObject* obj)
    {
        PyObject* newobj = PyNumber_Int(obj);
        if (!PyString_Check(obj) && newobj) {
            Py_DECREF(newobj);
            return obj;
        }
        else {
            if (newobj) {
                Py_DECREF(newobj);
            }
            PyErr_Clear();
            return 0;
        }
    }

    static void construct(PyObject* _obj, converter::rvalue_from_python_stage1_data* data)
    {
        PyObject* newobj = PyNumber_Int(_obj);
        int* storage = (int*)((converter::rvalue_from_python_storage<int>*)data)->storage.bytes;
        *storage = extract<int>(newobj);
        Py_DECREF(newobj);
        data->convertible = storage;
    }
};

template<typename T>
struct T_from_number
{
    T_from_number()
    {
        converter::registry::push_back(&convertible, &construct, type_id<T>());
    }

    static void* convertible( PyObject* obj)
    {
        PyObject* newobj = PyNumber_Float(obj);
        if (!PyString_Check(obj) && newobj) {
            Py_DECREF(newobj);
            return obj;
        }
        else {
            if (newobj) {
                Py_DECREF(newobj);
            }
            PyErr_Clear();
            return 0;
        }
    }

    static void construct(PyObject* _obj, converter::rvalue_from_python_stage1_data* data)
    {
        PyObject* newobj = PyNumber_Float(_obj);
        T* storage = (T*)((converter::rvalue_from_python_storage<T>*)data)->storage.bytes;
        *storage = extract<T>(newobj);
        Py_DECREF(newobj);
        data->convertible = storage;
    }
};

int GetDoubleImSize() { return DoubleImSize; }
void SetDoubleImSize(int i) { DoubleImSize = i; }
int GetScales() { return Scales; }
void SetScales(int i) { Scales = i; }
float GetInitSigma() { return InitSigma; }
void SetInitSigma(float f) { InitSigma = f; }
float GetPeakThresh() { return PeakThresh; }
void SetPeakThresh(float f) { PeakThresh = f; }

BOOST_PYTHON_MODULE(siftfastpy)
{
    import_array();
    numeric::array::set_module_and_type("numpy", "ndarray");
    register_exception_translator<siftfast_exception>(&translate_siftfast_exception);
    int_from_int();
    T_from_number<float>();
    T_from_number<double>();

    def("DestroyAllResources",DestroyAllResources);
    object (*pkeypoints1)(PyImage&) = PyGetKeypoints;
    object (*pkeypoints2)(numeric::array) = PyGetKeypoints;
    def("GetKeypoints",pkeypoints1,args("image"));
    def("GetKeypoints",pkeypoints2,args("array"));

    class_<PyImage>("Image", no_init)
        .def(init<int,int>())
        .def(init<object>())
        .def_readonly("width",&PyImage::width)
        .def_readonly("height",&PyImage::height)
        .def("SetData",&PyImage::SetData,args("array"))
        .def_pickle(Image_pickle_suite())
        ;

    {
        scope options = class_<DummyStruct>("options")
            .add_property("DoubleImSize",GetDoubleImSize,SetDoubleImSize)
            .add_property("Scales",GetScales,SetScales)
            .add_property("InitSigma",GetInitSigma,SetInitSigma)
            .add_property("PeakThresh",GetPeakThresh,SetPeakThresh)
            ;
    }
}

ext: cpp

max_stars_repo_name: heralex/OTB

max_issues_repo_name: guandd/OTB

max_forks_repo_name: guandd/OTB


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

#include "cursor.h"
#include "search.h"

#include <iostream>

#include <algorithm>
#include <boost/crc.hpp>

namespace Akumuli {

// CursorFSM

CursorFSM::CursorFSM()
    : usr_buffer_(nullptr)
    , usr_buffer_len_(0)
    , write_offset_(0)
    , error_(false)
    , error_code_(AKU_SUCCESS)
    , complete_(false)
    , closed_(false)
{
}

CursorFSM::~CursorFSM() {
#ifdef DEBUG
    if (!closed_) {
        std::cout << "Warning in " << __FUNCTION__ << " - cursor isn't closed" << std::endl;
    }
#endif
}

void CursorFSM::update_buffer(void* buf, size_t buf_len) {
    usr_buffer_ = buf;
    usr_buffer_len_ = buf_len;
    write_offset_ = 0;
}

void CursorFSM::update_buffer(CursorFSM *other_fsm) {
    usr_buffer_ = other_fsm->usr_buffer_;
    usr_buffer_len_ = other_fsm->usr_buffer_len_;
    write_offset_ = other_fsm->write_offset_;
}

bool CursorFSM::can_put(int size) const {
    return usr_buffer_ != nullptr && (write_offset_ + size) < usr_buffer_len_;
}

void CursorFSM::put(const aku_Sample &result) {
    auto len = std::max(result.payload.size, (uint16_t)sizeof(aku_Sample));
    auto ptr = (char*)usr_buffer_ + write_offset_;
    assert(len >= sizeof(aku_Sample));
    assert((result.payload.type|aku_PData::SAX_WORD) == 0 ?
           result.payload.size == sizeof(aku_Sample) :
           result.payload.size >= sizeof(aku_Sample));
    if (len > sizeof(aku_Sample)) {
        std::cout << "CursorFSM::len " << len << std::endl;
        std::cout << "CursorFSM::write_offset_ " << write_offset_ << std::endl;
        std::cout << "CursorFSM::usr_buffer_len_ " << usr_buffer_len_ << std::endl;
    }
    memcpy(ptr, &result, len);
    write_offset_ += len;
}

bool CursorFSM::close() {
    bool old = closed_;
    closed_ = true;
    return old != closed_;
}

void CursorFSM::complete() {
    complete_ = true;
}

void CursorFSM::set_error(aku_Status error_code) {
    error_code_ = error_code;
    error_ = true;
    complete_ = true;
}

bool CursorFSM::is_done() const {
    return complete_ || closed_;
}

bool CursorFSM::get_error(aku_Status *error_code) const {
    if (error_ && error_code) {
        *error_code = error_code_;
        return true;
    }
    return error_;
}

size_t CursorFSM::get_data_len() const {
    return write_offset_;
}

// CoroCursor

void CoroCursorStackAllocator::allocate(boost::coroutines::stack_context& ctx, size_t size) const
{
    ctx.size = size;
    ctx.sp = reinterpret_cast<char*>(malloc(size)) + size;
}

void CoroCursorStackAllocator::deallocate(boost::coroutines::stack_context& ctx) const {
    free(reinterpret_cast<char*>(ctx.sp) - ctx.size);
}

// External cursor implementation

size_t CoroCursor::read_ex(void* buffer, size_t buffer_size) {
    cursor_fsm_.update_buffer(buffer, buffer_size);
    coroutine_->operator()(this);
    return cursor_fsm_.get_data_len();
}

bool CoroCursor::is_done() const {
    return cursor_fsm_.is_done();
}

bool CoroCursor::is_error(aku_Status* out_error_code_or_null) const {
    return cursor_fsm_.get_error(out_error_code_or_null);
}

void CoroCursor::close() {
    if (cursor_fsm_.close()) {
        coroutine_->operator()(this);
        coroutine_.reset();
    }
}

// Internal cursor implementation

void CoroCursor::set_error(Caller& caller, aku_Status error_code) {
    cursor_fsm_.set_error(error_code);
    caller();
}

bool CoroCursor::put(Caller& caller, aku_Sample const& result) {
    if (cursor_fsm_.is_done()) {
        return false;
    }
    if (!cursor_fsm_.can_put(std::max(result.payload.size, (uint16_t)sizeof(aku_Sample)))) {
        // yield control to client
        caller();
    }
    if (cursor_fsm_.is_done()) {
        return false;
    }
    cursor_fsm_.put(result);
    if (result.payload.type&aku_PData::URGENT) {
        caller();
    }
    return true;
}

void CoroCursor::complete(Caller& caller) {
    cursor_fsm_.complete();
    caller();
}

}

max_stars_repo_name: vladon/Akumuli

max_issues_repo_name: vladon/Akumuli

max_forks_repo_name: vladon/Akumuli


text:
/*
 *          Copyright Andrey Semashev 2007 - 2014.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   text_file_backend.cpp
 * \author Andrey Semashev
 * \date   09.06.2009
 *
 * \brief  This header is the Boost.Log library implementation, see the library documentation
 *         at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
 */

// Modification of boost implementation to alter log file rotation naming.

#include <bitcoin/bitcoin/log/file_collector.hpp>

#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <boost/spirit/home/qi/numeric/numeric_utils.hpp>

#include <bitcoin/bitcoin/compat.hpp>
#include <bitcoin/bitcoin/log/file_char_traits.hpp>
#include <bitcoin/bitcoin/log/file_collector_repository.hpp>
#include <bitcoin/bitcoin/log/file_counter_formatter.hpp>

namespace libbitcoin {
namespace log {

namespace filesystem = boost::filesystem;
namespace qi = boost::spirit::qi;

static boost::arg<1> _1;
static boost::arg<1> _2;

//! A possible Boost.Filesystem extension
//- renames or moves the file to the target storage
inline void move_file(
    filesystem::path const& from,
    filesystem::path const& to)
{
#if defined(BOOST_WINDOWS_API)
    // On Windows MoveFile already does what we need
    filesystem::rename(from, to);
#else
    // On POSIX rename fails if the target points to a different device
    boost::system::error_code ec;
    filesystem::rename(from, to, ec);
    if (ec)
    {
        if (ec.value() == boost::system::errc::cross_device_link)
        {
            // Attempt to manually move the file instead
            filesystem::copy_file(from, to);
            filesystem::remove(from);
        }
        else
        {
            BOOST_THROW_EXCEPTION(filesystem::filesystem_error(
                "failed to move file to another location", from, to, ec));
        }
    }
#endif
}

//! The function parses the format placeholder for file counter
bool parse_counter_placeholder(path_string_type::const_iterator& it,
    path_string_type::const_iterator end, unsigned int& width)
{
    typedef qi::extract_uint<unsigned int, 10, 1, -1> width_extract;

    if (it == end)
        return false;

    path_string_type::value_type c = *it;
    if (c == file_char_traits::zero || c == file_char_traits::space ||
        c == file_char_traits::plus || c == file_char_traits::minus)
    {
        // Skip filler and alignment specification
        ++it;
        if (it == end)
            return false;
        c = *it;
    }

    if (file_char_traits::is_digit(c))
    {
        // Parse width
        if (!width_extract::call(it, end, width))
            return false;
        if (it == end)
            return false;
        c = *it;
    }

    if (c == file_char_traits::dot)
    {
        // Skip precision
        ++it;
        while (it != end && file_char_traits::is_digit(*it))
            ++it;
        if (it == end)
            return false;
        c = *it;
    }

    if (c == file_char_traits::number_placeholder)
    {
        ++it;
        return true;
    }

    return false;
}

//! The function matches the file name and the pattern
bool match_pattern(path_string_type const& file_name,
    path_string_type const& pattern,
    unsigned int& file_counter)
{
    typedef qi::extract_uint<unsigned int, 10, 1, -1> file_counter_extract;

    struct local
    {
        // Verifies that the string contains exactly n digits
        static bool scan_digits(path_string_type::const_iterator& it,
            path_string_type::const_iterator end, std::ptrdiff_t n)
        {
            for (; n > 0; --n)
            {
                path_string_type::value_type c = *it++;
                if (!file_char_traits::is_digit(c) || it == end)
                    return false;
            }
            return true;
        }
    };

    path_string_type::const_iterator
        f_it = file_name.begin(),
        f_end = file_name.end(),
        p_it = pattern.begin(),
        p_end = pattern.end();
    bool placeholder_expected = false;
    while (f_it != f_end && p_it != p_end)
    {
        path_string_type::value_type p_c = *p_it,
            f_c = *f_it;

        if (!placeholder_expected)
        {
            if (p_c == file_char_traits::percent)
            {
                placeholder_expected = true;
                ++p_it;
            }
            else if (p_c == f_c)
            {
                ++p_it;
                ++f_it;
            }
            else
                return false;
        }
        else
        {
            switch (p_c)
            {
            case file_char_traits::percent: // An escaped '%'
                if (p_c == f_c)
                {
                    ++p_it;
                    ++f_it;
                    break;
                }
                else
                    return false;

            // Date/time components with 2-digits width
            case file_char_traits::seconds_placeholder:
            case file_char_traits::minutes_placeholder:
            case file_char_traits::hours_placeholder:
            case file_char_traits::day_placeholder:
            case file_char_traits::month_placeholder:
            case file_char_traits::year_placeholder:
                if (!local::scan_digits(f_it, f_end, 2))
                    return false;
                ++p_it;
                break;

            // Date/time components with 4-digits width
            case file_char_traits::full_year_placeholder:
                if (!local::scan_digits(f_it, f_end, 4))
                    return false;
                ++p_it;
                break;

            // Fraction seconds width is configuration-dependent
            case file_char_traits::frac_sec_placeholder:
                if (!local::scan_digits(f_it, f_end,
                    boost::posix_time::time_res_traits::num_fractional_digits()))
                {
                    return false;
                }
                ++p_it;
                break;

            // This should be the file counter placeholder or some unsupported placeholder
            default:
                {
                    path_string_type::const_iterator p = p_it;
                    unsigned int width = 0;
                    if (!parse_counter_placeholder(p, p_end, width))
                    {
                        BOOST_THROW_EXCEPTION(std::invalid_argument(
                            "Unsupported placeholder used in pattern for file scanning"));
                    }

                    // Find where the file number ends
                    path_string_type::const_iterator f = f_it;
                    if (!local::scan_digits(f, f_end, width))
                        return false;
                    while (f != f_end && file_char_traits::is_digit(*f))
                        ++f;

                    if (!file_counter_extract::call(f_it, f, file_counter))
                        return false;

                    p_it = p;
                }
                break;
            }

            placeholder_expected = false;
        }
    }

    if (p_it == p_end)
    {
        if (f_it != f_end)
        {
            // The actual file name may end with an additional counter
            // that is added by the collector in case if file name clash
            return local::scan_digits(f_it, f_end, std::distance(f_it, f_end));
        }
        else
            return true;
    }
    else
        return false;
}

file_collector::file_collector(
    boost::shared_ptr<file_collector_repository> const& repo,
    filesystem::path const& target_dir,
    size_t max_size,
    size_t min_free_space,
    size_t max_files)
  : repository_(repo), max_size_(max_size), min_free_space_(min_free_space),
    max_files_(max_files), base_path_(filesystem::current_path()),
    total_size_(0)
{
    storage_dir_ = make_absolute(target_dir);
    filesystem::create_directories(storage_dir_);
}

file_collector::~file_collector()
{
    repository_->remove_collector(this);
}

//! The function stores the specified file in the storage
void file_collector::store_file(filesystem::path const& src_path)
{
    // NOTE FOR THE FOLLOWING CODE:
    // Avoid using Boost.Filesystem functions that would call path::codecvt(). store_file() can be called
    // at process termination, and the global codecvt facet can already be destroyed at this point.
    // https://svn.boost.org/trac/boost/ticket/8642

    // Let's construct the new file name
    file_info info;
    info.timestamp = filesystem::last_write_time(src_path);
    info.size = filesystem::file_size(src_path);

#ifdef _MSC_VER
    path_string_type stem = src_path.stem().wstring();
    path_string_type extension = src_path.extension().wstring();
#else
    path_string_type stem = src_path.stem().string();
    path_string_type extension = src_path.extension().string();
#endif

//    info.path = storage_dir_ / file_name_path;

    // If the file already exists, try to mangle the file name
    // to ensure there's no conflict. I'll need to make this customizable some day.
    file_counter_formatter formatter(5);
    unsigned int n = 0;
    do
    {
        filesystem::path alt_file_name = formatter(stem, extension, n++);
        info.path = storage_dir_ / alt_file_name;
    }
    while (filesystem::exists(info.path) && n < (std::numeric_limits<unsigned int>::max)());

    // The directory should have been created in constructor, but just in case it got deleted since then...
    filesystem::create_directories(storage_dir_);

    BOOST_LOG_EXPR_IF_MT(boost::lock_guard<boost::mutex> lock(mutex_);)

    // Check if an old file should be erased
    uintmax_t free_space = min_free_space_ ?
        filesystem::space(storage_dir_).available : 0;

    file_list::iterator it = files_.begin(), end = files_.end();
    while (it != end &&
        (total_size_ + info.size > max_size_ || min_free_space_ > free_space || max_files_ <= files_.size()))
    {
        file_info& old_info = *it;
        if (filesystem::exists(old_info.path) && filesystem::is_regular_file(old_info.path))
        {
            try
            {
                filesystem::remove(old_info.path);
                // Free space has to be queried as it may not increase equally
                // to the erased file size on compressed filesystems
                if (min_free_space_)
                    free_space = filesystem::space(storage_dir_).available;
                total_size_ -= old_info.size;
                files_.erase(it++);
            }
            catch (boost::system::system_error&)
            {
                // Can't erase the file. Maybe it's locked? Never mind...
                ++it;
            }
        }
        else
        {
            // If it's not a file or is absent, just remove it from the list
            total_size_ -= old_info.size;
            files_.erase(it++);
        }
    }

    // Move/rename the file to the target storage
    move_file(src_path, info.path);

    files_.push_back(info);
    total_size_ += info.size;
}

//! Scans the target directory for the files that have already been stored
uintmax_t file_collector::scan_for_files(
    boost::log::sinks::file::scan_method method,
    filesystem::path const& pattern, unsigned int* counter)
{
    uintmax_t file_count = 0;
    if (method != boost::log::sinks::file::no_scan)
    {
        filesystem::path dir = storage_dir_;
        path_string_type mask;
        if (method == boost::log::sinks::file::scan_matching)
        {
            mask = filename_string(pattern);
            if (pattern.has_parent_path())
                dir = make_absolute(pattern.parent_path());
        }
        else
        {
            counter = NULL;
        }

        if (filesystem::exists(dir) && filesystem::is_directory(dir))
        {
            BOOST_LOG_EXPR_IF_MT(boost::lock_guard<boost::mutex> lock(mutex_);)

            if (counter)
                *counter = 0;

            file_list files;
            filesystem::directory_iterator it(dir), end;
            uintmax_t total_size = 0;
            for (; it != end; ++it)
            {
                file_info info;
                info.path = *it;
                if (filesystem::is_regular_file(info.path))
                {
                    // Check that there are no duplicates in the resulting list
                    struct local
                    {
                        static bool equivalent(filesystem::path const& left, file_info const& right)
                        {
                            return filesystem::equivalent(left, right.path);
                        }
                    };

                    if (std::find_if(files_.begin(), files_.end(),
                        boost::bind(&local::equivalent, boost::cref(info.path), _1)) == files_.end())
                    {
                        // Check that the file name matches the pattern
                        unsigned int file_number = 0;
                        if (method != boost::log::sinks::file::scan_matching ||
                            match_pattern(filename_string(info.path), mask, file_number))
                        {
                            info.size = filesystem::file_size(info.path);
                            total_size += info.size;
                            info.timestamp = filesystem::last_write_time(info.path);
                            files.push_back(info);
                            ++file_count;

                            if (counter && file_number >= *counter)
                                *counter = file_number + 1;
                        }
                    }
                }
            }

            // Sort files chronologically
            files_.splice(files_.end(), files);
            total_size_ += total_size;
            files_.sort(boost::bind(&file_info::timestamp, _1) < boost::bind(&file_info::timestamp, _2));
        }
    }

    return file_count;
}

//! The function updates storage restrictions
void file_collector::update(
    size_t max_size, size_t min_free_space, size_t max_files)
{
    BOOST_LOG_EXPR_IF_MT(boost::lock_guard<boost::mutex> lock(mutex_);)

    max_size_ = (std::min)(max_size_, max_size);
    min_free_space_ = (std::max)(min_free_space_, min_free_space);
    max_files_ = (std::min)(max_files_, max_files);
}

bool file_collector::is_governed(filesystem::path const& dir) const
{
    return filesystem::equivalent(storage_dir_, dir);
}

filesystem::path file_collector::make_absolute(
    filesystem::path const& path)
{
    return filesystem::absolute(path, base_path_);
}

path_string_type file_collector::filename_string(
    filesystem::path const& path)
{
    return path.filename().string<path_string_type>();
}

} // namespace log
} // namespace libbitcoin

max_stars_repo_name: anatolse/beam

max_issues_repo_name: anatolse/beam

max_forks_repo_name: anatolse/beam


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

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

/**
 * @brief wraps GenericProjectionFactor for several values to python
 * @author Ellon Paiva Mendes (LAAS-CNRS)
 **/

#include <boost/python.hpp>

#define NO_IMPORT_ARRAY
#include <numpy_eigen/NumpyEigenConverter.hpp>

#include "gtsam/slam/ProjectionFactor.h"
#include "gtsam/geometry/Pose3.h"
#include "gtsam/geometry/Point3.h"
#include "gtsam/geometry/Cal3_S2.h"

using namespace boost::python;
using namespace gtsam;

using namespace std;

typedef GenericProjectionFactor<Pose3, Point3, Cal3_S2> GenericProjectionFactorCal3_S2;

BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(print_overloads, GenericProjectionFactorCal3_S2::print, 0, 1)
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(equals_overloads, GenericProjectionFactorCal3_S2::equals, 1, 2)
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(evaluateError_overloads, GenericProjectionFactorCal3_S2::evaluateError, 2, 4)

void exportGenericProjectionFactor()
{

  class_<GenericProjectionFactorCal3_S2, bases<NonlinearFactor> >("GenericProjectionFactorCal3_S2", init<>())
    .def(init<const Point2 &, SharedNoiseModel, Key, Key, const std::shared_ptr<Cal3_S2> &, optional<Pose3> >())
    .def(init<const Point2 &, SharedNoiseModel, Key, Key, const std::shared_ptr<Cal3_S2> &, bool, bool, optional<Pose3> >())
    .def("print", &GenericProjectionFactorCal3_S2::print, print_overloads(args("s")))
    .def("equals", &GenericProjectionFactorCal3_S2::equals, equals_overloads(args("q","tol")))
    .def("evaluate_error", &GenericProjectionFactorCal3_S2::evaluateError, evaluateError_overloads())
    .def("measured", &GenericProjectionFactorCal3_S2::measured, return_value_policy<copy_const_reference>())
    // TODO(Ellon): Find the right return policy when returning a 'const shared_ptr<...> &'
    // .def("calibration", &GenericProjectionFactorCal3_S2::calibration, return_value_policy<copy_const_reference>())
    .def("verbose_cheirality", &GenericProjectionFactorCal3_S2::verboseCheirality)
    .def("throw_cheirality", &GenericProjectionFactorCal3_S2::throwCheirality)
  ;

}

max_stars_repo_name: ProfFan/gtsam

max_issues_repo_name: ProfFan/gtsam

max_forks_repo_name: ProfFan/gtsam


text:
/*
 * Copyright (c) 2014, Stanislav Vorobiov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "ScorpComponent.h"
#include "ExplosionComponent.h"
#include "Scene.h"
#include "SceneObjectFactory.h"
#include "Settings.h"
#include "Const.h"
#include "Utils.h"
#include <boost/make_shared.hpp>

namespace af
{
    ScorpComponent::ScorpComponent(const AnimationComponentPtr& ac, float walkSpeed)
    : TargetableComponent(phaseThink),
      ac_(ac),
      walkSpeed_(walkSpeed),
      state_(StateIdle),
      t_(0.0f),
      fired_(false),
      weapon_(boost::make_shared<WeaponFireballComponent>(SceneObjectTypeEnemyMissile))
    {
        weapon_->setVelocity(settings.scorp.shootVelocity);
        weapon_->setDamage(settings.scorp.shootDamage);
        weapon_->setInterval(settings.scorp.attackTime);
    }

    ScorpComponent::~ScorpComponent()
    {
    }

    void ScorpComponent::accept(ComponentVisitor& visitor)
    {
        visitor.visitPhasedComponent(shared_from_this());
    }

    void ScorpComponent::update(float dt)
    {
        if (parent()->life() <= 0) {
            SceneObjectPtr explosion = sceneObjectFactory.createExplosion3(zOrderExplosion);

            explosion->setTransform(parent()->getTransform());

            explosion->findComponent<ExplosionComponent>()->setBlast(parent()->shared_from_this(),
                settings.scorp.explosionImpulse, settings.scorp.explosionDamage,
                SceneObjectTypeEnemy);

            scene()->addObject(explosion);

            scene()->spawnPowerup(parent()->pos());

            scene()->stats()->incEnemiesKilled();

            parent()->removeFromParent();

            return;
        }

        if (!interceptBehavior_) {
            interceptBehavior_ = parent()->interceptBehavior();
        }

        if (!avoidBehavior_) {
            avoidBehavior_ = parent()->avoidBehavior();
        }

        if (!detourBehavior_) {
            detourBehavior_ = parent()->detourBehavior();
        }

        updateAutoTarget(dt);

        t_ -=  dt;

        switch (state_) {
        case StateIdle: {
            if (parent()->stunned()) {
                state_ = StateStunned;
            } else if (target()) {
                interceptBehavior_->reset();
                interceptBehavior_->setAngularVelocity(settings.scorp.turnSpeed);
                interceptBehavior_->setTarget(target());
                interceptBehavior_->start();

                state_ = StateStand;
            }
            break;
        }
        case StateStand:
            if (parent()->stunned()) {
                interceptBehavior_->reset();
                state_ = StateStunned;
            } else if (!target()) {
                interceptBehavior_->reset();
                state_ = StateIdle;
            } else if (shouldAttack()) {
                ac_->startAnimation(AnimationAttack);

                interceptBehavior_->reset();

                state_ = StateAttack;
            } else if (b2DistanceSquared(parent()->pos(), target()->pos()) >= (settings.scorp.minRadius * settings.scorp.minRadius)) {
                state_ = StateWalk;
                ac_->startAnimation(AnimationWalk);

                avoidBehavior_->reset();
                avoidBehavior_->setTypes(SceneObjectTypeEnemy);
                avoidBehavior_->setRadius(3.5f);
                avoidBehavior_->setLinearVelocity(walkSpeed_);
                avoidBehavior_->setTimeout(0.05f);
                avoidBehavior_->setLoop(true);
                avoidBehavior_->start();

                detourBehavior_->reset();
                detourBehavior_->setAheadDistance(8.0f);
                detourBehavior_->setAngularVelocity(settings.scorp.turnSpeed);
                detourBehavior_->setTimeout(0.1f);
                detourBehavior_->start();
            }
            interceptBehavior_->setTarget(target());
            break;
        case StateWalk: {
            if (parent()->stunned()) {
                ac_->setPaused(true);

                interceptBehavior_->reset();
                avoidBehavior_->reset();
                detourBehavior_->reset();

                state_ = StateStunned;
                break;
            }

            if (!target()) {
                ac_->startAnimation(AnimationDefault);

                interceptBehavior_->reset();
                avoidBehavior_->reset();
                detourBehavior_->reset();

                state_ = StateIdle;

                break;
            }

            if (shouldAttack()) {
                ac_->startAnimation(AnimationAttack);

                interceptBehavior_->reset();
                avoidBehavior_->reset();
                detourBehavior_->reset();

                state_ = StateAttack;

                break;
            }

            if (b2DistanceSquared(parent()->pos(), target()->pos()) < (settings.scorp.minRadius * settings.scorp.minRadius)) {
                interceptBehavior_->setTarget(target());

                avoidBehavior_->reset();
                detourBehavior_->reset();

                ac_->startAnimation(AnimationDefault);

                state_ = StateStand;

                break;
            }

            bool detouring = !detourBehavior_->finished();

            if (!detouring && (b2DistanceSquared(parent()->pos(), target()->pos()) > (8.0f * 8.0f))) {
                detourBehavior_->start();
            }

            if (detouring) {
                interceptBehavior_->setTarget(SceneObjectPtr());
            } else {
                interceptBehavior_->setTarget(target());
            }

            if (parent()->linearVelocity().Length() < walkSpeed_) {
                parent()->applyForceToCenter(parent()->mass() *
                    parent()->getDirection(walkSpeed_ + parent()->linearVelocityDamped()), true);
            }

            break;
        }
        case StateAttack:
            if (parent()->stunned()) {
                ac_->setPaused(true);

                state_ = StateStunned;

                fired_ = false;

                break;
            }

            if ((ac_->animationFrameIndex() >= ac_->animationSpecialIndex(0)) && !fired_) {
                weapon_->triggerOnce();
                fired_ = true;
            }

            if (ac_->animationFinished()) {
                t_ = weapon_->interval();

                ac_->startAnimation(AnimationDefault);

                state_ = StateIdle;

                fired_ = false;

                break;
            }

            break;
        case StateStunned:
            if (!parent()->stunned()) {
                ac_->setPaused(false);

                t_ = weapon_->interval();

                ac_->startAnimation(AnimationDefault);

                state_ = StateIdle;
            }
            break;
        default:
            assert(false);
            break;
        }
    }

    void ScorpComponent::onRegister()
    {
        scene()->stats()->incEnemiesSpawned();

        parent()->addComponent(weapon_);
    }

    void ScorpComponent::onUnregister()
    {
        setTarget(SceneObjectPtr());
        ac_.reset();
        interceptBehavior_.reset();
        avoidBehavior_.reset();
        detourBehavior_.reset();
    }

    bool ScorpComponent::shouldAttack()
    {
        if (t_ > 0.0f) {
            return false;
        }

        if (b2DistanceSquared(parent()->pos(), target()->pos()) > (settings.scorp.attackRadius * settings.scorp.attackRadius)) {
            return false;
        }

        float angle = fabs(angleBetween(parent()->getDirection(1.0f), target()->pos() - parent()->pos()));

        return (angle <= settings.scorp.shootAngle);
    }
}

max_stars_repo_name: Sheph/TriggerTime

max_issues_repo_name: Sheph/TriggerTime

max_forks_repo_name: Sheph/TriggerTime


text:
#ifndef CAFFE_PARALLEL_MPI_GOSSIP_PARAMS_CPU9_HPP_
#define CAFFE_PARALLEL_MPI_GOSSIP_PARAMS_CPU9_HPP_

#include <boost/date_time/posix_time/posix_time.hpp>

#include <vector>

#include "caffe/common.hpp"
#include "caffe/mpi.hpp"
#include "caffe/parallel.hpp"
#include "caffe/parallel/stats.h"
#include "caffe/solver.hpp"
#include "caffe/sgd_solvers.hpp"

namespace caffe {

template<typename Dtype>
class MPIGossipParamsCPU9 : public CPUParams<Dtype>, public Solver<Dtype>::Callback {
 public:
  explicit MPIGossipParamsCPU9(shared_ptr<Solver<Dtype> > root_solver,
          const SolverParameter& param, bool cube, bool rotate);
  virtual ~MPIGossipParamsCPU9();

  inline const shared_ptr<Solver<Dtype> >& solver() const {
    return solver_;
  }

  void Run();
  void Step(int iters);

 protected:

  void on_start();
  void on_forward(int param_id);
  void on_gradients_ready(int param_id);
  void on_gradients_ready();
  int on_apply(int param_id);
  void on_update();

  void next();
  void next_cube();
  void next_cube_rotate();
  void next_diffuse();
  void next_diffuse_rotate();

  void make_progress();

  int comm_rank_orig_;
  int comm_rank_;
  int comm_size_;
  int logp_;
  int hci_;
  int mci_;
  int send_pair_;
  int recv_pair_;
  shared_ptr<Solver<Dtype> > solver_;
  shared_ptr<SGDSolver<Dtype> > sgdsolver_;
  shared_ptr<AdamSolver<Dtype> > adamsolver_;
  const vector<Blob<Dtype>*>& params_;
  vector<MPI_Comm> comms_;
  vector<MPI_Request> requests_;
  double time_comm_;
  double time_comp_;
  stats_t stats_comm_;
  stats_t stats_comp_;
  vector<Dtype*> data_recv_;
  vector<Dtype*> hist_recv_;
  bool cube_;
  bool rotate_;
  bool first_time_;
};

}  // namespace caffe

#endif

ext: hpp

max_stars_repo_name: matex-org/caffe-intel

max_issues_repo_name: matex-org/caffe-intel

max_forks_repo_name: matex-org/caffe-intel


text:
// boost lockfree
//
// Copyright (C) 2011 Tim Blechmann
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_LOCKFREE_DETAIL_PARAMETER_HPP
#define BOOST_LOCKFREE_DETAIL_PARAMETER_HPP

#include <boost/lockfree/policies.hpp>
#include <boost/integer_traits.hpp>

namespace boost {
namespace lockfree {
namespace detail {

namespace mpl = boost::mpl;

template <typename bound_args, typename tag_type>
struct has_arg
{
    typedef typename parameter::binding<bound_args, tag_type, mpl::void_>::type type;
    static const bool value = mpl::is_not_void_<type>::type::value;
};

template <typename bound_args>
struct extract_capacity
{
    static const bool has_capacity = has_arg<bound_args, tag::capacity>::value;

    typedef typename mpl::if_c<has_capacity,
                               typename has_arg<bound_args, tag::capacity>::type,
                               mpl::size_t< boost::integer_traits<size_t>::const_max >
                              >::type capacity_t;

    static const std::size_t capacity = capacity_t::value;
};

template <typename bound_args, typename T>
struct extract_allocator
{
    static const bool has_allocator = has_arg<bound_args, tag::allocator>::value;

    typedef typename mpl::if_c<has_allocator,
                               typename has_arg<bound_args, tag::allocator>::type,
                               std::allocator<T>
                              >::type allocator_arg;

    typedef typename allocator_arg::template rebind<T>::other type;
};

template <typename bound_args, bool default_ = false>
struct extract_fixed_sized
{
    static const bool has_fixed_sized = has_arg<bound_args, tag::fixed_sized>::value;

    typedef typename mpl::if_c<has_fixed_sized,
                               typename has_arg<bound_args, tag::fixed_sized>::type,
                               mpl::bool_<default_>
                              >::type type;

    static const bool value = type::value;
};

} /* namespace detail */
} /* namespace lockfree */
} /* namespace boost */

#endif /* BOOST_LOCKFREE_DETAIL_PARAMETER_HPP */

max_stars_repo_name: juslee/boost-svn

max_issues_repo_name: juslee/boost-svn

max_forks_repo_name: juslee/boost-svn