<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medickal and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/ for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#
#include "SampleApp.h"

#include <QmitkStdMultiWidget.h>
#include <QmitkSelectableGLWidget.h>
#include <QmitkCommonFunctionality.h>

#include <mitkStatusBar.h>

#include <QmitkFunctionality.h>
#include <QmitkFunctionalityFactory.h>
#include <QmitkFctMediator.h>
#include <QmitkControlsRightFctLayoutTemplate.h>
#include <QmitkControlsLeftFctLayoutTemplate.h>

#include <qlayout.h>
#include <qlibrary.h>
#include <qfiledialog.h>
// #include "AddFunctionalityCalls.h"

void RegisterFunctionalities();

SampleApp::SampleApp( QWidget* parent, const char* name, WFlags fl ):
QmitkMainTemplate( parent, name, fl ), m_ControlsLeft ( false )
{
  RegisterFunctionalities();
  this->setCaption("MITK Application");
  std::cout << "Instantiating new SampleApp..." << std::endl;

  QmitkMainTemplate::Initialize();

  parseCommandLine();

  connect (this, SIGNAL(ShowWidgetPlanesToggled(bool)), this, SLOT(SetWidgetPlanesEnabled(bool)));
  resize(1024,768);

}
/*
*  Destroys the object and frees any allocated resources
*/
SampleApp::~SampleApp()
{
  // no need to delete child widgets, Qt does it all for us
}

void SampleApp::InitializeFunctionality()
{
  m_MultiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
  //create and add functionalities. Functionalities are also invisible objects, which can be asked to
  //create their different parts (main widget, control widget, toolbutton for selection).
  mitk::DataTreePreOrderIterator iterator(m_Tree);

  QmitkFunctionalityFactory& qff = QmitkFunctionalityFactory::GetInstance();
  for (std::list<QmitkFunctionalityFactory::CreateFunctionalityPtr>::const_iterator it = qff.GetCreateFunctionalityPtrList().begin() ; it != qff.GetCreateFunctionalityPtrList().end(); it++) {
   qfm->AddFunctionality((*it)(qfm,m_MultiWidget,&iterator));
  }

  mitk::StatusBar::GetInstance()->DisplayText("Functionalities added",3000);
}

void SampleApp::InitializeQfm()
{
  if (m_ControlsLeft) {
    //create an QmitkFctMediator. This is an invisible object that controls, manages and mediates functionalities
    qfm=new QmitkFctMediator(this);

    //create an QmitkButtonFctLayoutTemplate. This is an simple example for an layout of the different widgets, of which
    //a functionality and the management consists: the main widget, the control widget and a menu for selecting the
    //active functionality.
    QmitkControlsLeftFctLayoutTemplate* layoutTemplate=new QmitkControlsLeftFctLayoutTemplate(this, "LayoutTemplate");
    setCentralWidget(layoutTemplate);

    //let the QmitkFctMediator know about the layout. This includes the toolbar and the layoutTemplate.
    qfm->Initialize(this);
  }
  else
  {
    QmitkMainTemplate::InitializeQfm();
  }
}

void SampleApp::SetWidgetPlanesEnabled(bool enable)
{
  CommonFunctionality::SetWidgetPlanesEnabled(m_Tree, enable);
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
<commit_msg>FIX: syntax<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medickal and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/ for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "SampleApp.h"

#include <QmitkStdMultiWidget.h>
#include <QmitkSelectableGLWidget.h>
#include <QmitkCommonFunctionality.h>

#include <mitkStatusBar.h>

#include <QmitkFunctionality.h>
#include <QmitkFunctionalityFactory.h>
#include <QmitkFctMediator.h>
#include <QmitkControlsRightFctLayoutTemplate.h>
#include <QmitkControlsLeftFctLayoutTemplate.h>

#include <qlayout.h>
#include <qlibrary.h>
#include <qfiledialog.h>
// #include "AddFunctionalityCalls.h"

void RegisterFunctionalities();

SampleApp::SampleApp( QWidget* parent, const char* name, WFlags fl ):
QmitkMainTemplate( parent, name, fl ), m_ControlsLeft ( false )
{
  RegisterFunctionalities();
  this->setCaption("MITK Application");
  std::cout << "Instantiating new SampleApp..." << std::endl;

  QmitkMainTemplate::Initialize();

  parseCommandLine();

  connect (this, SIGNAL(ShowWidgetPlanesToggled(bool)), this, SLOT(SetWidgetPlanesEnabled(bool)));
  resize(1024,768);

}
/*
*  Destroys the object and frees any allocated resources
*/
SampleApp::~SampleApp()
{
  // no need to delete child widgets, Qt does it all for us
}

void SampleApp::InitializeFunctionality()
{
  m_MultiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);
  //create and add functionalities. Functionalities are also invisible objects, which can be asked to
  //create their different parts (main widget, control widget, toolbutton for selection).
  mitk::DataTreePreOrderIterator iterator(m_Tree);

  QmitkFunctionalityFactory& qff = QmitkFunctionalityFactory::GetInstance();
  for (std::list<QmitkFunctionalityFactory::CreateFunctionalityPtr>::const_iterator it = qff.GetCreateFunctionalityPtrList().begin() ; it != qff.GetCreateFunctionalityPtrList().end(); it++) {
   qfm->AddFunctionality((*it)(qfm,m_MultiWidget,&iterator));
  }

  mitk::StatusBar::GetInstance()->DisplayText("Functionalities added",3000);
}

void SampleApp::InitializeQfm()
{
  if (m_ControlsLeft) {
    //create an QmitkFctMediator. This is an invisible object that controls, manages and mediates functionalities
    qfm=new QmitkFctMediator(this);

    //create an QmitkButtonFctLayoutTemplate. This is an simple example for an layout of the different widgets, of which
    //a functionality and the management consists: the main widget, the control widget and a menu for selecting the
    //active functionality.
    QmitkControlsLeftFctLayoutTemplate* layoutTemplate=new QmitkControlsLeftFctLayoutTemplate(this, "LayoutTemplate");
    setCentralWidget(layoutTemplate);

    //let the QmitkFctMediator know about the layout. This includes the toolbar and the layoutTemplate.
    qfm->Initialize(this);
  }
  else
  {
    QmitkMainTemplate::InitializeQfm();
  }
}

void SampleApp::SetWidgetPlanesEnabled(bool enable)
{
  CommonFunctionality::SetWidgetPlanesEnabled(m_Tree, enable);
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
<|endoftext|>


<commit_before>// vrkit is (C) Copyright 2005-2007
//    by Allen Bierbaum, Aron Bierbuam, Patrick Hartling, and Daniel Shipton
//
// This file is part of vrkit.
//
// vrkit is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version.
//
// vrkit 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 program.  If not, see <http://www.gnu.org/licenses/>.

#include <OpenSG/OSGSolidBackground.h>

#include <vrkit/video/CameraFBO.h>

#ifndef GL_COLOR_ATTACHMENT0_EXT
#  define GL_COLOR_ATTACHMENT0_EXT 0x8CE0
#endif

namespace
{

bool checkGLError(const char* where)
{
   GLenum errCode = 0;
   if ((errCode = glGetError()) != GL_NO_ERROR)
   {
      const GLubyte *errString = gluErrorString(errCode);
      FWARNING(("%s OpenGL Error: %s!\n", where, errString));
   }

   return errCode == GL_NO_ERROR;
}

}

namespace vrkit
{

namespace video
{

CameraFBO::CameraFBO()
   : Camera()
   , mFboVP(OSG::NullFC)
{
   /* Do nothing. */ ;
}

CameraFBOPtr CameraFBO::create()
{
   return CameraFBOPtr(new CameraFBO);
}

CameraFBO::~CameraFBO()
{
   /* Do nothing. */ ;
}

void CameraFBO::setWindow(OSG::WindowPtr window)
{
   Camera::setWindow(window);

   OSG::beginEditCP(mFboVP);
   mFboVP->setParent(window);
   OSG::endEditCP(mFboVP);
}

CameraPtr CameraFBO::init()
{
   CameraPtr cam_ptr = Camera::init();

   OSG::SolidBackgroundPtr bg = OSG::SolidBackground::create();
   OSG::beginEditCP(bg);
      bg->setColor(OSG::Color3f(0, 0, 0));
   OSG::endEditCP(bg);

   // create FBOViewport
   mFboVP = OSG::FBOViewport::create();
   OSG::beginEditCP(mFboVP);
      mFboVP->setBackground(bg);
      mFboVP->setCamera(mCamera);
      mFboVP->getTextures().push_back(mLeftTexture);
   OSG::endEditCP(mFboVP);

   return cam_ptr;
}

void CameraFBO::setSceneRoot(OSG::NodePtr root)
{
   OSG::beginEditCP(mFboVP);
      mFboVP->setRoot(root);
   OSG::endEditCP(mFboVP);
}

void CameraFBO::setTravMask(const OSG::UInt32 value)
{
   OSG::beginEditCP(mFboVP);
      mFboVP->setTravMask(value);
   OSG::endEditCP(mFboVP);
}

void CameraFBO::setSize(const OSG::UInt32 width, const OSG::UInt32 height)
{
   if( OSG::NullFC != mFboVP)
   {
      Camera::setSize(width, height);

      // Make sure this isn't the camera calling setsize from init
      // Resize the viewport.
      OSG::beginEditCP(mFboVP);
         mFboVP->setSize(0, 0, width - 1, height - 1);
         mFboVP->setStorageWidth(width);
         mFboVP->setStorageHeight(height);
      OSG::endEditCP(mFboVP);
   }
}

void CameraFBO::render(OSG::RenderAction* ra)
{
   OSG::beginEditCP(mFboVP);
      mFboVP->getTextures()[0] = mCurrentTexture;
   OSG::endEditCP(mFboVP);

   // Do the actual rendering.
   glClear(GL_DEPTH_BUFFER_BIT);
   glPushAttrib(GL_ALL_ATTRIB_BITS);
      glPushMatrix();
         mFboVP->render(ra);
      glPopMatrix();
   glPopAttrib();

   mFboVP->bind(ra->getWindow());

   OSG::UInt32 source_width = ( mWidth / 2 ) * 2;
   OSG::UInt32 source_height = ( mHeight / 2 ) * 2;

   // If we are using an FBO, then we should change to the FBO buffer.
   glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
   checkGLError("before glReadPixels");

   // Read the buffer into an OpenSG image.
   glReadPixels(mFboVP->getPixelLeft(), mFboVP->getPixelBottom(),
                source_width, source_height, mCurrentImage->getPixelFormat(),
                GL_UNSIGNED_BYTE, mCurrentImage->getData());
   checkGLError("after glReadPixels");

   // XXX: We don't really need to change the read buffer target since we
   //      are not reading from the pixel buffer anywhere else.
   // Double buffered.
   //glReadBuffer(GL_BACK);

   mFboVP->stop(ra->getWindow());
}

}

}
<commit_msg>Const-fiy and comment.<commit_after>// vrkit is (C) Copyright 2005-2007
//    by Allen Bierbaum, Aron Bierbuam, Patrick Hartling, and Daniel Shipton
//
// This file is part of vrkit.
//
// vrkit is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version.
//
// vrkit 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 program.  If not, see <http://www.gnu.org/licenses/>.

#include <OpenSG/OSGSolidBackground.h>

#include <vrkit/video/CameraFBO.h>

#ifndef GL_COLOR_ATTACHMENT0_EXT
#  define GL_COLOR_ATTACHMENT0_EXT 0x8CE0
#endif

namespace
{

bool checkGLError(const char* where)
{
   GLenum errCode = 0;
   if ((errCode = glGetError()) != GL_NO_ERROR)
   {
      const GLubyte *errString = gluErrorString(errCode);
      FWARNING(("%s OpenGL Error: %s!\n", where, errString));
   }

   return errCode == GL_NO_ERROR;
}

}

namespace vrkit
{

namespace video
{

CameraFBO::CameraFBO()
   : Camera()
   , mFboVP(OSG::NullFC)
{
   /* Do nothing. */ ;
}

CameraFBOPtr CameraFBO::create()
{
   return CameraFBOPtr(new CameraFBO);
}

CameraFBO::~CameraFBO()
{
   /* Do nothing. */ ;
}

void CameraFBO::setWindow(OSG::WindowPtr window)
{
   Camera::setWindow(window);

   OSG::beginEditCP(mFboVP);
   mFboVP->setParent(window);
   OSG::endEditCP(mFboVP);
}

CameraPtr CameraFBO::init()
{
   CameraPtr cam_ptr = Camera::init();

   OSG::SolidBackgroundPtr bg = OSG::SolidBackground::create();
   OSG::beginEditCP(bg);
      bg->setColor(OSG::Color3f(0, 0, 0));
   OSG::endEditCP(bg);

   // create FBOViewport
   mFboVP = OSG::FBOViewport::create();
   OSG::beginEditCP(mFboVP);
      mFboVP->setBackground(bg);
      mFboVP->setCamera(mCamera);
      mFboVP->getTextures().push_back(mLeftTexture);
   OSG::endEditCP(mFboVP);

   return cam_ptr;
}

void CameraFBO::setSceneRoot(OSG::NodePtr root)
{
   OSG::beginEditCP(mFboVP);
      mFboVP->setRoot(root);
   OSG::endEditCP(mFboVP);
}

void CameraFBO::setTravMask(const OSG::UInt32 value)
{
   OSG::beginEditCP(mFboVP);
      mFboVP->setTravMask(value);
   OSG::endEditCP(mFboVP);
}

void CameraFBO::setSize(const OSG::UInt32 width, const OSG::UInt32 height)
{
   if( OSG::NullFC != mFboVP)
   {
      Camera::setSize(width, height);

      // Make sure this isn't the camera calling setsize from init
      // Resize the viewport.
      OSG::beginEditCP(mFboVP);
         mFboVP->setSize(0, 0, width - 1, height - 1);
         mFboVP->setStorageWidth(width);
         mFboVP->setStorageHeight(height);
      OSG::endEditCP(mFboVP);
   }
}

void CameraFBO::render(OSG::RenderAction* ra)
{
   OSG::beginEditCP(mFboVP);
      mFboVP->getTextures()[0] = mCurrentTexture;
   OSG::endEditCP(mFboVP);

   // Do the actual rendering.
   glClear(GL_DEPTH_BUFFER_BIT);
   glPushAttrib(GL_ALL_ATTRIB_BITS);
      glPushMatrix();
         mFboVP->render(ra);
      glPopMatrix();
   glPopAttrib();

   mFboVP->bind(ra->getWindow());

   // Ensure that width and height are multiples of two.
   const OSG::UInt32 source_width(mWidth / 2) * 2;
   const OSG::UInt32 source_height(mHeight / 2) * 2;

   // If we are using an FBO, then we should change to the FBO buffer.
   glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
   checkGLError("before glReadPixels");

   // Read the buffer into an OpenSG image.
   glReadPixels(mFboVP->getPixelLeft(), mFboVP->getPixelBottom(),
                source_width, source_height, mCurrentImage->getPixelFormat(),
                GL_UNSIGNED_BYTE, mCurrentImage->getData());
   checkGLError("after glReadPixels");

   // XXX: We don't really need to change the read buffer target since we
   //      are not reading from the pixel buffer anywhere else.
   // Double buffered.
   //glReadBuffer(GL_BACK);

   mFboVP->stop(ra->getWindow());
}

}

}
<|endoftext|>


<commit_before>#ifndef SWIFT_RANDOM_HPP
#define SWIFT_RANDOM_HPP

#include <random>
#include <chrono>

namespace swift
{
	namespace math
	{
		class Random
		{
			public:
				template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
				T operator()(T low, T high)
				{
					return std::uniform_int_distribution<T>(low, high)(generator);
				}

				template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
				T operator()(T low, T high)
				{
					return std::uniform_real_distribution<T>(low, high)(generator);
				}

				static Random& get();

			private:
				Random() {};

				static Random* rand;
				static std::mt19937 generator;
		};

		extern Random& rand;
	}
}

#endif // SWIFT_RANDOM_HPP
<commit_msg>Update Random.hpp<commit_after>#ifndef SWIFT_RANDOM_HPP
#define SWIFT_RANDOM_HPP

#include <random>
#include <chrono>

namespace swift
{
	namespace math
	{
		class Random
		{
			public:
				template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
				T operator()(T low, T high)
				{
					return std::uniform_int_distribution<T>(low, high)(generator);
				}

				template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
				T operator()(T low, T high)
				{
					return std::uniform_real_distribution<T>(low, high)(generator);
				}

			private:
				friend Random& get();

				Random() = default;

				static Random rand;
				static std::mt19937 generator;
		};

		extern Random& rand;
	}
}

#endif
<|endoftext|>


<commit_before>/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2014 Cheng Li

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 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 license for more details.
*/

#include <qlext/indexes/repo.hpp>
#include <ql/currencies/asia.hpp>
#include <ql/time/calendars/china.hpp>
#include <ql/time/daycounters/actual360.hpp>

namespace QuantLib {

    namespace {

        BusinessDayConvention repoConvention(const Period& p) {
            switch (p.units()) {
              case Days:
              case Weeks:
                return Following;
              case Months:
              case Years:
                return ModifiedFollowing;
              default:
                QL_FAIL("invalid time units");
            }
        }

    }

    Repo::Repo(const Period& tenor,
               const Handle<YieldTermStructure>& h)
    : IborIndex("Repo", tenor, (tenor == 1*Days? 0 : 1), CNYCurrency(),
                China(China::IB), repoConvention(tenor), false,
                Actual360(), h) {}
    boost::shared_ptr<IborIndex> Repo::clone(
        const Handle<YieldTermStructure>& h) const {
        return boost::shared_ptr<IborIndex>(new Repo(tenor(), h));
    }
}
<commit_msg>update repo implementation<commit_after>/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2014 Cheng Li

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 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 license for more details.
*/

#include <qlext/indexes/repo.hpp>
#include <ql/currencies/asia.hpp>
#include <ql/time/calendars/china.hpp>
#include <ql/time/daycounters/actual360.hpp>

namespace QuantLib {

    namespace {

        BusinessDayConvention repoConvention(const Period& p) {
            switch (p.units()) {
              case Days:
              case Weeks:
                return Following;
              case Months:
              case Years:
                return ModifiedFollowing;
              default:
                QL_FAIL("invalid time units");
            }
        }

    }

    Repo::Repo(const Period& tenor,
               const Handle<YieldTermStructure>& h)
    : IborIndex("Repo", tenor, (tenor == 1*Days? 0 : 1), CNYCurrency(),
                China(China::IB), repoConvention(tenor), false,
                Actual365Fixed(), h) {}
    boost::shared_ptr<IborIndex> Repo::clone(
        const Handle<YieldTermStructure>& h) const {
        return boost::shared_ptr<IborIndex>(new Repo(tenor(), h));
    }
}
<|endoftext|>


<commit_before>/*
	Copyright (c) 2017-2018 Andrew Depke
*/
#include "LinuxStackTrace.h"

#include "../../Math/MathCore.h"

#include <cxxabi.h>
#include <execinfo.h>

#include <strings.h>  // TEMPORARY FOR STACK TRACE ADDRESS TESTING

namespace Red
{
	bool CaptureStackTrace(int MaxDepth, std::vector<StackFrame>* Output)
	{
		if (!Output || MaxDepth <= 0)
		{
			return false;
		}

		size_t Frames = 0;
		void* RawStackTrace[128];

		Frames = backtrace(RawStackTrace, Min(MaxDepth, 128));

		if (Frames <= 0)
		{
			return false;
		}

		char** StackTrace = backtrace_symbols(RawStackTrace, Frames);

		for (size_t Iter = 0; Iter < Frames; ++Iter)
		{
			std::string FrameString = StackTrace[Iter];

			StackFrame Frame;

			char FrameAddressBuffer[64];
			snprintf(FrameAddressBuffer, sizeof(FrameAddressBuffer), "0x%016llX", (unsigned long long int)RawStackTrace[Iter]);  // Assume 64 Bit Addresses.

			Frame.Address = FrameAddressBuffer;

			// -- TEMPORARY FOR TESTING
			size_t AddressStart = FrameString.find('[') + 1;
			size_t AddressEnd = FrameString.find(']') - 1;

			if (strcasecmp(Frame.Address, FrameString.substr()) != 0)
			{
				throw("LINUX STACKTRACE ADDRESS MISMATCH!");
			}
			// --

			size_t ModuleNameEnd = FrameString.find('(') - 1;
			Frame.Module = FrameString.substr(0, ModuleNameEnd);

			size_t FunctionNameStart = FrameString.find('(') + 1;
			size_t FunctionNameEnd = FrameString.find('+') - 1;

#ifdef HAVE_CXA_DEMANGLE
			int OperationStatus = 0;

			char* DemangledName = abi::__cxa_demangle(FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart).c_str(), nullptr, nullptr, &OperationStatus);

			if (OperationStatus == 0)
			{
				Frame.Function = DemangledName;

				free(DemangledName);
			}

			else
			{
				Frame.Function = FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart);
			}
#else
			Frame.Function = FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart);
#endif
		}
	}
}  // namespace Red<commit_msg>Fixed Improper strcasecmp() Arguments<commit_after>/*
	Copyright (c) 2017-2018 Andrew Depke
*/
#include "LinuxStackTrace.h"

#include "../../Math/MathCore.h"

#include <cxxabi.h>
#include <execinfo.h>

#include <strings.h>  // TEMPORARY FOR STACK TRACE ADDRESS TESTING

namespace Red
{
	bool CaptureStackTrace(int MaxDepth, std::vector<StackFrame>* Output)
	{
		if (!Output || MaxDepth <= 0)
		{
			return false;
		}

		size_t Frames = 0;
		void* RawStackTrace[128];

		Frames = backtrace(RawStackTrace, Min(MaxDepth, 128));

		if (Frames <= 0)
		{
			return false;
		}

		char** StackTrace = backtrace_symbols(RawStackTrace, Frames);

		for (size_t Iter = 0; Iter < Frames; ++Iter)
		{
			std::string FrameString = StackTrace[Iter];

			StackFrame Frame;

			char FrameAddressBuffer[64];
			snprintf(FrameAddressBuffer, sizeof(FrameAddressBuffer), "0x%016llX", (unsigned long long int)RawStackTrace[Iter]);  // Assume 64 Bit Addresses.

			Frame.Address = FrameAddressBuffer;

			// -- TEMPORARY FOR TESTING
			size_t AddressStart = FrameString.find('[') + 1;
			size_t AddressEnd = FrameString.find(']') - 1;

			if (strcasecmp(Frame.Address.c_str(), FrameString.substr().c_str()) != 0)
			{
				throw("LINUX STACKTRACE ADDRESS MISMATCH!");
			}
			// --

			size_t ModuleNameEnd = FrameString.find('(') - 1;
			Frame.Module = FrameString.substr(0, ModuleNameEnd);

			size_t FunctionNameStart = FrameString.find('(') + 1;
			size_t FunctionNameEnd = FrameString.find('+') - 1;

#ifdef HAVE_CXA_DEMANGLE
			int OperationStatus = 0;

			char* DemangledName = abi::__cxa_demangle(FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart).c_str(), nullptr, nullptr, &OperationStatus);

			if (OperationStatus == 0)
			{
				Frame.Function = DemangledName;

				free(DemangledName);
			}

			else
			{
				Frame.Function = FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart);
			}
#else
			Frame.Function = FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart);
#endif
		}
	}
}  // namespace Red<|endoftext|>


<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2015 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/string_util.h"

#include <cinttypes>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <string>

#include "xenia/base/platform.h"
#include "xenia/base/vec128.h"

namespace xe {
namespace string_util {

inline std::string to_hex_string(uint32_t value) {
  char buffer[21];
  std::snprintf(buffer, sizeof(buffer), "%08" PRIX32, value);
  return std::string(buffer);
}

inline std::string to_hex_string(uint64_t value) {
  char buffer[21];
  std::snprintf(buffer, sizeof(buffer), "%016" PRIX64, value);
  return std::string(buffer);
}

inline std::string to_hex_string(const vec128_t& value) {
  char buffer[128];
  std::snprintf(buffer, sizeof(buffer), "[%.8X, %.8X, %.8X, %.8X]",
                value.u32[0], value.u32[1], value.u32[2], value.u32[3]);
  return std::string(buffer);
}

#if XE_ARCH_AMD64

// TODO(DrChat): This should not exist. Force the caller to use vec128.
inline std::string to_hex_string(const __m128& value) {
  char buffer[128];
  float f[4];
  _mm_storeu_ps(f, value);
  std::snprintf(
      buffer, sizeof(buffer), "[%.8X, %.8X, %.8X, %.8X]",
      *reinterpret_cast<uint32_t*>(&f[0]), *reinterpret_cast<uint32_t*>(&f[1]),
      *reinterpret_cast<uint32_t*>(&f[2]), *reinterpret_cast<uint32_t*>(&f[3]));
  return std::string(buffer);
}

inline std::string to_string(const __m128& value) {
  char buffer[128];
  float f[4];
  _mm_storeu_ps(f, value);
  std::snprintf(buffer, sizeof(buffer), "(%F, %F, %F, %F)", f[0], f[1], f[2], f[3]);
  return std::string(buffer);
}

#endif

}  // namespace string_util
}  // namespace xe
<commit_msg>[Base] Fix formatting in string_util.cc.<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2015 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/string_util.h"

#include <cinttypes>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <string>

#include "xenia/base/platform.h"
#include "xenia/base/vec128.h"

namespace xe {
namespace string_util {

inline std::string to_hex_string(uint32_t value) {
  char buffer[21];
  std::snprintf(buffer, sizeof(buffer), "%08" PRIX32, value);
  return std::string(buffer);
}

inline std::string to_hex_string(uint64_t value) {
  char buffer[21];
  std::snprintf(buffer, sizeof(buffer), "%016" PRIX64, value);
  return std::string(buffer);
}

inline std::string to_hex_string(const vec128_t& value) {
  char buffer[128];
  std::snprintf(buffer, sizeof(buffer), "[%.8X, %.8X, %.8X, %.8X]",
                value.u32[0], value.u32[1], value.u32[2], value.u32[3]);
  return std::string(buffer);
}

#if XE_ARCH_AMD64

// TODO(DrChat): This should not exist. Force the caller to use vec128.
inline std::string to_hex_string(const __m128& value) {
  char buffer[128];
  float f[4];
  _mm_storeu_ps(f, value);
  std::snprintf(
      buffer, sizeof(buffer), "[%.8X, %.8X, %.8X, %.8X]",
      *reinterpret_cast<uint32_t*>(&f[0]), *reinterpret_cast<uint32_t*>(&f[1]),
      *reinterpret_cast<uint32_t*>(&f[2]), *reinterpret_cast<uint32_t*>(&f[3]));
  return std::string(buffer);
}

inline std::string to_string(const __m128& value) {
  char buffer[128];
  float f[4];
  _mm_storeu_ps(f, value);
  std::snprintf(buffer, sizeof(buffer), "(%F, %F, %F, %F)", f[0], f[1], f[2],
                f[3]);
  return std::string(buffer);
}

#endif

}  // namespace string_util
}  // namespace xe
<|endoftext|>


<commit_before>/**
 * @file	src/OutPortUser.cpp
 * @date	June 2016
 * @author	PhRG - opticalp.fr
 */

/*
 Copyright (c) 2016 Ph. Renaud-Goud / Opticalp

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

#include "OutPortUser.h"

#include "Poco/NumberFormatter.h"

void OutPortUser::addOutPort(Module* parent,
		std::string name, std::string description,
        int dataType, size_t index)
{
    if (index<outPorts.size())
        outPorts[index] = new OutPort(parent, name, description, dataType, index);
    else
        poco_bugcheck_msg(("addOutPort: wrong index "
                + Poco::NumberFormatter::format(index)).c_str());
}

OutPort* OutPortUser::getOutPort(std::string portName)
{
    for (std::vector<OutPort*>::iterator it = outPorts.begin(),
            ite = outPorts.end(); it != ite; it++)
    {
        if (portName.compare((*it)->name()) == 0)
            return *it;
    }

    throw Poco::NotFoundException("getOutPort",
            "port: " + portName + " not found "
            + "in module: " + name());
}

bool OutPortUser::tryOutPortLock(size_t portIndex)
{
    OutPort* outPort = outPorts.at(portIndex);

    if (isOutPortCaught(portIndex))
        poco_bugcheck_msg("try to re-lock an output port that was already locked? ");

    if (outPort->tryLock())
    {
    	caughts->insert(portIndex);
    	return true;
    }
    else
    {
    	return false;
    }
}

void OutPortUser::notifyOutPortReady(size_t portIndex,
		DataAttributeOut attribute)
{
    if (!isOutPortCaught(portIndex))
        poco_bugcheck_msg("try to unlock an output port "
                "that was not previously locked? ");

    outPorts[portIndex]->notifyReady(attribute);

    caughts->erase(portIndex);

	if (caughts->empty())
		unlockOut();
}

void OutPortUser::notifyAllOutPortReady(DataAttributeOut attribute)
{
	if (caughts->empty())
		return;

	for (std::set<size_t>::iterator it = caughts->begin(),
			ite = caughts->end(); it != ite; it++)
		notifyOutPortReady(*it, attribute);

	caughts->clear();
	unlockOut();
}

void OutPortUser::releaseAllOutPorts()
{
	if (caughts->empty())
		return;

	for (std::set<size_t>::iterator it = caughts->begin(),
			ite = caughts->end(); it != ite; it++)
            outPorts[*it]->releaseOnFailure();

	caughts->clear();
	unlockOut();
}

void OutPortUser::reserveAllOutPorts()
{
	std::set<size_t> allPorts;

	for (size_t ind = 0; ind < outPorts.size(); ind++)
		allPorts.insert(ind);

	reserveOutPorts(allPorts);
}

void OutPortUser::reserveOutPorts(std::set<size_t> outputs)
{
	if (caughts->empty() && outputs.size())
		reserveLockOut();

	ModuleTask::RunningStates oldState = getRunningState();
	setRunningState(ModuleTask::retrievingOutDataLocks);

	while (!outputs.empty())
	{
		try
		{
			for (std::set<size_t>::iterator it = outputs.begin();
					it != outputs.end(); )
			{
				if (tryOutPortLock(*it))
				{
					std::set<size_t>::iterator itTmp = it++;
					outputs.erase(itTmp);
				}
				else
				{
					it++;
				}
			}

			if (yield())
				throw Poco::RuntimeException("reserveOutPorts",
						"Task cancellation upon user request");
		}
		catch (...)
		{
			if (caughts->empty())
				unlockOut();
			else
				releaseAllOutPorts();

			throw;
		}

//		poco_information(logger(),"Not all output ports caught. Retrying...");
	}

	setRunningState(oldState);
}

size_t OutPortUser::reserveOutPortOneOf(std::set<size_t>& outputs)
{
	if (outputs.empty())
		poco_bugcheck_msg("empty output port set to lock");

	if (caughts->empty())
		reserveLockOut();

	ModuleTask::RunningStates oldState = getRunningState();
	setRunningState(ModuleTask::retrievingOutDataLocks);

	do
	{
		for (std::set<size_t>::iterator it = outputs.begin(),
				ite = outputs.end(); it != ite; it++)
		{
			if (tryOutPortLock(*it))
			{
				size_t retValue = *it;
				outputs.erase(it);
				setRunningState(oldState);
				return retValue;
			}
		}
	}
	while (!yield());

	throw Poco::RuntimeException("reserveOutPortOneOf",
			"Task cancellation upon user request");
}

void OutPortUser::reserveOutPort(size_t output)
{
	if (caughts->empty())
		reserveLockOut();

	ModuleTask::RunningStates oldState = getRunningState();
	setRunningState(ModuleTask::retrievingOutDataLocks);

	try
	{
		while (!tryOutPortLock(output))
		{
			if (yield())
				throw Poco::RuntimeException("reserveOutPort",
						"Task cancellation upon user request");

	//		poco_information(logger(),"Output port not caught. Retrying...");
		}
	}
	catch (...)
	{
		unlockOut();
		throw;
	}

	setRunningState(oldState);
}

void OutPortUser::expireOutData()
{
	// reserveLockOut is not used here, since this method can be called
	// from outer a module task.
	Poco::Mutex::ScopedLock lock(outMutex);

    for (size_t portIndex = 0, cnt = outPorts.size();
    		portIndex < cnt; portIndex++)
        outPorts[portIndex]->expire();
}

OutPortUser::~OutPortUser()
{
    for (std::vector<OutPort*>::iterator it=outPorts.begin(), ite=outPorts.end();
            it!=ite; it++)
        delete *it;
}

void OutPortUser::reserveLockOut()
{
	while (!tryLockOut())
	{
		if (yield())
			throw Poco::RuntimeException(name(), "task cancelled upon user request");
	}
}

<commit_msg>Fix OutPortUser iterator invalidation issue<commit_after>/**
 * @file	src/OutPortUser.cpp
 * @date	June 2016
 * @author	PhRG - opticalp.fr
 */

/*
 Copyright (c) 2016 Ph. Renaud-Goud / Opticalp

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

#include "OutPortUser.h"

#include "Poco/NumberFormatter.h"

void OutPortUser::addOutPort(Module* parent,
		std::string name, std::string description,
        int dataType, size_t index)
{
    if (index<outPorts.size())
        outPorts[index] = new OutPort(parent, name, description, dataType, index);
    else
        poco_bugcheck_msg(("addOutPort: wrong index "
                + Poco::NumberFormatter::format(index)).c_str());
}

OutPort* OutPortUser::getOutPort(std::string portName)
{
    for (std::vector<OutPort*>::iterator it = outPorts.begin(),
            ite = outPorts.end(); it != ite; it++)
    {
        if (portName.compare((*it)->name()) == 0)
            return *it;
    }

    throw Poco::NotFoundException("getOutPort",
            "port: " + portName + " not found "
            + "in module: " + name());
}

bool OutPortUser::tryOutPortLock(size_t portIndex)
{
    OutPort* outPort = outPorts.at(portIndex);

    if (isOutPortCaught(portIndex))
        poco_bugcheck_msg("try to re-lock an output port that was already locked? ");

    if (outPort->tryLock())
    {
    	caughts->insert(portIndex);
    	return true;
    }
    else
    {
    	return false;
    }
}

void OutPortUser::notifyOutPortReady(size_t portIndex,
		DataAttributeOut attribute)
{
    if (!isOutPortCaught(portIndex))
        poco_bugcheck_msg("try to unlock an output port "
                "that was not previously locked? ");

    outPorts[portIndex]->notifyReady(attribute);

    caughts->erase(portIndex);

	if (caughts->empty())
		unlockOut();
}

void OutPortUser::notifyAllOutPortReady(DataAttributeOut attribute)
{
	if (caughts->empty())
		return;

	for (std::set<size_t>::iterator it = caughts->begin(),
			ite = caughts->end(); it != ite; )
	{
		size_t port = *it++;
		notifyOutPortReady(port, attribute);
	}

	poco_assert(caughts->empty());
	unlockOut();
}

void OutPortUser::releaseAllOutPorts()
{
	if (caughts->empty())
		return;

	for (std::set<size_t>::iterator it = caughts->begin(),
			ite = caughts->end(); it != ite; it++)
            outPorts[*it]->releaseOnFailure();

	caughts->clear();
	unlockOut();
}

void OutPortUser::reserveAllOutPorts()
{
	std::set<size_t> allPorts;

	for (size_t ind = 0; ind < outPorts.size(); ind++)
		allPorts.insert(ind);

	reserveOutPorts(allPorts);
}

void OutPortUser::reserveOutPorts(std::set<size_t> outputs)
{
	if (caughts->empty() && outputs.size())
		reserveLockOut();

	ModuleTask::RunningStates oldState = getRunningState();
	setRunningState(ModuleTask::retrievingOutDataLocks);

	while (!outputs.empty())
	{
		try
		{
			for (std::set<size_t>::iterator it = outputs.begin();
					it != outputs.end(); )
			{
				if (tryOutPortLock(*it))
				{
					std::set<size_t>::iterator itTmp = it++;
					outputs.erase(itTmp);
				}
				else
				{
					it++;
				}
			}

			if (yield())
				throw Poco::RuntimeException("reserveOutPorts",
						"Task cancellation upon user request");
		}
		catch (...)
		{
			if (caughts->empty())
				unlockOut();
			else
				releaseAllOutPorts();

			throw;
		}

//		poco_information(logger(),"Not all output ports caught. Retrying...");
	}

	setRunningState(oldState);
}

size_t OutPortUser::reserveOutPortOneOf(std::set<size_t>& outputs)
{
	if (outputs.empty())
		poco_bugcheck_msg("empty output port set to lock");

	if (caughts->empty())
		reserveLockOut();

	ModuleTask::RunningStates oldState = getRunningState();
	setRunningState(ModuleTask::retrievingOutDataLocks);

	do
	{
		for (std::set<size_t>::iterator it = outputs.begin(),
				ite = outputs.end(); it != ite; it++)
		{
			if (tryOutPortLock(*it))
			{
				size_t retValue = *it;
				outputs.erase(it);
				setRunningState(oldState);
				return retValue;
			}
		}
	}
	while (!yield());

	throw Poco::RuntimeException("reserveOutPortOneOf",
			"Task cancellation upon user request");
}

void OutPortUser::reserveOutPort(size_t output)
{
	if (caughts->empty())
		reserveLockOut();

	ModuleTask::RunningStates oldState = getRunningState();
	setRunningState(ModuleTask::retrievingOutDataLocks);

	try
	{
		while (!tryOutPortLock(output))
		{
			if (yield())
				throw Poco::RuntimeException("reserveOutPort",
						"Task cancellation upon user request");

	//		poco_information(logger(),"Output port not caught. Retrying...");
		}
	}
	catch (...)
	{
		unlockOut();
		throw;
	}

	setRunningState(oldState);
}

void OutPortUser::expireOutData()
{
	// reserveLockOut is not used here, since this method can be called
	// from outer a module task.
	Poco::Mutex::ScopedLock lock(outMutex);

    for (size_t portIndex = 0, cnt = outPorts.size();
    		portIndex < cnt; portIndex++)
        outPorts[portIndex]->expire();
}

OutPortUser::~OutPortUser()
{
    for (std::vector<OutPort*>::iterator it=outPorts.begin(), ite=outPorts.end();
            it!=ite; it++)
        delete *it;
}

void OutPortUser::reserveLockOut()
{
	while (!tryLockOut())
	{
		if (yield())
			throw Poco::RuntimeException(name(), "task cancelled upon user request");
	}
}

<|endoftext|>


<commit_before>// PythonStuff.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include <wx/file.h>
#include <wx/mimetype.h>
#include <wx/process.h>
#include "PythonStuff.h"
#include "ProgramCanvas.h"
#include "OutputCanvas.h"
#include "Program.h"

class CPyProcess : public wxProcess
{
protected:
	int m_pid;

public:
	CPyProcess(void): wxProcess(heeksCAD->GetMainFrame()), m_pid(0) { }

	void Execute(const wxChar* cmd);
	void Cancel(void);
	void OnTerminate(int pid, int status);

	virtual void ThenDo(void) { }
};

void CPyProcess::Execute(const wxChar* cmd)
{
	m_pid = wxExecute(cmd, wxEXEC_ASYNC, this);
}

void CPyProcess::Cancel(void)
{
	if (m_pid)
	{
		wxProcess::Kill(m_pid);
		m_pid = 0;
	}
}

void CPyProcess::OnTerminate(int pid, int status)
{
	if (pid == m_pid)
	{
		m_pid = 0;
		ThenDo();
	}
}

////////////////////////////////////////////////////////

class CPyBackPlot : public CPyProcess
{
protected:
	const CProgram* m_program;
	HeeksObj* m_into;
	wxString m_filename;

	static CPyBackPlot* m_object;

public:
	CPyBackPlot(const CProgram* program, HeeksObj* into, const wxChar* filename): m_program(program), m_into(into),m_filename(filename) { m_object = this; }
	~CPyBackPlot(void) { m_object = NULL; }

	static void StaticCancel(void) { if (m_object) m_object->Cancel(); }

	void Do(void)
	{
		if (m_program->m_machine.file_name == _T("not found"))
		{
			wxMessageBox(_T("Machine name (defined in Program Properties) not found"));
		} // End if - then
		else
		{
#ifdef WIN32
			Execute(wxString(_T("\"")) + theApp.GetDllFolder() + _T("/nc_read.bat\" ") + m_program->m_machine.file_name + _T(" \"") + m_filename + _T("\""));
#else
			Execute(wxString(_T("python \"")) + theApp.GetDllFolder() + wxString(_T("/../heekscnc/nc/") + m_program->m_machine.file_name + _T("_read.py\" ")) + wxString(_T("\"")) + m_filename + wxString(_T("\"")) );
#endif
		} // End if - else
	}
	void ThenDo(void)
	{
		// there should now be a .nc.xml written
		wxString xml_file_str = m_filename + wxString(_T(".nc.xml"));
		wxFile ofs(xml_file_str.c_str());
		if(!ofs.IsOpened())
		{
			wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + xml_file_str);
			return;
		}

		// read the xml file, just like paste, into the program
		heeksCAD->OpenXMLFile(xml_file_str, m_into);
		heeksCAD->Repaint();

		// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
		heeksCAD->GetMainFrame()->Raise();
	}
};

CPyBackPlot* CPyBackPlot::m_object = NULL;

class CPyPostProcess : public CPyProcess
{
protected:
	const CProgram* m_program;
	wxString m_filename;
	bool m_include_backplot_processing;

	static CPyPostProcess* m_object;

public:
	CPyPostProcess(const CProgram* program,
			const wxChar* filename,
			const bool include_backplot_processing = true ) :
		m_program(program), m_filename(filename), m_include_backplot_processing(include_backplot_processing)
	{
		m_object = this;
	}

	~CPyPostProcess(void) { m_object = NULL; }

	static void StaticCancel(void) { if (m_object) m_object->Cancel(); }

	void Do(void)
	{
#ifdef WIN32
		Execute(theApp.GetDllFolder() + wxString(_T("/post.bat")));
#else
		Execute(wxString(_T("python ")) + wxString(_T("/tmp/heekscnc_post.py")));
#endif
	}
	void ThenDo(void)
	{
		if (m_include_backplot_processing)
		{
			(new CPyBackPlot(m_program, (HeeksObj*)m_program, m_filename))->Do();
		}
	}
};

CPyPostProcess* CPyPostProcess::m_object = NULL;

////////////////////////////////////////////////////////

static bool write_python_file(const wxString& python_file_path)
{
	wxFile ofs(python_file_path.c_str(), wxFile::write);
	if(!ofs.IsOpened())return false;

	ofs.Write(theApp.m_program_canvas->m_textCtrl->GetValue());

	return true;
}

bool HeeksPyPostProcess(const CProgram* program, const wxString &filepath, const bool include_backplot_processing)
{
	try{
		theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window

		// write the python file
#ifdef WIN32
		wxString file_str = theApp.GetDllFolder() + wxString(_T("/post.py"));
#else
		wxString file_str = wxString(_T("/tmp/heekscnc_post.py"));
#endif
		if(!write_python_file(file_str))
		{
			wxMessageBox(_T("couldn't write post.py!"));
		}
		else
		{
#ifdef WIN32
			::wxSetWorkingDirectory(theApp.GetDllFolder());
#else
			::wxSetWorkingDirectory(wxString(_T("/tmp")));
#endif
			// call the python file
			(new CPyPostProcess(program, filepath, include_backplot_processing))->Do();

			return true;
		}
	}
	catch(...)
	{
		wxMessageBox(_T("Error while post-processing the program!"));
	}
	return false;
}

bool HeeksPyBackplot(const CProgram* program, HeeksObj* into, const wxString &filepath)
{
	try{
		theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window

		::wxSetWorkingDirectory(theApp.GetDllFolder());

		// call the python file
		(new CPyBackPlot(program, into, filepath))->Do();

		// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
		heeksCAD->GetMainFrame()->Raise();

		return true;
	}
	catch(...)
	{
		wxMessageBox(_T("Error while backplotting the program!"));
	}
	return false;
}

void HeeksPyCancel(void)
{
	CPyBackPlot::StaticCancel();
	CPyPostProcess::StaticCancel();
}
<commit_msg>I added a busy ( waiting ) cursor, for post processing.<commit_after>// PythonStuff.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include <wx/file.h>
#include <wx/mimetype.h>
#include <wx/process.h>
#include "PythonStuff.h"
#include "ProgramCanvas.h"
#include "OutputCanvas.h"
#include "Program.h"

class CPyProcess : public wxProcess
{
protected:
	int m_pid;

public:
	CPyProcess(void): wxProcess(heeksCAD->GetMainFrame()), m_pid(0) { }

	void Execute(const wxChar* cmd);
	void Cancel(void);
	void OnTerminate(int pid, int status);

	virtual void ThenDo(void) { }
};

void CPyProcess::Execute(const wxChar* cmd)
{
	m_pid = wxExecute(cmd, wxEXEC_ASYNC, this);
}

void CPyProcess::Cancel(void)
{
	if (m_pid)
	{
		wxProcess::Kill(m_pid);
		m_pid = 0;
	}
}

void CPyProcess::OnTerminate(int pid, int status)
{
	if (pid == m_pid)
	{
		m_pid = 0;
		ThenDo();
	}
}

////////////////////////////////////////////////////////

class CPyBackPlot : public CPyProcess
{
protected:
	const CProgram* m_program;
	HeeksObj* m_into;
	wxString m_filename;
	wxBusyCursor *m_busy_cursor;

	static CPyBackPlot* m_object;

public:
	CPyBackPlot(const CProgram* program, HeeksObj* into, const wxChar* filename): m_program(program), m_into(into),m_filename(filename),m_busy_cursor(NULL) { m_object = this; }
	~CPyBackPlot(void) { m_object = NULL; }

	static void StaticCancel(void) { if (m_object) m_object->Cancel(); }

	void Do(void)
	{
		if(m_busy_cursor == NULL)m_busy_cursor = new wxBusyCursor();

		if (m_program->m_machine.file_name == _T("not found"))
		{
			wxMessageBox(_T("Machine name (defined in Program Properties) not found"));
		} // End if - then
		else
		{
#ifdef WIN32
			Execute(wxString(_T("\"")) + theApp.GetDllFolder() + _T("/nc_read.bat\" ") + m_program->m_machine.file_name + _T(" \"") + m_filename + _T("\""));
#else
			Execute(wxString(_T("python \"")) + theApp.GetDllFolder() + wxString(_T("/../heekscnc/nc/") + m_program->m_machine.file_name + _T("_read.py\" ")) + wxString(_T("\"")) + m_filename + wxString(_T("\"")) );
#endif
		} // End if - else
	}
	void ThenDo(void)
	{
		// there should now be a .nc.xml written
		wxString xml_file_str = m_filename + wxString(_T(".nc.xml"));
		wxFile ofs(xml_file_str.c_str());
		if(!ofs.IsOpened())
		{
			wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + xml_file_str);
			return;
		}

		// read the xml file, just like paste, into the program
		heeksCAD->OpenXMLFile(xml_file_str, m_into);
		heeksCAD->Repaint();

		// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
		heeksCAD->GetMainFrame()->Raise();

		delete m_busy_cursor;
		m_busy_cursor = NULL;
	}
};

CPyBackPlot* CPyBackPlot::m_object = NULL;

class CPyPostProcess : public CPyProcess
{
protected:
	const CProgram* m_program;
	wxString m_filename;
	bool m_include_backplot_processing;

	static CPyPostProcess* m_object;

public:
	CPyPostProcess(const CProgram* program,
			const wxChar* filename,
			const bool include_backplot_processing = true ) :
		m_program(program), m_filename(filename), m_include_backplot_processing(include_backplot_processing)
	{
		m_object = this;
	}

	~CPyPostProcess(void) { m_object = NULL; }

	static void StaticCancel(void) { if (m_object) m_object->Cancel(); }

	void Do(void)
	{
		wxBusyCursor wait; // show an hour glass until the end of this function
#ifdef WIN32
		Execute(theApp.GetDllFolder() + wxString(_T("/post.bat")));
#else
		Execute(wxString(_T("python ")) + wxString(_T("/tmp/heekscnc_post.py")));
#endif
	}
	void ThenDo(void)
	{
		if (m_include_backplot_processing)
		{
			(new CPyBackPlot(m_program, (HeeksObj*)m_program, m_filename))->Do();
		}
	}
};

CPyPostProcess* CPyPostProcess::m_object = NULL;

////////////////////////////////////////////////////////

static bool write_python_file(const wxString& python_file_path)
{
	wxFile ofs(python_file_path.c_str(), wxFile::write);
	if(!ofs.IsOpened())return false;

	ofs.Write(theApp.m_program_canvas->m_textCtrl->GetValue());

	return true;
}

bool HeeksPyPostProcess(const CProgram* program, const wxString &filepath, const bool include_backplot_processing)
{
	try{
		theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window

		// write the python file
#ifdef WIN32
		wxString file_str = theApp.GetDllFolder() + wxString(_T("/post.py"));
#else
		wxString file_str = wxString(_T("/tmp/heekscnc_post.py"));
#endif
		if(!write_python_file(file_str))
		{
			wxMessageBox(_T("couldn't write post.py!"));
		}
		else
		{
#ifdef WIN32
			::wxSetWorkingDirectory(theApp.GetDllFolder());
#else
			::wxSetWorkingDirectory(wxString(_T("/tmp")));
#endif
			// call the python file
			(new CPyPostProcess(program, filepath, include_backplot_processing))->Do();

			return true;
		}
	}
	catch(...)
	{
		wxMessageBox(_T("Error while post-processing the program!"));
	}
	return false;
}

bool HeeksPyBackplot(const CProgram* program, HeeksObj* into, const wxString &filepath)
{
	try{
		theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window

		::wxSetWorkingDirectory(theApp.GetDllFolder());

		// call the python file
		(new CPyBackPlot(program, into, filepath))->Do();

		// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
		heeksCAD->GetMainFrame()->Raise();

		return true;
	}
	catch(...)
	{
		wxMessageBox(_T("Error while backplotting the program!"));
	}
	return false;
}

void HeeksPyCancel(void)
{
	CPyBackPlot::StaticCancel();
	CPyPostProcess::StaticCancel();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <thread>
#include <future>

#include <boost/utility/string_ref.hpp>

#include "restc-cpp/restc-cpp.h"
#include "restc-cpp/Url.h"
#include "restc-cpp/Socket.h"
#include "restc-cpp/ConnectionPool.h"
#include "restc-cpp/IoTimer.h"

// TODO: If we have a ready body in a buffer, send the header and body as two buffers

using namespace std;

namespace restc_cpp {

class RequestImpl : public Request {
public:

    RequestImpl(const std::string& url,
                const Type requestType,
                RestClient& owner,
                boost::optional<Body> body,
                const boost::optional<args_t>& args,
                const boost::optional<headers_t>& headers)
    : url_{url}, parsed_url_{url.c_str()} , request_type_{requestType}
    , owner_{owner}
    {
        if (args || headers) {
            properties_ = make_shared<Properties>(*owner_.GetConnectionProperties());

            if (args) {
                properties_->args.insert(properties_->args.end(),
                                         args->begin(), args->end());
            }

            merge_map(headers, properties_->headers);
        } else {
            properties_ = owner_.GetConnectionProperties();
        }

        if (body) {
            if (body->type_ == Body::Type::STRING) {
                assert(body->body_str_);
                body_ = move(*body->body_str_);
            }
        }
    }

    const Properties& GetProperties() const override {
        return *properties_;
    }

    void SetProperties(Properties::ptr_t propreties) override {
        properties_ = move(propreties);
    }

    const std::string& Verb(const Type requestType) {
        static const std::vector<std::string> names =
            { "GET", "POST", "PUT", "DELETE" };

        return names[static_cast<int>(requestType)];
    }

    std::string BuildOutgoingRequest() {
        static const std::string crlf{"\r\n"};
        static const std::string column{": "};

        std::ostringstream request_buffer;

        // Build the request-path
        request_buffer << Verb(request_type_) << ' '
            << parsed_url_.GetPath().to_string();

        // Add arguments to the path as ?name=value&name=value...
        bool first_arg = true;
        for(const auto& arg : properties_->args) {
            // TODO: Add escaping of strings
            if (first_arg) {
                first_arg = false;
                if (!parsed_url_.GetPath().ends_with('/')) {
                    request_buffer << '/';
                }
                request_buffer << '?';
            } else {
                request_buffer << '&';
            }

            request_buffer << arg.name<< '=' << arg.value;
        }

        request_buffer << " HTTP/1.1" << crlf;

        // Build the header buffers
        const headers_t& headers = properties_->headers;
        if (headers.find("Host") == headers.end()) {
            request_buffer << "Host: " << parsed_url_.GetHost().to_string()
                << crlf;
        }

        if (headers.find("Content-Lenght") == headers.end()) {
            request_buffer << "Content-Lenght: " << body_.size() << crlf;
        }

        for(const auto& it : headers) {
            request_buffer << it.first << column << it.second << crlf;
        }

        // End the header section.
        request_buffer << crlf;

        return request_buffer.str();
    }

    unique_ptr<Reply> Execute(Context& ctx) override {
        const Connection::Type protocol_type =
            (parsed_url_.GetProtocol() == Url::Protocol::HTTPS)
            ? Connection::Type::HTTPS
            : Connection::Type::HTTP;

        Socket::write_buffers_t write_buffer;
        ToBuffer headers(BuildOutgoingRequest());
        write_buffer.push_back(headers);
        if (!body_.empty()) {
            write_buffer.push_back({body_.data(), body_.size()});
        }

        owner_.LogDebug(headers);

        const int max_retries = 3;

        /* Loop three times (on connect or write error) over each IP
         * resolved from the hostname. Third time, ask for a new connection.
         */

        boost::asio::ip::tcp::resolver resolver(owner_.GetIoService());
        for(int attempts = 1; attempts <= max_retries; ++attempts) {
            // Resolve the hostname
            const boost::asio::ip::tcp::resolver::query query{
                parsed_url_.GetHost().to_string(),
                parsed_url_.GetPort().to_string()};

            {
                std::ostringstream msg;
                msg << "Resolving " << query.host_name() << ":"
                    << query.service_name() << endl;
                owner_.LogDebug(msg);
            }

            auto address_it = resolver.async_resolve(query,ctx.GetYield());
            decltype(address_it) addr_end;

            for(; address_it != addr_end; ++address_it) {

                const auto endpoint = address_it->endpoint();

                // Get a connection from the pool
                auto connection = owner_.GetConnectionPool().GetConnection(
                    endpoint, protocol_type, attempts == max_retries);

                // Connect if the connection is new.
                if (!connection->GetSocket().GetSocket().is_open()) {

                    std::ostringstream msg;
                    msg << "Connecting to " << endpoint << endl;
                    owner_.LogDebug(msg);

                    auto timer = IoTimer::Create(properties_->connectTimeoutMs,
                                                 owner_.GetIoService(),
                                                 connection);

                    try {
                        connection->GetSocket().AsyncConnect(
                            endpoint, ctx.GetYield());
                    } catch(const exception& ex) {
                        std::ostringstream msg;
                        msg << "Connect failed with exception type: "
                            << typeid(ex).name()
                            << ", message: " << ex.what();
                        owner_.LogDebug(msg);
                        continue;
                    }
                }

                // Send the request.
                {
                    auto timer = IoTimer::Create(properties_->connectTimeoutMs,
                                                 owner_.GetIoService(),
                                                 connection);

                    try {
                        connection->GetSocket().AsyncWrite(write_buffer,
                                                           ctx.GetYield());
                    } catch(const exception& ex) {
                        std::ostringstream msg;
                        msg << "Write failed with exception type: "
                            << typeid(ex).name()
                            << ", message: " << ex.what();
                        owner_.LogDebug(msg);
                        continue;
                    }
                }

                // Pass IO resposibility to the Reply
                auto reply = Reply::Create(connection, ctx, owner_);

                // TODO: Handle redirects
                reply->StartReceiveFromServer();

                /* Return the reply. At this time the reply headers and body
                 * is returned, and the connection can be returned to the
                 * connection-pool.
                 */

                return reply;
            }
        }

        throw runtime_error("Failed to connect");
    }

private:
    const std::string url_;
    const Url parsed_url_;
    const Type request_type_;
    std::string body_;
    Properties::ptr_t properties_;
    RestClient &owner_;
};

std::unique_ptr<Request>
Request::Create(const std::string& url,
                const Type requestType,
                RestClient& owner,
                boost::optional<Body> body,
                const boost::optional<args_t>& args,
                const boost::optional<headers_t>& headers) {

    return make_unique<RequestImpl>(url, requestType, owner, body, args, headers);
}

} // restc_cpp

<commit_msg>Minor reorg of pub/private sections<commit_after>#include <iostream>
#include <thread>
#include <future>

#include <boost/utility/string_ref.hpp>

#include "restc-cpp/restc-cpp.h"
#include "restc-cpp/Url.h"
#include "restc-cpp/Socket.h"
#include "restc-cpp/ConnectionPool.h"
#include "restc-cpp/IoTimer.h"

using namespace std;

namespace restc_cpp {

class RequestImpl : public Request {
public:

    RequestImpl(const std::string& url,
                const Type requestType,
                RestClient& owner,
                boost::optional<Body> body,
                const boost::optional<args_t>& args,
                const boost::optional<headers_t>& headers)
    : url_{url}, parsed_url_{url.c_str()} , request_type_{requestType}
    , owner_{owner}
    {
        if (args || headers) {
            properties_ = make_shared<Properties>(*owner_.GetConnectionProperties());

            if (args) {
                properties_->args.insert(properties_->args.end(),
                                         args->begin(), args->end());
            }

            merge_map(headers, properties_->headers);
        } else {
            properties_ = owner_.GetConnectionProperties();
        }

        if (body) {
            if (body->type_ == Body::Type::STRING) {
                assert(body->body_str_);
                body_ = move(*body->body_str_);
            }
        }
    }

    const Properties& GetProperties() const override {
        return *properties_;
    }

    void SetProperties(Properties::ptr_t propreties) override {
        properties_ = move(propreties);
    }

    const std::string& Verb(const Type requestType) {
        static const std::vector<std::string> names =
            { "GET", "POST", "PUT", "DELETE" };

        return names[static_cast<int>(requestType)];
    }

private:
    std::string BuildOutgoingRequest() {
        static const std::string crlf{"\r\n"};
        static const std::string column{": "};

        std::ostringstream request_buffer;

        // Build the request-path
        request_buffer << Verb(request_type_) << ' '
            << parsed_url_.GetPath().to_string();

        // Add arguments to the path as ?name=value&name=value...
        bool first_arg = true;
        for(const auto& arg : properties_->args) {
            // TODO: Add escaping of strings
            if (first_arg) {
                first_arg = false;
                if (!parsed_url_.GetPath().ends_with('/')) {
                    request_buffer << '/';
                }
                request_buffer << '?';
            } else {
                request_buffer << '&';
            }

            request_buffer << arg.name<< '=' << arg.value;
        }

        request_buffer << " HTTP/1.1" << crlf;

        // Build the header buffers
        const headers_t& headers = properties_->headers;
        if (headers.find("Host") == headers.end()) {
            request_buffer << "Host: " << parsed_url_.GetHost().to_string()
                << crlf;
        }

        if (headers.find("Content-Lenght") == headers.end()) {
            request_buffer << "Content-Lenght: " << body_.size() << crlf;
        }

        for(const auto& it : headers) {
            request_buffer << it.first << column << it.second << crlf;
        }

        // End the header section.
        request_buffer << crlf;

        return request_buffer.str();
    }

    unique_ptr<Reply> Execute(Context& ctx) override {
        const Connection::Type protocol_type =
            (parsed_url_.GetProtocol() == Url::Protocol::HTTPS)
            ? Connection::Type::HTTPS
            : Connection::Type::HTTP;

        Socket::write_buffers_t write_buffer;
        ToBuffer headers(BuildOutgoingRequest());
        write_buffer.push_back(headers);
        if (!body_.empty()) {
            write_buffer.push_back({body_.data(), body_.size()});
        }

        owner_.LogDebug(headers);

        const int max_retries = 3;

        /* Loop three times (on connect or write error) over each IP
         * resolved from the hostname. Third time, ask for a new connection.
         */

        boost::asio::ip::tcp::resolver resolver(owner_.GetIoService());
        for(int attempts = 1; attempts <= max_retries; ++attempts) {
            // Resolve the hostname
            const boost::asio::ip::tcp::resolver::query query{
                parsed_url_.GetHost().to_string(),
                parsed_url_.GetPort().to_string()};

            {
                std::ostringstream msg;
                msg << "Resolving " << query.host_name() << ":"
                    << query.service_name() << endl;
                owner_.LogDebug(msg);
            }

            auto address_it = resolver.async_resolve(query,ctx.GetYield());
            decltype(address_it) addr_end;

            for(; address_it != addr_end; ++address_it) {

                const auto endpoint = address_it->endpoint();

                // Get a connection from the pool
                auto connection = owner_.GetConnectionPool().GetConnection(
                    endpoint, protocol_type, attempts == max_retries);

                // Connect if the connection is new.
                if (!connection->GetSocket().GetSocket().is_open()) {

                    std::ostringstream msg;
                    msg << "Connecting to " << endpoint << endl;
                    owner_.LogDebug(msg);

                    auto timer = IoTimer::Create(properties_->connectTimeoutMs,
                                                 owner_.GetIoService(),
                                                 connection);

                    try {
                        connection->GetSocket().AsyncConnect(
                            endpoint, ctx.GetYield());
                    } catch(const exception& ex) {
                        std::ostringstream msg;
                        msg << "Connect failed with exception type: "
                            << typeid(ex).name()
                            << ", message: " << ex.what();
                        owner_.LogDebug(msg);
                        continue;
                    }
                }

                // Send the request.
                {
                    auto timer = IoTimer::Create(properties_->connectTimeoutMs,
                                                 owner_.GetIoService(),
                                                 connection);

                    try {
                        connection->GetSocket().AsyncWrite(write_buffer,
                                                           ctx.GetYield());
                    } catch(const exception& ex) {
                        std::ostringstream msg;
                        msg << "Write failed with exception type: "
                            << typeid(ex).name()
                            << ", message: " << ex.what();
                        owner_.LogDebug(msg);
                        continue;
                    }
                }

                // Pass IO resposibility to the Reply
                auto reply = Reply::Create(connection, ctx, owner_);

                // TODO: Handle redirects
                reply->StartReceiveFromServer();

                /* Return the reply. At this time the reply headers and body
                 * is returned, and the connection can be returned to the
                 * connection-pool.
                 */

                return reply;
            }
        }

        throw runtime_error("Failed to connect");
    }

    const std::string url_;
    const Url parsed_url_;
    const Type request_type_;
    std::string body_;
    Properties::ptr_t properties_;
    RestClient &owner_;
};

std::unique_ptr<Request>
Request::Create(const std::string& url,
                const Type requestType,
                RestClient& owner,
                boost::optional<Body> body,
                const boost::optional<args_t>& args,
                const boost::optional<headers_t>& headers) {

    return make_unique<RequestImpl>(url, requestType, owner, body, args, headers);
}

} // restc_cpp

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qbluetoothuuid.h"
#include "qbluetoothuuid_p.h"

#include <QStringList>

#include <QDebug>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>

QTM_BEGIN_NAMESPACE

// Bluetooth base UUID 00000000-0000-1000-8000-00805F9B34FB
static QUuid baseUuid(QLatin1String("{00000000-0000-1000-8000-00805F9B34FB}"));

/*!
    \class QBluetoothUuid
    \brief The QBluetoothUuid class provides a Bluetooth UUID.

    \ingroup connectivity-bluetooth
    \inmodule QtConnectivity
*/

/*!
    \enum QBluetoothUuid::ProtocolUuid

    This enum is a convienience type for Bluetooth protocol UUIDs. Values of this type will be
    implicitly converted into a QBluetoothUuid when necessary.

    \value Sdp      SDP protocol UUID.
    \value Udp      UDP protocol UUID.
    \value Rfcomm   RFCOMM protocol UUID.
    \value Tcp      TCP protocol UUID.
    \value Obex     OBEX protocol UUID.
    \value Ip       IP protocol UUID.
    \value Ftp      FTP protocol UUID.
    \value Http     HTTP protocol UUID.
    \value L2cap    L2CAP protocol UUID.
*/

/*!
    \enum QBluetoothUuid::ServiceClassUuid

    This enum is a convienience type for Bluetooth service class UUIDs. Values of this type will be
    implicitly converted into a QBluetoothUuid when necessary.

    \value PublicBrowseGroup    Public browse group service class. Services which have the public
                                browse group in their
                                \l {QBluetoothServiceInfo::BrowseGroupList}{browse group list} are
                                discoverable by remote devices.
    \value ObexObjectPush       OBEX object push service UUID.
*/

/*!
    Constructs a new null Bluetooth UUID.
*/
QBluetoothUuid::QBluetoothUuid()
{
}

/*!
    Constructs a new Bluetooth UUID from the protocol UUID \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(ProtocolUuid uuid)
:   QUuid(uuid, baseUuid.data2, baseUuid.data3, baseUuid.data4[0], baseUuid.data4[1],
          baseUuid.data4[2], baseUuid.data4[3], baseUuid.data4[4], baseUuid.data4[5],
          baseUuid.data4[6], baseUuid.data4[7])
{
}

/*!
    Constructs a new Bluetooth UUID from the service class UUID \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(ServiceClassUuid uuid)
:   QUuid(uuid, baseUuid.data2, baseUuid.data3, baseUuid.data4[0], baseUuid.data4[1],
          baseUuid.data4[2], baseUuid.data4[3], baseUuid.data4[4], baseUuid.data4[5],
          baseUuid.data4[6], baseUuid.data4[7])
{
}

/*!
    Constructs a new Bluetooth UUID from the 16 bit UUID \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(quint16 uuid)
:   QUuid(uuid, baseUuid.data2, baseUuid.data3, baseUuid.data4[0], baseUuid.data4[1],
          baseUuid.data4[2], baseUuid.data4[3], baseUuid.data4[4], baseUuid.data4[5],
          baseUuid.data4[6], baseUuid.data4[7])
{
}

/*!
    Constructs a new Bluetooth UUID from the 32 bit UUID \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(quint32 uuid)
:   QUuid(uuid, baseUuid.data2, baseUuid.data3, baseUuid.data4[0], baseUuid.data4[1],
          baseUuid.data4[2], baseUuid.data4[3], baseUuid.data4[4], baseUuid.data4[5],
          baseUuid.data4[6], baseUuid.data4[7])
{
}

/*!
    Constructs a new Bluetooth UUID from the 128 bit UUID \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(quint128 uuid)
{
    quint32 tmp32;
    memcpy(&tmp32, &uuid.data[0], 4);
    data1 = ntohl(tmp32);

    quint16 tmp16;
    memcpy(&tmp16, &uuid.data[4], 2);
    data2 = ntohs(tmp16);

    memcpy(&tmp16, &uuid.data[6], 2);
    data3 = ntohs(tmp16);

    memcpy(data4, &uuid.data[8], 8);
}

/*!
    Constructs a new Bluetooth UUID from the string \a uuid.

    The string must be in the form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.
*/
QBluetoothUuid::QBluetoothUuid(const QString &uuid)
:   QUuid(uuid)
{
}

/*!
    Constructs a new Bluetooth UUID that is a copy of \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(const QBluetoothUuid &uuid)
:   QUuid(uuid)
{
}

/*!
    Constructs a new Bluetooth UUID that is a copy of \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(const QUuid &uuid)
:   QUuid(uuid)
{
}

/*!
    Destroys the Bluetooth UUID.
*/
QBluetoothUuid::~QBluetoothUuid()
{
}

/*!
    Returns the minimum size in bytes that this UUID can be represented in.  For non-null UUIDs 2,
    4 or 16 is returned.  0 is returned for null UUIDs.

    \sa isNull(), toUInt16(), toUInt32(), toUInt128()
*/
int QBluetoothUuid::minimumSize() const
{
    if (data2 == baseUuid.data2 && data3 == baseUuid.data3 &&
        memcmp(data4, baseUuid.data4, 8) == 0) {
        // 16 or 32 bit Bluetooth UUID
        if (data1 & 0xFFFF0000)
            return 4;
        else
            return 2;
    }

    if (isNull())
        return 0;

    return 16;
}

/*!
    Returns the 16 bit representation of this UUID. If \a ok is passed it is set to true if the
    conversion is possible otherwise it is set to false. The return value is undefined if \a ok is
    set to false.
*/
quint16 QBluetoothUuid::toUInt16(bool *ok) const
{
    if (data1 & 0xFFFF0000 || data2 != baseUuid.data2 || data3 != baseUuid.data3 ||
        memcmp(data4, baseUuid.data4, 8) != 0) {
        // not convertable to 16 bit Bluetooth UUID.
        if (ok)
            *ok = false;
        return 0;
    }

    if (ok)
        *ok = true;

    return data1;
}

/*!
    Returns the 32 bit representation of this UUID. If \a ok is passed it is set to true if the
    conversion is possible otherwise it is set to false. The return value is undefined if \a ok is
    set to false.
*/
quint32 QBluetoothUuid::toUInt32(bool *ok) const
{
    if (data2 != baseUuid.data2 || data3 != baseUuid.data3 ||
        memcmp(data4, baseUuid.data4, 8) != 0) {
        // not convertable to 32 bit Bluetooth UUID.
        if (ok)
            *ok = false;
        return 0;
    }

    if (ok)
        *ok = true;

    return data1;
}

/*!
    Returns the 128 bit representation of this UUID.
*/
quint128 QBluetoothUuid::toUInt128() const
{
    quint128 uuid;

    quint32 tmp32 = htonl(data1);
    memcpy(&uuid.data[0], &tmp32, 4);

    quint16 tmp16 = htons(data2);
    memcpy(&uuid.data[4], &tmp16, 2);

    tmp16 = htons(data3);
    memcpy(&uuid.data[6], &tmp16, 2);

    memcpy(&uuid.data[8], data4, 8);

    return uuid;
}

/*!
    Returns true if \a other is equal to this Bluetooth UUID; otherwise returns false.
*/
bool QBluetoothUuid::operator==(const QBluetoothUuid &other) const
{
    return QUuid::operator==(other);
}

QTM_END_NAMESPACE
<commit_msg>Remove arpa/in.h and convert ntohl to Qt<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qbluetoothuuid.h"
#include "qbluetoothuuid_p.h"

#include <QStringList>

#include <QDebug>

#include <QtEndian>

//#include <arpa/inet.h>
//#include <netinet/in.h>
#include <string.h>

QTM_BEGIN_NAMESPACE

// Bluetooth base UUID 00000000-0000-1000-8000-00805F9B34FB
static QUuid baseUuid(QLatin1String("{00000000-0000-1000-8000-00805F9B34FB}"));

/*!
    \class QBluetoothUuid
    \brief The QBluetoothUuid class provides a Bluetooth UUID.

    \ingroup connectivity-bluetooth
    \inmodule QtConnectivity
*/

/*!
    \enum QBluetoothUuid::ProtocolUuid

    This enum is a convienience type for Bluetooth protocol UUIDs. Values of this type will be
    implicitly converted into a QBluetoothUuid when necessary.

    \value Sdp      SDP protocol UUID.
    \value Udp      UDP protocol UUID.
    \value Rfcomm   RFCOMM protocol UUID.
    \value Tcp      TCP protocol UUID.
    \value Obex     OBEX protocol UUID.
    \value Ip       IP protocol UUID.
    \value Ftp      FTP protocol UUID.
    \value Http     HTTP protocol UUID.
    \value L2cap    L2CAP protocol UUID.
*/

/*!
    \enum QBluetoothUuid::ServiceClassUuid

    This enum is a convienience type for Bluetooth service class UUIDs. Values of this type will be
    implicitly converted into a QBluetoothUuid when necessary.

    \value PublicBrowseGroup    Public browse group service class. Services which have the public
                                browse group in their
                                \l {QBluetoothServiceInfo::BrowseGroupList}{browse group list} are
                                discoverable by remote devices.
    \value ObexObjectPush       OBEX object push service UUID.
*/

/*!
    Constructs a new null Bluetooth UUID.
*/
QBluetoothUuid::QBluetoothUuid()
{
}

/*!
    Constructs a new Bluetooth UUID from the protocol UUID \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(ProtocolUuid uuid)
:   QUuid(uuid, baseUuid.data2, baseUuid.data3, baseUuid.data4[0], baseUuid.data4[1],
          baseUuid.data4[2], baseUuid.data4[3], baseUuid.data4[4], baseUuid.data4[5],
          baseUuid.data4[6], baseUuid.data4[7])
{
}

/*!
    Constructs a new Bluetooth UUID from the service class UUID \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(ServiceClassUuid uuid)
:   QUuid(uuid, baseUuid.data2, baseUuid.data3, baseUuid.data4[0], baseUuid.data4[1],
          baseUuid.data4[2], baseUuid.data4[3], baseUuid.data4[4], baseUuid.data4[5],
          baseUuid.data4[6], baseUuid.data4[7])
{
}

/*!
    Constructs a new Bluetooth UUID from the 16 bit UUID \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(quint16 uuid)
:   QUuid(uuid, baseUuid.data2, baseUuid.data3, baseUuid.data4[0], baseUuid.data4[1],
          baseUuid.data4[2], baseUuid.data4[3], baseUuid.data4[4], baseUuid.data4[5],
          baseUuid.data4[6], baseUuid.data4[7])
{
}

/*!
    Constructs a new Bluetooth UUID from the 32 bit UUID \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(quint32 uuid)
:   QUuid(uuid, baseUuid.data2, baseUuid.data3, baseUuid.data4[0], baseUuid.data4[1],
          baseUuid.data4[2], baseUuid.data4[3], baseUuid.data4[4], baseUuid.data4[5],
          baseUuid.data4[6], baseUuid.data4[7])
{
}

/*!
    Constructs a new Bluetooth UUID from the 128 bit UUID \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(quint128 uuid)
{
    // TODO: look at the memcpy(), should not be needed
    quint32 tmp32;
    memcpy(&tmp32, &uuid.data[0], 4);
    data1 = qFromBigEndian<quint32>(tmp32);

    quint16 tmp16;
    memcpy(&tmp16, &uuid.data[4], 2);
    data2 = qFromBigEndian<quint16>(tmp16);

    memcpy(&tmp16, &uuid.data[6], 2);
    data3 = qFromBigEndian<quint16>(tmp16);

    memcpy(data4, &uuid.data[8], 8);
}

/*!
    Constructs a new Bluetooth UUID from the string \a uuid.

    The string must be in the form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.
*/
QBluetoothUuid::QBluetoothUuid(const QString &uuid)
:   QUuid(uuid)
{
}

/*!
    Constructs a new Bluetooth UUID that is a copy of \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(const QBluetoothUuid &uuid)
:   QUuid(uuid)
{
}

/*!
    Constructs a new Bluetooth UUID that is a copy of \a uuid.
*/
QBluetoothUuid::QBluetoothUuid(const QUuid &uuid)
:   QUuid(uuid)
{
}

/*!
    Destroys the Bluetooth UUID.
*/
QBluetoothUuid::~QBluetoothUuid()
{
}

/*!
    Returns the minimum size in bytes that this UUID can be represented in.  For non-null UUIDs 2,
    4 or 16 is returned.  0 is returned for null UUIDs.

    \sa isNull(), toUInt16(), toUInt32(), toUInt128()
*/
int QBluetoothUuid::minimumSize() const
{
    if (data2 == baseUuid.data2 && data3 == baseUuid.data3 &&
        memcmp(data4, baseUuid.data4, 8) == 0) {
        // 16 or 32 bit Bluetooth UUID
        if (data1 & 0xFFFF0000)
            return 4;
        else
            return 2;
    }

    if (isNull())
        return 0;

    return 16;
}

/*!
    Returns the 16 bit representation of this UUID. If \a ok is passed it is set to true if the
    conversion is possible otherwise it is set to false. The return value is undefined if \a ok is
    set to false.
*/
quint16 QBluetoothUuid::toUInt16(bool *ok) const
{
    if (data1 & 0xFFFF0000 || data2 != baseUuid.data2 || data3 != baseUuid.data3 ||
        memcmp(data4, baseUuid.data4, 8) != 0) {
        // not convertable to 16 bit Bluetooth UUID.
        if (ok)
            *ok = false;
        return 0;
    }

    if (ok)
        *ok = true;

    return data1;
}

/*!
    Returns the 32 bit representation of this UUID. If \a ok is passed it is set to true if the
    conversion is possible otherwise it is set to false. The return value is undefined if \a ok is
    set to false.
*/
quint32 QBluetoothUuid::toUInt32(bool *ok) const
{
    if (data2 != baseUuid.data2 || data3 != baseUuid.data3 ||
        memcmp(data4, baseUuid.data4, 8) != 0) {
        // not convertable to 32 bit Bluetooth UUID.
        if (ok)
            *ok = false;
        return 0;
    }

    if (ok)
        *ok = true;

    return data1;
}

/*!
    Returns the 128 bit representation of this UUID.
*/
quint128 QBluetoothUuid::toUInt128() const
{
    quint128 uuid;

    quint32 tmp32 = qToBigEndian<quint32>(data1);
    memcpy(&uuid.data[0], &tmp32, 4);

    quint16 tmp16 = qToBigEndian<quint16>(data2);
    memcpy(&uuid.data[4], &tmp16, 2);

    tmp16 = qToBigEndian<quint16>(data3);
    memcpy(&uuid.data[6], &tmp16, 2);

    memcpy(&uuid.data[8], data4, 8);

    return uuid;
}

/*!
    Returns true if \a other is equal to this Bluetooth UUID; otherwise returns false.
*/
bool QBluetoothUuid::operator==(const QBluetoothUuid &other) const
{
    return QUuid::operator==(other);
}

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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)
//=======================================================================

#include "assert.hpp"
#include "SymbolTable.hpp"
#include "Types.hpp"
#include "Type.hpp"

using namespace eddic;

//Global symbol table
SymbolTable eddic::symbols;

SymbolTable::SymbolTable(){
    reset();
}

void SymbolTable::reset(){
    functions.clear();
    structs.clear();

    //Add the standard functions to the function table
    defineStandardFunctions();
}

FunctionMap::const_iterator SymbolTable::begin(){
    return functions.cbegin();
}

FunctionMap::const_iterator SymbolTable::end(){
    return functions.cend();
}

void SymbolTable::addFunction(std::shared_ptr<Function> function){
    functions[function->mangledName] = function;
}

std::shared_ptr<Function> SymbolTable::getFunction(const std::string& function){
    return functions[function];
}

bool SymbolTable::exists(const std::string& function){
    return functions.find(function) != functions.end();
}

void SymbolTable::add_struct(std::shared_ptr<Struct> struct_){
    structs[struct_->name] = struct_;
}

std::shared_ptr<Struct> SymbolTable::get_struct(const std::string& struct_){
    return structs[struct_];
}

int SymbolTable::member_offset(std::shared_ptr<Struct> struct_, const std::string& member){
    int offset = 0;

    for(auto m : struct_->members){
        if(m->name == member){
            return offset;
        }

        offset -= m->type->size();
    }

    ASSERT_PATH_NOT_TAKEN("The member is not part of the struct");
}

int SymbolTable::member_offset_reverse(std::shared_ptr<Struct> struct_, const std::string& member){
    int offset = -size_of_struct(struct_->name) + INT->size();

    for(auto m : struct_->members){
        if(m->name == member){
            return offset;
        }

        offset -= m->type->size();
    }

    ASSERT_PATH_NOT_TAKEN("The member is not part of the struct");
}

int SymbolTable::size_of_struct(const std::string& struct_name){
    int struct_size = 0;

    auto struct_ = get_struct(struct_name);

    for(auto m : struct_->members){
        struct_size += m->type->size();
    }

    return struct_size;
}

bool SymbolTable::struct_exists(const std::string& struct_){
    return structs.find(struct_) != structs.end();
}

void SymbolTable::addReference(const std::string& function){
    ++(functions[function]->references);
}

int SymbolTable::referenceCount(const std::string& function){
    return functions[function]->references;
}

void SymbolTable::addPrintFunction(const std::string& function, std::shared_ptr<Type> parameterType){
    auto printFunction = std::make_shared<Function>(VOID, "print");
    printFunction->mangledName = function;
    printFunction->parameters.push_back({"a", parameterType});
    addFunction(printFunction);
}

void SymbolTable::defineStandardFunctions(){
    //print string
    addPrintFunction("_F5printS", STRING);
    addPrintFunction("_F7printlnS", STRING);

    //print integer
    addPrintFunction("_F5printI", INT);
    addPrintFunction("_F7printlnI", INT);

    //print bool
    addPrintFunction("_F5printB", BOOL);
    addPrintFunction("_F7printlnB", BOOL);

    //print float
    addPrintFunction("_F5printF", FLOAT);
    addPrintFunction("_F7printlnF", FLOAT);

    //concat function
    auto concatFunction = std::make_shared<Function>(STRING, "concat");
    concatFunction->mangledName = "_F6concatSS";
    concatFunction->parameters.push_back({"a", STRING});
    concatFunction->parameters.push_back({"b", STRING});
    addFunction(concatFunction);

    //time function
    auto timeFunction = std::make_shared<Function>(VOID, "time");
    timeFunction->mangledName = "_F4timeAI";
    timeFunction->parameters.push_back({"a", new_array_type(BaseType::INT)});
    addFunction(timeFunction);

    //duration function
    auto durationFunction = std::make_shared<Function>(VOID, "duration");
    durationFunction->mangledName = "_F8durationAIAI";
    durationFunction->parameters.push_back({"a", new_array_type(BaseType::INT)});
    durationFunction->parameters.push_back({"b", new_array_type(BaseType::INT)});
    addFunction(durationFunction);
}
<commit_msg>Use new_type instead of new_array_type<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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)
//=======================================================================

#include "assert.hpp"
#include "SymbolTable.hpp"
#include "Types.hpp"
#include "Type.hpp"

using namespace eddic;

//Global symbol table
SymbolTable eddic::symbols;

SymbolTable::SymbolTable(){
    reset();
}

void SymbolTable::reset(){
    functions.clear();
    structs.clear();

    //Add the standard functions to the function table
    defineStandardFunctions();
}

FunctionMap::const_iterator SymbolTable::begin(){
    return functions.cbegin();
}

FunctionMap::const_iterator SymbolTable::end(){
    return functions.cend();
}

void SymbolTable::addFunction(std::shared_ptr<Function> function){
    functions[function->mangledName] = function;
}

std::shared_ptr<Function> SymbolTable::getFunction(const std::string& function){
    return functions[function];
}

bool SymbolTable::exists(const std::string& function){
    return functions.find(function) != functions.end();
}

void SymbolTable::add_struct(std::shared_ptr<Struct> struct_){
    structs[struct_->name] = struct_;
}

std::shared_ptr<Struct> SymbolTable::get_struct(const std::string& struct_){
    return structs[struct_];
}

int SymbolTable::member_offset(std::shared_ptr<Struct> struct_, const std::string& member){
    int offset = 0;

    for(auto m : struct_->members){
        if(m->name == member){
            return offset;
        }

        offset -= m->type->size();
    }

    ASSERT_PATH_NOT_TAKEN("The member is not part of the struct");
}

int SymbolTable::member_offset_reverse(std::shared_ptr<Struct> struct_, const std::string& member){
    int offset = -size_of_struct(struct_->name) + INT->size();

    for(auto m : struct_->members){
        if(m->name == member){
            return offset;
        }

        offset -= m->type->size();
    }

    ASSERT_PATH_NOT_TAKEN("The member is not part of the struct");
}

int SymbolTable::size_of_struct(const std::string& struct_name){
    int struct_size = 0;

    auto struct_ = get_struct(struct_name);

    for(auto m : struct_->members){
        struct_size += m->type->size();
    }

    return struct_size;
}

bool SymbolTable::struct_exists(const std::string& struct_){
    return structs.find(struct_) != structs.end();
}

void SymbolTable::addReference(const std::string& function){
    ++(functions[function]->references);
}

int SymbolTable::referenceCount(const std::string& function){
    return functions[function]->references;
}

void SymbolTable::addPrintFunction(const std::string& function, std::shared_ptr<Type> parameterType){
    auto printFunction = std::make_shared<Function>(VOID, "print");
    printFunction->mangledName = function;
    printFunction->parameters.push_back({"a", parameterType});
    addFunction(printFunction);
}

void SymbolTable::defineStandardFunctions(){
    //print string
    addPrintFunction("_F5printS", STRING);
    addPrintFunction("_F7printlnS", STRING);

    //print integer
    addPrintFunction("_F5printI", INT);
    addPrintFunction("_F7printlnI", INT);

    //print bool
    addPrintFunction("_F5printB", BOOL);
    addPrintFunction("_F7printlnB", BOOL);

    //print float
    addPrintFunction("_F5printF", FLOAT);
    addPrintFunction("_F7printlnF", FLOAT);

    //concat function
    auto concatFunction = std::make_shared<Function>(STRING, "concat");
    concatFunction->mangledName = "_F6concatSS";
    concatFunction->parameters.push_back({"a", STRING});
    concatFunction->parameters.push_back({"b", STRING});
    addFunction(concatFunction);

    //time function
    auto timeFunction = std::make_shared<Function>(VOID, "time");
    timeFunction->mangledName = "_F4timeAI";
    timeFunction->parameters.push_back({"a", new_type("int[]")});
    addFunction(timeFunction);

    //duration function
    auto durationFunction = std::make_shared<Function>(VOID, "duration");
    durationFunction->mangledName = "_F8durationAIAI";
    durationFunction->parameters.push_back({"a", new_type("int[]")});
    durationFunction->parameters.push_back({"b", new_type("int[]")});
    addFunction(durationFunction);
}
<|endoftext|>