<commit_before>#include <string>
#include <vector>
#include "xUnit++/xUnit++.h"

using xUnitpp::xUnitAssert;

SUITE("AssertDoesNotContain")
{

FACT("DoesNotContainForSequenceSuccess")
{
    std::vector<int> v;

    Assert.DoesNotContain(v, 0);
}

FACT("DoesNotContainForSequenceAssertsOnFailure")
{
    std::vector<int> v(1, 0);

    Assert.Throws<xUnitAssert>([&]() { Assert.DoesNotContain(v, 0); });
}

namespace TestNs_24
{
    using xUnitpp::Assert;
    std::shared_ptr<xUnitpp::Check> pCheck = std::make_shared<xUnitpp::Check>();
    class TestFixture_24 : public xUnitpp::NoFixture
    {
        TestFixture_24 &operator =(TestFixture_24);
    public:
        TestFixture_24() : Check(*pCheck) { }
        void TestFn_24();

        const xUnitpp::Check &Check;
    };
    void TestRunner_24()
    {
        TestFixture_24().TestFn_24();
    }
    xUnitpp::TestCollection::Register reg(xUnitpp::TestCollection::Instance(), &TestRunner_24, "ContainsForSequenceAppendsUserMessage", xUnitSuite::Name(), xUnitAttributes::Attributes(), -1, "assert.contains.cpp", 24, pCheck);
}
void TestNs_24 :: TestFixture_24 :: TestFn_24()
{
    static const std::string msg = "xUnit++";
    std::vector<int> v;

    auto assert = Assert.Throws<xUnitAssert>([&]() { Assert.Contains(v, 0) << msg; });
    auto what = std::string(assert.what());

    Assert.NotEqual(std::string::npos, what.find(msg));
}

FACT("DoesNotContainForSequenceAppendsUserMessage")
{
    static const std::string msg = "xUnit++";
    std::vector<int> v(1, 0);

    auto assert = Assert.Throws<xUnitAssert>([&]() { Assert.DoesNotContain(v, 0) << msg; });

    Assert.Contains(assert.what(), msg.c_str());
}

FACT("DoesNotContainForStringSuccess")
{
    std::string actual = "abcd";

    Assert.DoesNotContain(actual, "xyz");
}

FACT("DoesNotContainForStringAssertsOnFailure")
{
    std::string actual = "abcd";

    Assert.Throws<xUnitAssert>([&]() { Assert.DoesNotContain(actual, "bc"); });
}

FACT("DoesNotContainForStringAppendsUserMessage")
{
    static const std::string msg = "xUnit++";
    std::string actual = "abcd";

    auto assert = Assert.Throws<xUnitAssert>([&]() { Assert.DoesNotContain(actual, "ab") << msg; });

    Assert.Contains(assert.what(), msg.c_str());
}

}<commit_msg>removed some debugging code<commit_after>#include <string>
#include <vector>
#include "xUnit++/xUnit++.h"

using xUnitpp::xUnitAssert;

SUITE("AssertDoesNotContain")
{

FACT("DoesNotContainForSequenceSuccess")
{
    std::vector<int> v;

    Assert.DoesNotContain(v, 0);
}

FACT("DoesNotContainForSequenceAssertsOnFailure")
{
    std::vector<int> v(1, 0);

    Assert.Throws<xUnitAssert>([&]() { Assert.DoesNotContain(v, 0); });
}

FACT("DoesNotContainForSequenceAppendsUserMessage")
{
    static const std::string msg = "xUnit++";
    std::vector<int> v(1, 0);

    auto assert = Assert.Throws<xUnitAssert>([&]() { Assert.DoesNotContain(v, 0) << msg; });

    Assert.Contains(assert.what(), msg.c_str());
}

FACT("DoesNotContainForStringSuccess")
{
    std::string actual = "abcd";

    Assert.DoesNotContain(actual, "xyz");
}

FACT("DoesNotContainForStringAssertsOnFailure")
{
    std::string actual = "abcd";

    Assert.Throws<xUnitAssert>([&]() { Assert.DoesNotContain(actual, "bc"); });
}

FACT("DoesNotContainForStringAppendsUserMessage")
{
    static const std::string msg = "xUnit++";
    std::string actual = "abcd";

    auto assert = Assert.Throws<xUnitAssert>([&]() { Assert.DoesNotContain(actual, "ab") << msg; });

    Assert.Contains(assert.what(), msg.c_str());
}

}<|endoftext|>


<commit_before>/************************************************************************
	filename: 	WLTitlebar.cpp
	created:	8/8/2004
	author:		Paul D Turner
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

    This library 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.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "WLTitlebar.h"
#include "CEGUIImageset.h"
#include "CEGUIFont.h"
#include "elements/CEGUIFrameWindow.h"

// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
	Constants
*************************************************************************/
const utf8	WLTitlebar::WidgetTypeName[]			= "WindowsLook/Titlebar";

const utf8	WLTitlebar::ImagesetName[]				= "WindowsLook";
const utf8	WLTitlebar::LeftEndSectionImageName[]	= "TitlebarLeft";
const utf8	WLTitlebar::MiddleSectionImageName[]	= "TitlebarMiddle";
const utf8	WLTitlebar::RightEndSectionImageName[]	= "TitlebarRight";
const utf8	WLTitlebar::NormalCursorImageName[]		= "MouseMoveCursor";
const utf8	WLTitlebar::NoDragCursorImageName[]		= "MouseArrow";

// colours
const colour WLTitlebar::ActiveColour		= 0xA7C7FF;
const colour WLTitlebar::InactiveColour		= 0xEFEFEF;
const colour WLTitlebar::CaptionColour		= 0x000000;

/*************************************************************************
	Constructor
*************************************************************************/
WLTitlebar::WLTitlebar(const String& type, const String& name) :
	Titlebar(type, name)
{
	// get images
	Imageset* iset = ImagesetManager::getSingleton().getImageset(ImagesetName);

	d_leftImage		= &iset->getImage(LeftEndSectionImageName);
	d_middleImage	= &iset->getImage(MiddleSectionImageName);
	d_rightImage	= &iset->getImage(RightEndSectionImageName);

	// default text colour
	d_captionColour = CaptionColour;

	// set cursor
	setMouseCursor(&iset->getImage(NormalCursorImageName));

	setAlwaysOnTop(false);
}

/*************************************************************************
	Destructor
*************************************************************************/
WLTitlebar::~WLTitlebar(void)
{
}

/*************************************************************************
	return a Rect object describing the appropriately clipped Window
	area in screen space.
*************************************************************************/
Rect WLTitlebar::getPixelRect(void) const
{
	// clip to screen if we have no grand-parent
	if ((d_parent == NULL) || (d_parent->getParent() == NULL))
	{
		return System::getSingleton().getRenderer()->getRect().getIntersection(getUnclippedPixelRect());
	}
	// else clip to grand-parent
	else
	{
		return d_parent->getParent()->getInnerRect().getIntersection(getUnclippedPixelRect());
	}

}

/*************************************************************************
	Perform the actual rendering for this widget.
*************************************************************************/
void WLTitlebar::drawSelf(float z)
{
	Rect clipper(getPixelRect());

	// do nothing if the widget is totally clipped.
	if (clipper.getWidth() == 0)
	{
		return;
	}

	// get the destination screen rect for this window
	Rect absrect(getUnclippedPixelRect());

	// calculate colours to use.
	float alpha_comp = getEffectiveAlpha();
	ColourRect colours(((d_parent != NULL) && d_parent->isActive()) ? ActiveColour : InactiveColour);
	colours.setAlpha(alpha_comp);

	// calculate widths for the title bar segments
	float leftWidth		= d_leftImage->getWidth();
	float rightWidth	= d_rightImage->getWidth();
	float midWidth		= absrect.getWidth() - leftWidth - rightWidth;

	//
	// draw the title bar images
	//
	Vector3 pos(absrect.d_left, absrect.d_top, z);
	Size	sz(leftWidth, absrect.getHeight());
	d_leftImage->draw(pos, sz, clipper, colours);
	pos.d_x += sz.d_width;

	sz.d_width = midWidth;
	d_middleImage->draw(pos, sz, clipper, colours);
	pos.d_x += sz.d_width;

	sz.d_width = rightWidth;
	d_rightImage->draw(pos, sz, clipper, colours);

	//
	// Draw the title text
	//
	colours.setColours(CaptionColour);
	colours.setAlpha(alpha_comp);

	Rect textClipper(clipper);
	textClipper.setWidth(midWidth);
	textClipper = clipper.getIntersection(textClipper);

	pos.d_x = absrect.d_left + leftWidth;
	pos.d_y = absrect.d_top + PixelAligned((absrect.getHeight() - getFont()->getLineSpacing()) * 0.5f);
	pos.d_z = System::getSingleton().getRenderer()->getZLayer(1);

	getFont()->drawText(d_parent->getText(), pos, textClipper, colours);
}

/*************************************************************************
	Handler for when drag mode changes
*************************************************************************/
void WLTitlebar::onDraggingModeChanged(WindowEventArgs& e)
{
	// base class processing
	Titlebar::onDraggingModeChanged(e);

	// change cursor depending on new mode.
	if (d_dragEnabled)
	{
		setMouseCursor(&ImagesetManager::getSingleton().getImageset(ImagesetName)->getImage(NormalCursorImageName));
	}
	else
	{
		setMouseCursor(&ImagesetManager::getSingleton().getImageset(ImagesetName)->getImage(NoDragCursorImageName));
	}

	requestRedraw();

	e.handled = true;
}

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

	Factory Methods

*************************************************************************/
//////////////////////////////////////////////////////////////////////////
/*************************************************************************
	Create, initialise and return a WLTitlebar
*************************************************************************/
Window* WLTitlebarFactory::createWindow(const String& name)
{
	WLTitlebar* wnd = new WLTitlebar(d_type, name);
	wnd->initialise();

	return wnd;
}

} // End of  CEGUI namespace section
<commit_msg>Bug Fix: WindowsLook titlebar was not using correct set caption colour.<commit_after>/************************************************************************
	filename: 	WLTitlebar.cpp
	created:	8/8/2004
	author:		Paul D Turner
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

    This library 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.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "WLTitlebar.h"
#include "CEGUIImageset.h"
#include "CEGUIFont.h"
#include "elements/CEGUIFrameWindow.h"

// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
	Constants
*************************************************************************/
const utf8	WLTitlebar::WidgetTypeName[]			= "WindowsLook/Titlebar";

const utf8	WLTitlebar::ImagesetName[]				= "WindowsLook";
const utf8	WLTitlebar::LeftEndSectionImageName[]	= "TitlebarLeft";
const utf8	WLTitlebar::MiddleSectionImageName[]	= "TitlebarMiddle";
const utf8	WLTitlebar::RightEndSectionImageName[]	= "TitlebarRight";
const utf8	WLTitlebar::NormalCursorImageName[]		= "MouseMoveCursor";
const utf8	WLTitlebar::NoDragCursorImageName[]		= "MouseArrow";

// colours
const colour WLTitlebar::ActiveColour		= 0xA7C7FF;
const colour WLTitlebar::InactiveColour		= 0xEFEFEF;
const colour WLTitlebar::CaptionColour		= 0x000000;

/*************************************************************************
	Constructor
*************************************************************************/
WLTitlebar::WLTitlebar(const String& type, const String& name) :
	Titlebar(type, name)
{
	// get images
	Imageset* iset = ImagesetManager::getSingleton().getImageset(ImagesetName);

	d_leftImage		= &iset->getImage(LeftEndSectionImageName);
	d_middleImage	= &iset->getImage(MiddleSectionImageName);
	d_rightImage	= &iset->getImage(RightEndSectionImageName);

	// default text colour
	d_captionColour = CaptionColour;

	// set cursor
	setMouseCursor(&iset->getImage(NormalCursorImageName));

	setAlwaysOnTop(false);
}

/*************************************************************************
	Destructor
*************************************************************************/
WLTitlebar::~WLTitlebar(void)
{
}

/*************************************************************************
	return a Rect object describing the appropriately clipped Window
	area in screen space.
*************************************************************************/
Rect WLTitlebar::getPixelRect(void) const
{
	// clip to screen if we have no grand-parent
	if ((d_parent == NULL) || (d_parent->getParent() == NULL))
	{
		return System::getSingleton().getRenderer()->getRect().getIntersection(getUnclippedPixelRect());
	}
	// else clip to grand-parent
	else
	{
		return d_parent->getParent()->getInnerRect().getIntersection(getUnclippedPixelRect());
	}

}

/*************************************************************************
	Perform the actual rendering for this widget.
*************************************************************************/
void WLTitlebar::drawSelf(float z)
{
	Rect clipper(getPixelRect());

	// do nothing if the widget is totally clipped.
	if (clipper.getWidth() == 0)
	{
		return;
	}

	// get the destination screen rect for this window
	Rect absrect(getUnclippedPixelRect());

	// calculate colours to use.
	float alpha_comp = getEffectiveAlpha();
	ColourRect colours(((d_parent != NULL) && d_parent->isActive()) ? ActiveColour : InactiveColour);
	colours.setAlpha(alpha_comp);

	// calculate widths for the title bar segments
	float leftWidth		= d_leftImage->getWidth();
	float rightWidth	= d_rightImage->getWidth();
	float midWidth		= absrect.getWidth() - leftWidth - rightWidth;

	//
	// draw the title bar images
	//
	Vector3 pos(absrect.d_left, absrect.d_top, z);
	Size	sz(leftWidth, absrect.getHeight());
	d_leftImage->draw(pos, sz, clipper, colours);
	pos.d_x += sz.d_width;

	sz.d_width = midWidth;
	d_middleImage->draw(pos, sz, clipper, colours);
	pos.d_x += sz.d_width;

	sz.d_width = rightWidth;
	d_rightImage->draw(pos, sz, clipper, colours);

	//
	// Draw the title text
	//
	colours.setColours(d_captionColour);
	colours.setAlpha(alpha_comp);

	Rect textClipper(clipper);
	textClipper.setWidth(midWidth);
	textClipper = clipper.getIntersection(textClipper);

	pos.d_x = absrect.d_left + leftWidth;
	pos.d_y = absrect.d_top + PixelAligned((absrect.getHeight() - getFont()->getLineSpacing()) * 0.5f);
	pos.d_z = System::getSingleton().getRenderer()->getZLayer(1);

	getFont()->drawText(d_parent->getText(), pos, textClipper, colours);
}

/*************************************************************************
	Handler for when drag mode changes
*************************************************************************/
void WLTitlebar::onDraggingModeChanged(WindowEventArgs& e)
{
	// base class processing
	Titlebar::onDraggingModeChanged(e);

	// change cursor depending on new mode.
	if (d_dragEnabled)
	{
		setMouseCursor(&ImagesetManager::getSingleton().getImageset(ImagesetName)->getImage(NormalCursorImageName));
	}
	else
	{
		setMouseCursor(&ImagesetManager::getSingleton().getImageset(ImagesetName)->getImage(NoDragCursorImageName));
	}

	requestRedraw();

	e.handled = true;
}

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

	Factory Methods

*************************************************************************/
//////////////////////////////////////////////////////////////////////////
/*************************************************************************
	Create, initialise and return a WLTitlebar
*************************************************************************/
Window* WLTitlebarFactory::createWindow(const String& name)
{
	WLTitlebar* wnd = new WLTitlebar(d_type, name);
	wnd->initialise();

	return wnd;
}

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>#include <crab/config.h>
#include <crab/common/stats.hpp>

#ifndef CRAB_STATS
namespace crab {
Stopwatch::Stopwatch() {}
void Stopwatch::start() {}
void Stopwatch::stop() {}
void Stopwatch::resume() {}
long Stopwatch::systemTime() const { return (long)0;}
long Stopwatch::getTimeElapsed() const { return (long)0;}
double Stopwatch::toSeconds() { return (double)0;}
void Stopwatch::Print(crab_os &out) const {}
void CrabStats::reset() {}
void CrabStats::count(const std::string &name) {}
void CrabStats::count_max(const std::string &name, unsigned v) {}
unsigned CrabStats::uset(const std::string &n, unsigned v) { return (unsigned)0;}
unsigned CrabStats::get(const std::string &n) { return (unsigned)0;}
void CrabStats::start(const std::string &name) {}
void CrabStats::stop(const std::string &name) {}
void CrabStats::resume(const std::string &name) {}

/** Outputs all statistics to std output */
void CrabStats::Print(crab_os &OS) {
  OS << "\n\n************** STATS ***************** \n";
  OS << "Crab compiled with support for gathering stats. "
     << "Compile Crab with -DCRAB_ENABLE_STATS=ON\n";
  OS << "************** STATS END ***************** \n";
}

void CrabStats::PrintBrunch(crab_os &OS) {
  OS << "\n\n************** BRUNCH STATS ***************** \n";
  OS << "Crab compiled with support for gathering stats. "
     << "Compile Crab with -DCRAB_ENABLE_STATS=ON\n";
  OS << "************** BRUNCH STATS END ***************** \n";
}

ScopedCrabStats::ScopedCrabStats(const std::string &name, bool reset): m_name("") {}
ScopedCrabStats::~ScopedCrabStats() {}
#else
/* Real implementation stars here */
#include <sys/resource.h>
#include <sys/time.h>

namespace crab {

std::map<std::string, unsigned> CrabStats::counters;
std::map<std::string, Stopwatch> CrabStats::sw;

long Stopwatch::systemTime() const {
  struct rusage ru;
  getrusage(RUSAGE_SELF, &ru);
  long r = ru.ru_utime.tv_sec * 1000000L + ru.ru_utime.tv_usec;
  return r;
}

Stopwatch::Stopwatch() { start(); }

void Stopwatch::start() {
  started = systemTime();
  finished = -1;
  timeElapsed = 0;
}

void Stopwatch::stop() {
  if (finished < started) {
    finished = systemTime();
  }
}

void Stopwatch::resume() {
  if (finished >= started) {
    timeElapsed += finished - started;
    started = systemTime();
    finished = -1;
  }
}

long Stopwatch::getTimeElapsed() const {
  if (finished < started)
    return timeElapsed + systemTime() - started;
  else
    return timeElapsed + finished - started;
}

double Stopwatch::toSeconds() {
  double time = ((double)getTimeElapsed() / 1000000);
  return time;
}

void Stopwatch::Print(crab_os &out) const {
  long time = getTimeElapsed();
  long h = time / 3600000000L;
  long m = time / 60000000L - h * 60;
  float s = ((float)time / 1000000L) - m * 60 - h * 3600;

  if (h > 0)
    out << h << "h";
  if (m > 0)
    out << m << "m";
  out << s << "s";
}

void CrabStats::reset() {
  counters.clear();
  sw.clear();
}

void CrabStats::count(const std::string &name) { ++counters[name]; }
void CrabStats::count_max(const std::string &name, unsigned v) {
  counters[name] = std::max(counters[name], v);
}

unsigned CrabStats::uset(const std::string &n, unsigned v) {
  return counters[n] = v;
}
unsigned CrabStats::get(const std::string &n) { return counters[n]; }

void CrabStats::start(const std::string &name) { sw[name].start(); }
void CrabStats::stop(const std::string &name) { sw[name].stop(); }
void CrabStats::resume(const std::string &name) { sw[name].resume(); }

/** Outputs all statistics to std output */
void CrabStats::Print(crab_os &OS) {
  OS << "\n\n************** STATS ***************** \n";
  for (auto &kv : counters)
    OS << kv.first << ": " << kv.second << "\n";
  for (auto &kv : sw)
    OS << kv.first << ": " << kv.second << "\n";
  OS << "************** STATS END ***************** \n";
}

void CrabStats::PrintBrunch(crab_os &OS) {
  OS << "\n\n************** BRUNCH STATS ***************** \n";
  for (auto &kv : counters)
    OS << "BRUNCH_STAT " << kv.first << " " << kv.second << "\n";
  for (auto &kv : sw)
    OS << "BRUNCH_STAT " << kv.first << " " << (kv.second).toSeconds()
       << "sec \n";
  OS << "************** BRUNCH STATS END ***************** \n";
}

ScopedCrabStats::ScopedCrabStats(const std::string &name, bool reset)
    : m_name(name) {
  if (reset) {
    m_name += ".last";
    CrabStats::start(m_name);
  } else {
    CrabStats::resume(m_name);
  }
}

ScopedCrabStats::~ScopedCrabStats() { CrabStats::stop(m_name); }

} // namespace crab
#endif
<commit_msg>Fix typo<commit_after>#include <crab/config.h>
#include <crab/common/stats.hpp>

#ifndef CRAB_STATS
namespace crab {
Stopwatch::Stopwatch() {}
void Stopwatch::start() {}
void Stopwatch::stop() {}
void Stopwatch::resume() {}
long Stopwatch::systemTime() const { return (long)0;}
long Stopwatch::getTimeElapsed() const { return (long)0;}
double Stopwatch::toSeconds() { return (double)0;}
void Stopwatch::Print(crab_os &out) const {}
void CrabStats::reset() {}
void CrabStats::count(const std::string &name) {}
void CrabStats::count_max(const std::string &name, unsigned v) {}
unsigned CrabStats::uset(const std::string &n, unsigned v) { return (unsigned)0;}
unsigned CrabStats::get(const std::string &n) { return (unsigned)0;}
void CrabStats::start(const std::string &name) {}
void CrabStats::stop(const std::string &name) {}
void CrabStats::resume(const std::string &name) {}

/** Outputs all statistics to std output */
void CrabStats::Print(crab_os &OS) {
  OS << "\n\n************** STATS ***************** \n";
  OS << "Crab compiled with support for gathering stats. "
     << "Compile Crab with -DCRAB_ENABLE_STATS=ON\n";
  OS << "************** STATS END ***************** \n";
}

void CrabStats::PrintBrunch(crab_os &OS) {
  OS << "\n\n************** BRUNCH STATS ***************** \n";
  OS << "Crab compiled with support for gathering stats. "
     << "Compile Crab with -DCRAB_ENABLE_STATS=ON\n";
  OS << "************** BRUNCH STATS END ***************** \n";
}

ScopedCrabStats::ScopedCrabStats(const std::string &name, bool reset): m_name("") {}
ScopedCrabStats::~ScopedCrabStats() {}
}
#else
/* Real implementation stars here */
#include <sys/resource.h>
#include <sys/time.h>

namespace crab {

std::map<std::string, unsigned> CrabStats::counters;
std::map<std::string, Stopwatch> CrabStats::sw;

long Stopwatch::systemTime() const {
  struct rusage ru;
  getrusage(RUSAGE_SELF, &ru);
  long r = ru.ru_utime.tv_sec * 1000000L + ru.ru_utime.tv_usec;
  return r;
}

Stopwatch::Stopwatch() { start(); }

void Stopwatch::start() {
  started = systemTime();
  finished = -1;
  timeElapsed = 0;
}

void Stopwatch::stop() {
  if (finished < started) {
    finished = systemTime();
  }
}

void Stopwatch::resume() {
  if (finished >= started) {
    timeElapsed += finished - started;
    started = systemTime();
    finished = -1;
  }
}

long Stopwatch::getTimeElapsed() const {
  if (finished < started)
    return timeElapsed + systemTime() - started;
  else
    return timeElapsed + finished - started;
}

double Stopwatch::toSeconds() {
  double time = ((double)getTimeElapsed() / 1000000);
  return time;
}

void Stopwatch::Print(crab_os &out) const {
  long time = getTimeElapsed();
  long h = time / 3600000000L;
  long m = time / 60000000L - h * 60;
  float s = ((float)time / 1000000L) - m * 60 - h * 3600;

  if (h > 0)
    out << h << "h";
  if (m > 0)
    out << m << "m";
  out << s << "s";
}

void CrabStats::reset() {
  counters.clear();
  sw.clear();
}

void CrabStats::count(const std::string &name) { ++counters[name]; }
void CrabStats::count_max(const std::string &name, unsigned v) {
  counters[name] = std::max(counters[name], v);
}

unsigned CrabStats::uset(const std::string &n, unsigned v) {
  return counters[n] = v;
}
unsigned CrabStats::get(const std::string &n) { return counters[n]; }

void CrabStats::start(const std::string &name) { sw[name].start(); }
void CrabStats::stop(const std::string &name) { sw[name].stop(); }
void CrabStats::resume(const std::string &name) { sw[name].resume(); }

/** Outputs all statistics to std output */
void CrabStats::Print(crab_os &OS) {
  OS << "\n\n************** STATS ***************** \n";
  for (auto &kv : counters)
    OS << kv.first << ": " << kv.second << "\n";
  for (auto &kv : sw)
    OS << kv.first << ": " << kv.second << "\n";
  OS << "************** STATS END ***************** \n";
}

void CrabStats::PrintBrunch(crab_os &OS) {
  OS << "\n\n************** BRUNCH STATS ***************** \n";
  for (auto &kv : counters)
    OS << "BRUNCH_STAT " << kv.first << " " << kv.second << "\n";
  for (auto &kv : sw)
    OS << "BRUNCH_STAT " << kv.first << " " << (kv.second).toSeconds()
       << "sec \n";
  OS << "************** BRUNCH STATS END ***************** \n";
}

ScopedCrabStats::ScopedCrabStats(const std::string &name, bool reset)
    : m_name(name) {
  if (reset) {
    m_name += ".last";
    CrabStats::start(m_name);
  } else {
    CrabStats::resume(m_name);
  }
}

ScopedCrabStats::~ScopedCrabStats() { CrabStats::stop(m_name); }

} // namespace crab
#endif
<|endoftext|>


<commit_before>#include <wtypes.h>
#include "nbind/nbind.h"
#include "screen-size.h"

using namespace std;

struct ScreenInfo {
	static ScreenSize mainDisplaySize() {
		 RECT desktop;
		// Get a handle to the desktop window
		const HWND hDesktop = GetDesktopWindow();
		// Get the size of screen to the variable desktop
		GetWindowRect(hDesktop, &desktop);
		// The top left corner will have coordinates (0,0)
		// and the bottom right corner will have coordinates
		// (horizontal, vertical)
		return ScreenSize(
			(size_t) desktop.right,
			(size_t) desktop.bottom
		);
	}
};

NBIND_CLASS(ScreenInfo) {
	construct<>();
	method(mainDisplaySize);
}
<commit_msg>inverted<commit_after>#include "nbind/nbind.h"
#include <wtypes.h>
#include "screen-size.h"

using namespace std;

struct ScreenInfo {
	static ScreenSize mainDisplaySize() {
		 RECT desktop;
		// Get a handle to the desktop window
		const HWND hDesktop = GetDesktopWindow();
		// Get the size of screen to the variable desktop
		GetWindowRect(hDesktop, &desktop);
		// The top left corner will have coordinates (0,0)
		// and the bottom right corner will have coordinates
		// (horizontal, vertical)
		return ScreenSize(
			(size_t) desktop.right,
			(size_t) desktop.bottom
		);
	}
};

NBIND_CLASS(ScreenInfo) {
	construct<>();
	method(mainDisplaySize);
}
<|endoftext|>


<commit_before>
#include "microflo.h"
#include "components.h"

#include "components-gen-top.hpp"

// Generic
class Forward : public Component {
public:
    virtual void process(Packet in, int port) {
        if (in.isData()) {
            send(in, port);
        }
    }
};

// FIXME: using any of these should result in error
typedef Forward DummyComponent;
class Invalid : public DummyComponent {};
class Max : public DummyComponent {};

// I/O

// IDEA: wrap all actual I/O behind an IoMaster class/interface, which can handle multiple access etc.
// This should make it possible for all components to share implementation, and hide platform specifics in master.
// Should also be possible to use as an interception point for testing

#ifdef ARDUINO
class SerialIn : public Component {
public:
    virtual void process(Packet in, int port) {

        if (in.isSetup()) {
            // FIXME: do based on input data instead of hardcode
            // FIXME: avoid doing setup multiple times
            Serial.begin(9600);
        } else if (in.isTick()) {
            if (Serial.available() > 0) {
                char c = Serial.read();
                send(Packet(c));
            }
        }
    }
};

class SerialOut : public Component {
public:
    virtual void process(Packet in, int port) {

        if (in.isSetup()) {
            // FIXME: do based on input data instead of hardcode
            // FIXME: avoid doing multiple times
            Serial.begin(9600);
        } else if (in.isByte()) {
            Serial.write(in.asByte());
        } else if (in.isAscii()) {
            Serial.write(in.asAscii());
        }
    }
};

class DigitalWrite : public Component {
public:
    virtual void process(Packet in, int port) {
        // Note: have to match components.json
        const int inPort = 0;
        const int pinConfigPort = 1;
        const int outPort = 0;
        if (in.isSetup()) {
            outPin = 13; // default
            pinMode(outPin, OUTPUT);
        } else if (port == inPort && in.isBool()) {
            digitalWrite(outPin, in.asBool());
            send(in, outPort);
        } else if (port == pinConfigPort && in.isNumber()) {
            outPin = in.asInteger();
            pinMode(outPin, OUTPUT);
        }
    }
private:
    int outPin;
};

class DigitalRead : public Component {
public:
    virtual void process(Packet in, int port) {
        // Note: have to match components.json
        const int triggerPort = 0;
        const int pinConfigPort = 1;
        const int pullupConfigPort = 2;
        if (in.isSetup()) {
            setPinAndPullup(12, true); // defaults
        } else if (port == triggerPort && in.isData()) {
            bool isHigh = digitalRead(pin) == HIGH;
            send(Packet(isHigh));
        } else if (port == pinConfigPort && in.isNumber()) {
            setPinAndPullup(in.asInteger(), pullup);
        } else if (port == pullupConfigPort && in.isBool()) {
            setPinAndPullup(pin, in.asBool());
        }
    }
private:
    void setPinAndPullup(int newPin, bool newPullup) {
        pin = newPin;
        pullup = newPullup;
        pinMode(pin, INPUT);
        digitalWrite(pin, pullup ? HIGH : LOW);
    }
    int pin;
    bool pullup;
};

class Timer : public Component {
public:
    virtual void process(Packet in, int port) {
        const int intervalConfigPort = 0;
        if (in.isSetup()) {
            // defaults
            previousMillis = 0;
            interval = 1000;
        } else if (in.isTick()) {
            unsigned long currentMillis = millis();
            if (currentMillis - previousMillis > interval) {
                previousMillis = currentMillis;
                send(Packet());
            }
        } else if (port == intervalConfigPort && in.isData()) {
            previousMillis = millis();
            interval = in.asInteger();
        }
    }
private:
    unsigned long previousMillis;
    unsigned long interval;
};

#include <OneWire.h>
#include <DallasTemperature.h>

class ReadDallasTemperature : public Component {
public:
    ReadDallasTemperature()
        : pin(3) // default
        , oneWire(pin)
        , sensors(&oneWire)
    {}

    virtual void process(Packet in, int port) {
        const int triggerPort = 0;
        const int pinConfigPort = 1;
        const int addressConfigPort = 2;

        if (in.isSetup()) {
            // defaults
            addressIndex = 0;
            updateConfig(pin, 10);
        } else if (port == pinConfigPort && in.isNumber()) {
            updateConfig(in.asInteger(), sensors.getResolution());
        } else if (port == addressConfigPort) {
            if (in.isStartBracket()) {
                addressIndex = 0;
            } else if (in.isData()) {
                if (addressIndex < sizeof(address)) {
                    address[addressIndex++] = in.asByte();
                }
            } else if (in.isEndBracket()) {
                // ASSERT(addressIndex == sizeof(DeviceAddress));
            }

        } else if (port == triggerPort && in.isData()) {
            if (addressIndex == sizeof(DeviceAddress)) {
                sensors.requestTemperatures();
                const float tempC = sensors.getTempC(address);
                if (tempC != -127) {
                    send(Packet(tempC));
                }
            }
        }
    }
private:
    void updateConfig(int newPin, int newResolution) {
        if (newPin != pin)  {
            oneWire = OneWire(pin);
            sensors = DallasTemperature(&oneWire);
        }
        sensors.setResolution(newResolution);
    }

    int pin;
    int addressIndex;
    DeviceAddress address;
    OneWire oneWire;
    DallasTemperature sensors;
};
#else
// TODO: implement host I/O components which can be used for simulation/testing
class SerialIn : public DummyComponent {};
class SerialOut : public DummyComponent {};
class DigitalWrite : public DummyComponent {};
class DigitalRead : public DummyComponent {};
class Timer : public DummyComponent {};
class ReadDallasTemperature : public DummyComponent {};
#endif // ARDUINO

class ToggleBoolean : public Component {
public:
    virtual void process(Packet in, int port) {

        if (in.isSetup()) {
            // FIXME: do based on input data instead of hardcode
            currentState = false;
        } else if (in.isData()) {
            currentState = !currentState;
            send(Packet(currentState));
        }
    }
private:
    bool currentState;
};

class InvertBoolean : public Component {
public:
    virtual void process(Packet in, int port) {
        if (in.isData()) {
            Packet p = Packet((bool)!in.asBool());
            send(p);
        }
    }
};

class ArduinoUno : public Component {
public:
    virtual void process(Packet in, int port) {
        const int digitalPins = 14;
        const int analogPins = 6;
        if (in.isSetup()) {
            for (int outPort=0; outPort < digitalPins+analogPins; outPort++) {
                // Emit 0 for A0, 1 for A1, and so on
                const long val = (outPort < digitalPins) ? outPort : outPort - digitalPins;
                send(Packet(val), outPort);
            }
        }
    }
};

class HysteresisLatch : public Component
{
public:
    virtual void process(Packet in, int port) {
        const int inputPort = 0;
        const int lowThresholdPort = 1;
        const int highThresholdPort = 2;

        if (in.isSetup()) {
            // defaults
            mHighThreshold = 30;
            mLowThreshold = 24;
            mCurrentState = true; // TODO: make tristate or configurable?
        } else if (port == lowThresholdPort && in.isNumber()) {
            mLowThreshold = in.asFloat();
        } else if (port == highThresholdPort && in.isNumber()) {
            mHighThreshold = in.asFloat();
        } else if (port == inputPort && in.isNumber()) {
            updateValue(in.asFloat());
        }
    }

private:
    void updateValue(float input) {
        if (mCurrentState) {
            if (input <= mLowThreshold) {
                mCurrentState = false;
            }
        } else {
            if (input >= mHighThreshold) {
                mCurrentState = true;
            }
        }
        send(Packet(mCurrentState));
    }

private:
    float mHighThreshold;
    float mLowThreshold;
    bool mCurrentState;
};

#ifdef HOST_BUILD
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>

#include <string>
#include <sstream>
#endif

class ToString : public Component
{
public:
    virtual void process(Packet in, int port) {

    // XXX: probably too generic a name for this component?
        if (in.isInteger()) {
#ifdef ARDUINO
            String s(in.asInteger(), DEC);
            send(Packet(MsgBracketStart));
            for (int i=0; i<s.length(); i++) {
                send(Packet(s.charAt(i)));
            }
            send(Packet(MsgBracketEnd));
#endif
#ifdef HOST_BUILD
            std::stringstream ss;
            ss << in.asInteger();
            std::string s = ss.str();
            send(Packet(MsgBracketStart));
            for (int i=0; i<s.size(); i++) {
                send(Packet(s[i]));
            }
            send(Packet(MsgBracketEnd));
#endif
        } else if (in.isBool()) {
            const char *s = in.asBool() ? "true" : "false";
            const int l = in.asBool() ? 4 : 5;
            send(Packet(MsgBracketStart));
            for (int i=0; i<l; i++) {
                send(Packet(s[i]));
            }
            send(Packet(MsgBracketEnd));
        } else if (in.isFloat()) {

            char s[20] = {0,};
            const int precision = 2;
            const int width = 2;
#ifdef ARDUINO
            dtostrf(in.asFloat(), width, precision, s);
#endif
#ifdef HOST_BUILD
            snprintf(s, sizeof(s), "%.2f", in.asFloat());
#endif
            send(Packet(MsgBracketStart));
            for (int i=0; i<strlen(s); i++) {
                send(Packet(s[i]));
            }
            send(Packet(MsgBracketEnd));
        }
    }
};

// IDEA: ability to express components as finite state machines using a DSL and/or GUI
class BreakBeforeMake : public Component
{
public:
    BreakBeforeMake() : state(Init) {}
    virtual void process(Packet in, int port) {
        const int inPort = 0;
        const int out1MonitorPort = 1;
        const int out2MonitorPort = 2;

        const int out1Port = 0;
        const int out2Port = 1;

        // XXX: inputs are ignored while in transition
        switch (state) {
        case Init:
            state = SettledOff;
            break;
        case WaitFor2Off:
            if (port == out2MonitorPort && !in.asBool()) {
                send(Packet((bool)true), out1Port);
                state = WaitFor1On;
            }
            break;
        case WaitFor1On:
            if (port == out1MonitorPort && in.asBool()) {
                state = SettledOff;
            }
            break;
        case SettledOff:
            if (port == inPort && in.asBool()) {
                send(Packet((bool)false), out1Port);
                state = WaitFor1Off;
            }
            break;
        case WaitFor1Off:
            if (port == out1MonitorPort && !in.asBool()) {
                send(Packet((bool)true), out2Port);
                state = WaitFor2On;
            }
            break;
        case WaitFor2On:
            if (port == out2MonitorPort && in.asBool()) {
                state = SettledOn;
            }
            break;
        case SettledOn:
            if (port == inPort && !in.asBool()) {
                send(Packet((bool)false), out2Port);
                state = WaitFor2Off;
            }
        default:
            break;
        }
    }
private:
    enum State {
        Init,
        WaitFor1On,
        WaitFor1Off,
        WaitFor2On,
        WaitFor2Off,
        SettledOn,
        SettledOff
    };

private:
    enum State state;
};

class Delimit : public Component {
public:
    Delimit(): startBracketRecieved(false) {}
    virtual void process(Packet in, int port) {
        if (in.isSetup()) {
            delimiter = '\r';
        }
        if (startBracketRecieved) {
            if (in.isEndBracket()) {
                startBracketRecieved = false;
                send(Packet(delimiter));
            } else {
                send(in);
            }
        } else {
            if (in.isStartBracket()) {
                startBracketRecieved = true;
            } else if (in.isData()) {
                send(in);
                send(Packet(delimiter));
            }
        }
    }
private:
    bool startBracketRecieved;
    char delimiter;
};

#ifdef HOST_BUILD
class ReadStdIn : public Component {
public:
    virtual void process(Packet in, int port) {
        if (in.isTick()) {
            send(Packet((char)getchar()));
        }
    }
};

class PrintStdOut : public Component {
public:
    virtual void process(Packet in, int port) {
        if (in.isByte()) {
            putchar(in.asByte());
        } else if (in.isAscii()) {
            putchar(in.asAscii());
        }
    }
};

class RandomChar : public Component {
public:
    virtual void process(Packet in, int port) {
        char c = 255 * (rand()/(RAND_MAX+1.0));
        send(Packet(c));
    }
};
#else
class ReadStdIn : public DummyComponent {};
class PrintStdOut : public DummyComponent {};
class RandomChar : public DummyComponent {};
#endif // HOST_BUILD

#include "components-gen-bottom.hpp"
<commit_msg>Use port definition enums in DigitalWrite<commit_after>
#include "microflo.h"
#include "components.h"

#include "components-gen-top.hpp"

// Generic
class Forward : public Component {
public:
    virtual void process(Packet in, int port) {
        if (in.isData()) {
            send(in, port);
        }
    }
};

// FIXME: using any of these should result in error
typedef Forward DummyComponent;
class Invalid : public DummyComponent {};
class Max : public DummyComponent {};

// I/O

// IDEA: wrap all actual I/O behind an IoMaster class/interface, which can handle multiple access etc.
// This should make it possible for all components to share implementation, and hide platform specifics in master.
// Should also be possible to use as an interception point for testing

#ifdef ARDUINO
class SerialIn : public Component {
public:
    virtual void process(Packet in, int port) {

        if (in.isSetup()) {
            // FIXME: do based on input data instead of hardcode
            // FIXME: avoid doing setup multiple times
            Serial.begin(9600);
        } else if (in.isTick()) {
            if (Serial.available() > 0) {
                char c = Serial.read();
                send(Packet(c));
            }
        }
    }
};

class SerialOut : public Component {
public:
    virtual void process(Packet in, int port) {

        if (in.isSetup()) {
            // FIXME: do based on input data instead of hardcode
            // FIXME: avoid doing multiple times
            Serial.begin(9600);
        } else if (in.isByte()) {
            Serial.write(in.asByte());
        } else if (in.isAscii()) {
            Serial.write(in.asAscii());
        }
    }
};

class DigitalWrite : public Component {
public:
    virtual void process(Packet in, int port) {
        using namespace DigitalWritePorts;
        if (in.isSetup()) {
            outPin = 13; // default
            pinMode(outPin, OUTPUT);
        } else if (port == InPorts::in && in.isBool()) {
            digitalWrite(outPin, in.asBool());
            send(in, OutPorts::out);
        } else if (port == InPorts::pin && in.isNumber()) {
            outPin = in.asInteger();
            pinMode(outPin, OUTPUT);
        }
    }
private:
    int outPin;
};

class DigitalRead : public Component {
public:
    virtual void process(Packet in, int port) {
        // Note: have to match components.json
        const int triggerPort = 0;
        const int pinConfigPort = 1;
        const int pullupConfigPort = 2;
        if (in.isSetup()) {
            setPinAndPullup(12, true); // defaults
        } else if (port == triggerPort && in.isData()) {
            bool isHigh = digitalRead(pin) == HIGH;
            send(Packet(isHigh));
        } else if (port == pinConfigPort && in.isNumber()) {
            setPinAndPullup(in.asInteger(), pullup);
        } else if (port == pullupConfigPort && in.isBool()) {
            setPinAndPullup(pin, in.asBool());
        }
    }
private:
    void setPinAndPullup(int newPin, bool newPullup) {
        pin = newPin;
        pullup = newPullup;
        pinMode(pin, INPUT);
        digitalWrite(pin, pullup ? HIGH : LOW);
    }
    int pin;
    bool pullup;
};

class Timer : public Component {
public:
    virtual void process(Packet in, int port) {
        const int intervalConfigPort = 0;
        if (in.isSetup()) {
            // defaults
            previousMillis = 0;
            interval = 1000;
        } else if (in.isTick()) {
            unsigned long currentMillis = millis();
            if (currentMillis - previousMillis > interval) {
                previousMillis = currentMillis;
                send(Packet());
            }
        } else if (port == intervalConfigPort && in.isData()) {
            previousMillis = millis();
            interval = in.asInteger();
        }
    }
private:
    unsigned long previousMillis;
    unsigned long interval;
};

#include <OneWire.h>
#include <DallasTemperature.h>

class ReadDallasTemperature : public Component {
public:
    ReadDallasTemperature()
        : pin(3) // default
        , oneWire(pin)
        , sensors(&oneWire)
    {}

    virtual void process(Packet in, int port) {
        const int triggerPort = 0;
        const int pinConfigPort = 1;
        const int addressConfigPort = 2;

        if (in.isSetup()) {
            // defaults
            addressIndex = 0;
            updateConfig(pin, 10);
        } else if (port == pinConfigPort && in.isNumber()) {
            updateConfig(in.asInteger(), sensors.getResolution());
        } else if (port == addressConfigPort) {
            if (in.isStartBracket()) {
                addressIndex = 0;
            } else if (in.isData()) {
                if (addressIndex < sizeof(address)) {
                    address[addressIndex++] = in.asByte();
                }
            } else if (in.isEndBracket()) {
                // ASSERT(addressIndex == sizeof(DeviceAddress));
            }

        } else if (port == triggerPort && in.isData()) {
            if (addressIndex == sizeof(DeviceAddress)) {
                sensors.requestTemperatures();
                const float tempC = sensors.getTempC(address);
                if (tempC != -127) {
                    send(Packet(tempC));
                }
            }
        }
    }
private:
    void updateConfig(int newPin, int newResolution) {
        if (newPin != pin)  {
            oneWire = OneWire(pin);
            sensors = DallasTemperature(&oneWire);
        }
        sensors.setResolution(newResolution);
    }

    int pin;
    int addressIndex;
    DeviceAddress address;
    OneWire oneWire;
    DallasTemperature sensors;
};
#else
// TODO: implement host I/O components which can be used for simulation/testing
class SerialIn : public DummyComponent {};
class SerialOut : public DummyComponent {};
class DigitalWrite : public DummyComponent {};
class DigitalRead : public DummyComponent {};
class Timer : public DummyComponent {};
class ReadDallasTemperature : public DummyComponent {};
#endif // ARDUINO

class ToggleBoolean : public Component {
public:
    virtual void process(Packet in, int port) {

        if (in.isSetup()) {
            // FIXME: do based on input data instead of hardcode
            currentState = false;
        } else if (in.isData()) {
            currentState = !currentState;
            send(Packet(currentState));
        }
    }
private:
    bool currentState;
};

class InvertBoolean : public Component {
public:
    virtual void process(Packet in, int port) {
        if (in.isData()) {
            Packet p = Packet((bool)!in.asBool());
            send(p);
        }
    }
};

class ArduinoUno : public Component {
public:
    virtual void process(Packet in, int port) {
        const int digitalPins = 14;
        const int analogPins = 6;
        if (in.isSetup()) {
            for (int outPort=0; outPort < digitalPins+analogPins; outPort++) {
                // Emit 0 for A0, 1 for A1, and so on
                const long val = (outPort < digitalPins) ? outPort : outPort - digitalPins;
                send(Packet(val), outPort);
            }
        }
    }
};

class HysteresisLatch : public Component
{
public:
    virtual void process(Packet in, int port) {
        const int inputPort = 0;
        const int lowThresholdPort = 1;
        const int highThresholdPort = 2;

        if (in.isSetup()) {
            // defaults
            mHighThreshold = 30;
            mLowThreshold = 24;
            mCurrentState = true; // TODO: make tristate or configurable?
        } else if (port == lowThresholdPort && in.isNumber()) {
            mLowThreshold = in.asFloat();
        } else if (port == highThresholdPort && in.isNumber()) {
            mHighThreshold = in.asFloat();
        } else if (port == inputPort && in.isNumber()) {
            updateValue(in.asFloat());
        }
    }

private:
    void updateValue(float input) {
        if (mCurrentState) {
            if (input <= mLowThreshold) {
                mCurrentState = false;
            }
        } else {
            if (input >= mHighThreshold) {
                mCurrentState = true;
            }
        }
        send(Packet(mCurrentState));
    }

private:
    float mHighThreshold;
    float mLowThreshold;
    bool mCurrentState;
};

#ifdef HOST_BUILD
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>

#include <string>
#include <sstream>
#endif

class ToString : public Component
{
public:
    virtual void process(Packet in, int port) {

    // XXX: probably too generic a name for this component?
        if (in.isInteger()) {
#ifdef ARDUINO
            String s(in.asInteger(), DEC);
            send(Packet(MsgBracketStart));
            for (int i=0; i<s.length(); i++) {
                send(Packet(s.charAt(i)));
            }
            send(Packet(MsgBracketEnd));
#endif
#ifdef HOST_BUILD
            std::stringstream ss;
            ss << in.asInteger();
            std::string s = ss.str();
            send(Packet(MsgBracketStart));
            for (int i=0; i<s.size(); i++) {
                send(Packet(s[i]));
            }
            send(Packet(MsgBracketEnd));
#endif
        } else if (in.isBool()) {
            const char *s = in.asBool() ? "true" : "false";
            const int l = in.asBool() ? 4 : 5;
            send(Packet(MsgBracketStart));
            for (int i=0; i<l; i++) {
                send(Packet(s[i]));
            }
            send(Packet(MsgBracketEnd));
        } else if (in.isFloat()) {

            char s[20] = {0,};
            const int precision = 2;
            const int width = 2;
#ifdef ARDUINO
            dtostrf(in.asFloat(), width, precision, s);
#endif
#ifdef HOST_BUILD
            snprintf(s, sizeof(s), "%.2f", in.asFloat());
#endif
            send(Packet(MsgBracketStart));
            for (int i=0; i<strlen(s); i++) {
                send(Packet(s[i]));
            }
            send(Packet(MsgBracketEnd));
        }
    }
};

// IDEA: ability to express components as finite state machines using a DSL and/or GUI
class BreakBeforeMake : public Component
{
public:
    BreakBeforeMake() : state(Init) {}
    virtual void process(Packet in, int port) {
        const int inPort = 0;
        const int out1MonitorPort = 1;
        const int out2MonitorPort = 2;

        const int out1Port = 0;
        const int out2Port = 1;

        // XXX: inputs are ignored while in transition
        switch (state) {
        case Init:
            state = SettledOff;
            break;
        case WaitFor2Off:
            if (port == out2MonitorPort && !in.asBool()) {
                send(Packet((bool)true), out1Port);
                state = WaitFor1On;
            }
            break;
        case WaitFor1On:
            if (port == out1MonitorPort && in.asBool()) {
                state = SettledOff;
            }
            break;
        case SettledOff:
            if (port == inPort && in.asBool()) {
                send(Packet((bool)false), out1Port);
                state = WaitFor1Off;
            }
            break;
        case WaitFor1Off:
            if (port == out1MonitorPort && !in.asBool()) {
                send(Packet((bool)true), out2Port);
                state = WaitFor2On;
            }
            break;
        case WaitFor2On:
            if (port == out2MonitorPort && in.asBool()) {
                state = SettledOn;
            }
            break;
        case SettledOn:
            if (port == inPort && !in.asBool()) {
                send(Packet((bool)false), out2Port);
                state = WaitFor2Off;
            }
        default:
            break;
        }
    }
private:
    enum State {
        Init,
        WaitFor1On,
        WaitFor1Off,
        WaitFor2On,
        WaitFor2Off,
        SettledOn,
        SettledOff
    };

private:
    enum State state;
};

class Delimit : public Component {
public:
    Delimit(): startBracketRecieved(false) {}
    virtual void process(Packet in, int port) {
        if (in.isSetup()) {
            delimiter = '\r';
        }
        if (startBracketRecieved) {
            if (in.isEndBracket()) {
                startBracketRecieved = false;
                send(Packet(delimiter));
            } else {
                send(in);
            }
        } else {
            if (in.isStartBracket()) {
                startBracketRecieved = true;
            } else if (in.isData()) {
                send(in);
                send(Packet(delimiter));
            }
        }
    }
private:
    bool startBracketRecieved;
    char delimiter;
};

#ifdef HOST_BUILD
class ReadStdIn : public Component {
public:
    virtual void process(Packet in, int port) {
        if (in.isTick()) {
            send(Packet((char)getchar()));
        }
    }
};

class PrintStdOut : public Component {
public:
    virtual void process(Packet in, int port) {
        if (in.isByte()) {
            putchar(in.asByte());
        } else if (in.isAscii()) {
            putchar(in.asAscii());
        }
    }
};

class RandomChar : public Component {
public:
    virtual void process(Packet in, int port) {
        char c = 255 * (rand()/(RAND_MAX+1.0));
        send(Packet(c));
    }
};
#else
class ReadStdIn : public DummyComponent {};
class PrintStdOut : public DummyComponent {};
class RandomChar : public DummyComponent {};
#endif // HOST_BUILD

#include "components-gen-bottom.hpp"
<|endoftext|>


<commit_before>/*
 * AscEmu Framework based on ArcEmu MMORPG Server
 * Copyright (C) 2014-2016 AscEmu Team <http://www.ascemu.org>
 * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
 * Copyright (C) 2005-2007 Ascent Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "StdAfx.h"

bool isNeutral(Object* a, Object* b)
{
    if ((a->m_faction->HostileMask & b->m_faction->Mask) == 0 && (a->m_faction->FriendlyMask & b->m_faction->Mask) == 0)
        return true;

    return false;
}

bool isHostile(Object* objA, Object* objB)
{
    if ((objA == NULL) || (objB == NULL))
        return false;

    bool hostile = false;

    if (!objA->IsInWorld() || !objB->IsInWorld())
        return false;

    if (objA == objB)
        return false;   // can't attack self.. this causes problems with buffs if we don't have it :p

    if (objA->IsCorpse() || objB->IsCorpse())
        return false;

    if ((objA->m_phase & objB->m_phase) == 0)     //What you can't see, can't be hostile!
        return false;

    if (objA->IsPlayer() && objA->HasFlag(PLAYER_FLAGS, PLAYER_FLAG_CONT_PVP) && objB->IsCreature() && static_cast< Unit* >(objB)->GetAIInterface()->m_isNeutralGuard)
        return true;
    if (objB->IsPlayer() && objB->HasFlag(PLAYER_FLAGS, PLAYER_FLAG_CONT_PVP) && objA->IsCreature() && static_cast< Unit* >(objA)->GetAIInterface()->m_isNeutralGuard)
        return true;

    if (objB->IsUnit() && objB->HasFlag(UNIT_FIELD_FLAGS, 2 | 128 | 256 | 65536))
        return false;

    if (!objB->m_faction || !objA->m_faction)
        return false;

    uint32 faction = objB->m_faction->Mask;
    uint32 host = objA->m_faction->HostileMask;

    if ((faction & host) != 0)
        hostile = true;

    faction = objA->m_faction->Mask;
    host = objB->m_faction->HostileMask;

    if ((faction & host) != 0)
        hostile = true;

    // check friend/enemy list
    for (uint8 i = 0; i < 4; i++)
    {
        if (objA->m_faction->EnemyFactions[i] == objB->m_faction->Faction)
        {
            hostile = true;
            break;
        }

        if (objA->m_faction->FriendlyFactions[i] == objB->m_faction->Faction)
        {
            hostile = false;
            break;
        }
    }

    // Reputation System Checks
    if (objA->IsPlayer() && !objB->IsPlayer())
        if (objB->m_factionDBC->RepListId >= 0)
            hostile = static_cast< Player* >(objA)->IsHostileBasedOnReputation(objB->m_factionDBC);

    if (objB->IsPlayer() && !objA->IsPlayer())
        if (objA->m_factionDBC->RepListId >= 0)
            hostile = static_cast< Player* >(objB)->IsHostileBasedOnReputation(objA->m_factionDBC);

    // PvP Flag System Checks
    // We check this after the normal isHostile test, that way if we're
    // on the opposite team we'll already know :p
    if ((objA->GetPlayerOwner() != NULL) && (objB->GetPlayerOwner() != NULL))
    {
        Player* a = static_cast< Player* >(objA->GetPlayerOwner());
        Player* b = static_cast< Player* >(objB->GetPlayerOwner());

        auto atA = a->GetArea();
        auto atB = b->GetArea();

        if (((atA && atA->flags & 0x800) != 0) || ((atB && atB->flags & 0x800) != 0))
            return false;

        if (hostile)
        {
            if (!b->IsSanctuaryFlagged() && (b->IsPvPFlagged() || b->IsFFAPvPFlagged()))
                return true;
            else
                return false;
        }

    }

    return hostile;
}

/// Where we check if we object A can attack object B. This is used in many feature's
/// Including the spell class and the player class.
bool isAttackable(Object* objA, Object* objB, bool CheckStealth)
{
    if ((objA == NULL) || (objB == NULL))
        return false;

    if (!objA->IsInWorld() || !objB->IsInWorld())
        return false;

    if (objA == objB)
        return false;   // can't attack self.. this causes problems with buffs if we don't have it :p

    if ((objA->m_phase & objB->m_phase) == 0)     //What you can't see, you can't attack either...
        return false;

    if (objA->IsCorpse() || objB->IsCorpse())
        return false;

    // Checks for untouchable, unattackable
    if (objA->IsUnit() && objA->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNTED_TAXI | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_DEAD))
        return false;

    if (objB->IsUnit())
    {
        if (objB->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNTED_TAXI | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_DEAD))
            return false;

        /// added by Zack :
        /// we cannot attack shealthed units. Maybe checked in other places too ?
        /// !! warning, this presumes that objA is attacking ObjB
        /// Capt: Added the possibility to disregard this (regarding the spell class)
        if (static_cast< Unit* >(objB)->IsStealth() && CheckStealth)
            return false;
    }

    if ((objA->GetPlayerOwner() != NULL) && (objB->GetPlayerOwner() != NULL))
    {
        Player* a = static_cast< Player* >(objA->GetPlayerOwner());
        Player* b = static_cast< Player* >(objB->GetPlayerOwner());

        if ((a->DuelingWith == b) && (a->GetDuelState() == DUEL_STATE_STARTED))
            return true;

        if (b->IsSanctuaryFlagged())
            return false;

        //players in same group should not attack each other. Required for arenas with mixed groups
        if ((a->GetGroup() != NULL) && (a->GetGroup() == b->GetGroup()))
            return false;

        if (a->IsFFAPvPFlagged() && b->IsFFAPvPFlagged())
            return true;
    }

    if (objA->m_faction == nullptr)     // no faction, no kill (added because spell_caster gos should summon a trap instead of casting the spell directly.)
        return false;

    if (objA->m_faction == objB->m_faction)    // same faction can't kill each other unless in ffa pvp/duel
        return false;

    // Neutral Creature Check
    if (objA->IsPlayer() || objA->IsPet())
    {

        if ((objB->m_factionDBC->RepListId == -1) && (objB->m_faction->HostileMask == 0) && (objB->m_faction->FriendlyMask == 0))
            return true;
    }
    else if (objB->IsPlayer() || objB->IsPet())
    {
        if ((objA->m_factionDBC->RepListId == -1) && (objA->m_faction->HostileMask == 0) && (objA->m_faction->FriendlyMask == 0))
            return true;
    }

    bool attackable = isHostile(objA, objB);   // B is attackable if its hostile for A

    return attackable;
}

bool isCombatSupport(Object* objA, Object* objB)// B combat supports A?
{
    if (!objA || !objB)
        return false;

    if (objA->IsCorpse())
        return false;

    if (objB->IsCorpse())
        return false;

    if (!objA->IsCreature() || !objB->IsCreature()) return false;    // cebernic: lowchance crashfix.
    // also if it's not a unit, it shouldn't support combat anyways.

    if (objA->IsPet() || objB->IsPet())   // fixes an issue where horde pets would chain aggro horde guards and vice versa for alliance.
        return false;

    if (!(objA->m_phase & objB->m_phase))   //What you can't see, you can't support either...
        return false;

    bool combatSupport = false;

    uint32 fSupport = objB->m_faction->FriendlyMask;
    uint32 myFaction = objA->m_faction->Mask;

    if (myFaction & fSupport)
    {
        combatSupport = true;
    }
    // check friend/enemy list
    for (uint8 i = 0; i < 4; i++)
    {
        if (objB->m_faction->EnemyFactions[i] == objA->m_faction->Faction)
        {
            combatSupport = false;
            break;
        }
        if (objB->m_faction->FriendlyFactions[i] == objA->m_faction->Faction)
        {
            combatSupport = true;
            break;
        }
    }

    return combatSupport;
}

bool isAlliance(Object* objA)// A is alliance?
{
    DBC::Structures::FactionTemplateEntry const* m_sw_faction = sFactionTemplateStore.LookupEntry(11);
    DBC::Structures::FactionEntry const* m_sw_factionDBC = sFactionStore.LookupEntry(72);
    if (!objA)          // || objA->m_factionDBC == NULL || objA->m_faction == NULL
        return true;

    if (m_sw_faction == objA->m_faction || m_sw_factionDBC == objA->m_factionDBC)
        return true;

    //bool hostile = false;
    uint32 faction = m_sw_faction->Faction;
    uint32 host = objA->m_faction->HostileMask;

    if (faction & host)
        return false;

    // check friend/enemy list
    for (uint8 i = 0; i < 4; i++)
    {
        if (objA->m_faction->EnemyFactions[i] == faction)
            return false;
    }

    faction = objA->m_faction->Faction;
    host = m_sw_faction->HostileMask;

    if (faction & host)
        return false;

    // check friend/enemy list
    for (uint8 i = 0; i < 4; i++)
    {
        if (objA->m_faction->EnemyFactions[i] == faction)
            return false;
    }

    return true;
}
<commit_msg>Added nullptr check for objB->m_faction since it is possible that it is a nullptr. Close #280<commit_after>/*
 * AscEmu Framework based on ArcEmu MMORPG Server
 * Copyright (C) 2014-2016 AscEmu Team <http://www.ascemu.org>
 * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
 * Copyright (C) 2005-2007 Ascent Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "StdAfx.h"

bool isNeutral(Object* a, Object* b)
{
    if ((a->m_faction->HostileMask & b->m_faction->Mask) == 0 && (a->m_faction->FriendlyMask & b->m_faction->Mask) == 0)
        return true;

    return false;
}

bool isHostile(Object* objA, Object* objB)
{
    if ((objA == NULL) || (objB == NULL))
        return false;

    bool hostile = false;

    if (!objA->IsInWorld() || !objB->IsInWorld())
        return false;

    if (objA == objB)
        return false;   // can't attack self.. this causes problems with buffs if we don't have it :p

    if (objA->IsCorpse() || objB->IsCorpse())
        return false;

    if ((objA->m_phase & objB->m_phase) == 0)     //What you can't see, can't be hostile!
        return false;

    if (objA->IsPlayer() && objA->HasFlag(PLAYER_FLAGS, PLAYER_FLAG_CONT_PVP) && objB->IsCreature() && static_cast< Unit* >(objB)->GetAIInterface()->m_isNeutralGuard)
        return true;
    if (objB->IsPlayer() && objB->HasFlag(PLAYER_FLAGS, PLAYER_FLAG_CONT_PVP) && objA->IsCreature() && static_cast< Unit* >(objA)->GetAIInterface()->m_isNeutralGuard)
        return true;

    if (objB->IsUnit() && objB->HasFlag(UNIT_FIELD_FLAGS, 2 | 128 | 256 | 65536))
        return false;

    if (!objB->m_faction || !objA->m_faction)
        return false;

    uint32 faction = objB->m_faction->Mask;
    uint32 host = objA->m_faction->HostileMask;

    if ((faction & host) != 0)
        hostile = true;

    faction = objA->m_faction->Mask;
    host = objB->m_faction->HostileMask;

    if ((faction & host) != 0)
        hostile = true;

    // check friend/enemy list
    for (uint8 i = 0; i < 4; i++)
    {
        if (objA->m_faction->EnemyFactions[i] == objB->m_faction->Faction)
        {
            hostile = true;
            break;
        }

        if (objA->m_faction->FriendlyFactions[i] == objB->m_faction->Faction)
        {
            hostile = false;
            break;
        }
    }

    // Reputation System Checks
    if (objA->IsPlayer() && !objB->IsPlayer())
        if (objB->m_factionDBC->RepListId >= 0)
            hostile = static_cast< Player* >(objA)->IsHostileBasedOnReputation(objB->m_factionDBC);

    if (objB->IsPlayer() && !objA->IsPlayer())
        if (objA->m_factionDBC->RepListId >= 0)
            hostile = static_cast< Player* >(objB)->IsHostileBasedOnReputation(objA->m_factionDBC);

    // PvP Flag System Checks
    // We check this after the normal isHostile test, that way if we're
    // on the opposite team we'll already know :p
    if ((objA->GetPlayerOwner() != NULL) && (objB->GetPlayerOwner() != NULL))
    {
        Player* a = static_cast< Player* >(objA->GetPlayerOwner());
        Player* b = static_cast< Player* >(objB->GetPlayerOwner());

        auto atA = a->GetArea();
        auto atB = b->GetArea();

        if (((atA && atA->flags & 0x800) != 0) || ((atB && atB->flags & 0x800) != 0))
            return false;

        if (hostile)
        {
            if (!b->IsSanctuaryFlagged() && (b->IsPvPFlagged() || b->IsFFAPvPFlagged()))
                return true;
            else
                return false;
        }

    }

    return hostile;
}

/// Where we check if we object A can attack object B. This is used in many feature's
/// Including the spell class and the player class.
bool isAttackable(Object* objA, Object* objB, bool CheckStealth)
{
    if ((objA == NULL) || (objB == NULL))
        return false;

    if (!objA->IsInWorld() || !objB->IsInWorld())
        return false;

    if (objA == objB)
        return false;   // can't attack self.. this causes problems with buffs if we don't have it :p

    if ((objA->m_phase & objB->m_phase) == 0)     //What you can't see, you can't attack either...
        return false;

    if (objA->IsCorpse() || objB->IsCorpse())
        return false;

    // Checks for untouchable, unattackable
    if (objA->IsUnit() && objA->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNTED_TAXI | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_DEAD))
        return false;

    if (objB->IsUnit())
    {
        if (objB->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNTED_TAXI | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_DEAD))
            return false;

        /// added by Zack :
        /// we cannot attack shealthed units. Maybe checked in other places too ?
        /// !! warning, this presumes that objA is attacking ObjB
        /// Capt: Added the possibility to disregard this (regarding the spell class)
        if (static_cast< Unit* >(objB)->IsStealth() && CheckStealth)
            return false;
    }

    if ((objA->GetPlayerOwner() != NULL) && (objB->GetPlayerOwner() != NULL))
    {
        Player* a = static_cast< Player* >(objA->GetPlayerOwner());
        Player* b = static_cast< Player* >(objB->GetPlayerOwner());

        if ((a->DuelingWith == b) && (a->GetDuelState() == DUEL_STATE_STARTED))
            return true;

        if (b->IsSanctuaryFlagged())
            return false;

        //players in same group should not attack each other. Required for arenas with mixed groups
        if ((a->GetGroup() != NULL) && (a->GetGroup() == b->GetGroup()))
            return false;

        if (a->IsFFAPvPFlagged() && b->IsFFAPvPFlagged())
            return true;
    }

    if (objA->m_faction == nullptr || objB->m_faction == nullptr)     // no faction, no kill (added because spell_caster gos should summon a trap instead of casting the spell directly.)
        return false;

    if (objA->m_faction == objB->m_faction)    // same faction can't kill each other unless in ffa pvp/duel
        return false;

    // Neutral Creature Check
    if (objA->IsPlayer() || objA->IsPet())
    {

        if ((objB->m_factionDBC->RepListId == -1) && (objB->m_faction->HostileMask == 0) && (objB->m_faction->FriendlyMask == 0))
            return true;
    }
    else if (objB->IsPlayer() || objB->IsPet())
    {
        if ((objA->m_factionDBC->RepListId == -1) && (objA->m_faction->HostileMask == 0) && (objA->m_faction->FriendlyMask == 0))
            return true;
    }

    bool attackable = isHostile(objA, objB);   // B is attackable if its hostile for A

    return attackable;
}

bool isCombatSupport(Object* objA, Object* objB)// B combat supports A?
{
    if (!objA || !objB)
        return false;

    if (objA->IsCorpse())
        return false;

    if (objB->IsCorpse())
        return false;

    if (!objA->IsCreature() || !objB->IsCreature()) return false;    // cebernic: lowchance crashfix.
    // also if it's not a unit, it shouldn't support combat anyways.

    if (objA->IsPet() || objB->IsPet())   // fixes an issue where horde pets would chain aggro horde guards and vice versa for alliance.
        return false;

    if (!(objA->m_phase & objB->m_phase))   //What you can't see, you can't support either...
        return false;

    bool combatSupport = false;

    uint32 fSupport = objB->m_faction->FriendlyMask;
    uint32 myFaction = objA->m_faction->Mask;

    if (myFaction & fSupport)
    {
        combatSupport = true;
    }
    // check friend/enemy list
    for (uint8 i = 0; i < 4; i++)
    {
        if (objB->m_faction->EnemyFactions[i] == objA->m_faction->Faction)
        {
            combatSupport = false;
            break;
        }
        if (objB->m_faction->FriendlyFactions[i] == objA->m_faction->Faction)
        {
            combatSupport = true;
            break;
        }
    }

    return combatSupport;
}

bool isAlliance(Object* objA)// A is alliance?
{
    DBC::Structures::FactionTemplateEntry const* m_sw_faction = sFactionTemplateStore.LookupEntry(11);
    DBC::Structures::FactionEntry const* m_sw_factionDBC = sFactionStore.LookupEntry(72);
    if (!objA)          // || objA->m_factionDBC == NULL || objA->m_faction == NULL
        return true;

    if (m_sw_faction == objA->m_faction || m_sw_factionDBC == objA->m_factionDBC)
        return true;

    //bool hostile = false;
    uint32 faction = m_sw_faction->Faction;
    uint32 host = objA->m_faction->HostileMask;

    if (faction & host)
        return false;

    // check friend/enemy list
    for (uint8 i = 0; i < 4; i++)
    {
        if (objA->m_faction->EnemyFactions[i] == faction)
            return false;
    }

    faction = objA->m_faction->Faction;
    host = m_sw_faction->HostileMask;

    if (faction & host)
        return false;

    // check friend/enemy list
    for (uint8 i = 0; i < 4; i++)
    {
        if (objA->m_faction->EnemyFactions[i] == faction)
            return false;
    }

    return true;
}
<|endoftext|>


<commit_before>#include "../http/client-channel.hh"
#include "http-call.hh"
#include "json.hh"

namespace mimosa
{
namespace rpc
{

bool httpCall(const std::string               &url,
              const google::protobuf::Message &request,
              google::protobuf::Message       *response)
{
    http::ClientChannel cc;
    http::RequestWriter::Ptr rw = new http::RequestWriter(cc);

    /* request header */
    rw->setUrl(url);
    rw->setMethod(http::kMethodPost);
    rw->setProto(1, 1);
    rw->setContentLength(request.ByteSize());
    rw->setContentType("application/json");
    if (!rw->sendRequest())
        return false;

    /* request body (JSON) */
    jsonEncode(rw.get(), request);

    /* decode response */
    auto rr = rw->response();
    if (!rr)
        return false;

    if (response)
        jsonDecode(rr.get(), response);

    return true;
}

}
}
<commit_msg>Make a full json buffer first<commit_after>#include "../stream/string-stream.hh"
#include "../stream/copy.hh"
#include "../http/client-channel.hh"
#include "http-call.hh"
#include "json.hh"

namespace mimosa
{
namespace rpc
{

bool httpCall(const std::string               &url,
              const google::protobuf::Message &request,
              google::protobuf::Message       *response)
{
    http::ClientChannel cc;
    http::RequestWriter::Ptr rw = new http::RequestWriter(cc);

    /* request body (JSON) */
    stream::StringStream::Ptr data = new stream::StringStream;
    jsonEncode(data.get(), request);

    /* request header */
    rw->setUrl(url);
    rw->setMethod(http::kMethodPost);
    rw->setProto(1, 1);
    rw->setContentType("application/json");
    rw->setContentLength(data->str().size());
    if (!rw->sendRequest())
        return false;

    stream::copy(*data, *rw);

    /* decode response */
    auto rr = rw->response();
    if (!rr)
        return false;

    if (response)
        jsonDecode(rr.get(), response);

    return true;
}

}
}
<|endoftext|>


<commit_before>// SciTE - Scintilla based Text Editor
/** @file DirectorExtension.cxx
 ** Extension for communicating with a director program.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#include <string>
#include <vector>
#include <set>
#include <map>

#undef _WIN32_WINNT
#define _WIN32_WINNT  0x0500
#ifdef _MSC_VER
// windows.h, et al, use a lot of nameless struct/unions - can't fix it, so allow it
#pragma warning(disable: 4201)
#endif
#include <windows.h>
#ifdef _MSC_VER
// okay, that's done, don't allow it in our code
#pragma warning(default: 4201)
#endif
#include <commctrl.h>

#include "Scintilla.h"
#include "ILexer.h"

#include "GUI.h"
#include "SString.h"
#include "StringList.h"
#include "StringHelpers.h"
#include "FilePath.h"
#include "PropSetFile.h"
#include "Extender.h"
#include "DirectorExtension.h"
#include "SciTE.h"
#include "Mutex.h"
#include "JobQueue.h"
#include "Cookie.h"
#include "Worker.h"
#include "SciTEBase.h"

static ExtensionAPI *host = 0;
static HWND wDirector = 0;
static HWND wCorrespondent = 0;
static HWND wReceiver = 0;
static bool startedByDirector = false;
static bool shuttingDown = false;
unsigned int SDI = 0;

static void SendDirector(const char *verb, const char *arg = 0) {
	if ((wDirector != 0) || (wCorrespondent != 0)) {
		HWND wDestination = wCorrespondent;
		SString addressedMessage;
		if (wDestination) {
			addressedMessage += ":";
			SString address(reinterpret_cast<size_t>(wDestination));
			addressedMessage += address;
			addressedMessage += ":";
		} else {
			wDestination = wDirector;
		}
		addressedMessage += verb;
		addressedMessage += ":";
		if (arg)
			addressedMessage += arg;
		char *slashedMessage = Slash(addressedMessage.c_str(), false);
		if (slashedMessage) {
			COPYDATASTRUCT cds;
			cds.dwData = 0;
			cds.cbData = static_cast<int>(strlen(slashedMessage));
			cds.lpData = reinterpret_cast<void *>(
			                 const_cast<char *>(slashedMessage));
			::SendMessage(wDestination, WM_COPYDATA,
			              reinterpret_cast<WPARAM>(wReceiver),
			              reinterpret_cast<LPARAM>(&cds));
			delete []slashedMessage;
		}
	}
}

static void SendDirector(const char *verb, sptr_t arg) {
	SString s(static_cast<size_t>(arg));
	::SendDirector(verb, s.c_str());
}

static void CheckEnvironment(ExtensionAPI *host) {
	if (host && !shuttingDown) {
		if (!wDirector) {
			char *director = host->Property("director.hwnd");
			if (director && *director) {
				startedByDirector = true;
				wDirector = reinterpret_cast<HWND>(atoi(director));
				// Director is just seen so identify this to it
				::SendDirector("identity", reinterpret_cast<sptr_t>(wReceiver));
			}
			delete []director;
		}
		SString sReceiver(reinterpret_cast<size_t>(wReceiver));
		host->SetProperty("WindowID", sReceiver.c_str());
	}
}

static TCHAR DirectorExtension_ClassName[] = TEXT("DirectorExtension");

static LRESULT HandleCopyData(LPARAM lParam) {
	COPYDATASTRUCT *pcds = reinterpret_cast<COPYDATASTRUCT *>(lParam);
	// Copy into an temporary buffer to ensure \0 terminated
	if (pcds->lpData) {
		char *dataCopy = new char[pcds->cbData + 1];
		strncpy(dataCopy, reinterpret_cast<char *>(pcds->lpData), pcds->cbData);
		dataCopy[pcds->cbData] = '\0';
		DirectorExtension::Instance().HandleStringMessage(dataCopy);
		delete []dataCopy;
	}
	return 0;
}

LRESULT PASCAL DirectorExtension_WndProc(
    HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) {
	if (iMessage == WM_COPYDATA) {
		return HandleCopyData(lParam);
	} else if (iMessage == SDI) {
		return SDI;
	}
	return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}

static void DirectorExtension_Register(HINSTANCE hInstance) {
	WNDCLASS wndclass;
	wndclass.style = 0;
	wndclass.lpfnWndProc = DirectorExtension_WndProc;
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hInstance = hInstance;
	wndclass.hIcon = 0;
	wndclass.hCursor = NULL;
	wndclass.hbrBackground = NULL;
	wndclass.lpszMenuName = 0;
	wndclass.lpszClassName = DirectorExtension_ClassName;
	if (!::RegisterClass(&wndclass))
		::exit(FALSE);
}

DirectorExtension &DirectorExtension::Instance() {
	static DirectorExtension singleton;
	return singleton;
}

bool DirectorExtension::Initialise(ExtensionAPI *host_) {
	host = host_;
	SDI = ::RegisterWindowMessage(TEXT("SciTEDirectorInterface"));
	HINSTANCE hInstance = reinterpret_cast<HINSTANCE>(
	                          host->GetInstance());
	DirectorExtension_Register(hInstance);
	wReceiver = ::CreateWindow(
	                DirectorExtension_ClassName,
	                DirectorExtension_ClassName,
	                0,
	                0, 0, 0, 0,
	                0,
	                0,
	                hInstance,
	                0);
	if (!wReceiver)
		::exit(FALSE);
	// Make the frame window handle available so the director can activate it.
	::SetWindowLongPtr(wReceiver, GWLP_USERDATA,
		reinterpret_cast<LONG_PTR>((static_cast<SciTEBase*>(host))->GetID()));
	CheckEnvironment(host);
	return true;
}

bool DirectorExtension::Finalise() {
	::SendDirector("closing");
	if (wReceiver)
		::DestroyWindow(wReceiver);
	wReceiver = 0;
	return true;
}

bool DirectorExtension::Clear() {
	return false;
}

bool DirectorExtension::Load(const char *) {
	return false;
}

bool DirectorExtension::OnOpen(const char *path) {
	CheckEnvironment(host);
	if (*path) {
		::SendDirector("opened", path);
	}
	return false;
}

bool DirectorExtension::OnSwitchFile(const char *path) {
	CheckEnvironment(host);
	if (*path) {
		::SendDirector("switched", path);
	}
	return false;
}

bool DirectorExtension::OnSave(const char *path) {
	CheckEnvironment(host);
	if (*path) {
		::SendDirector("saved", path);
	}
	return false;
}

bool DirectorExtension::OnClose(const char *path) {
	CheckEnvironment(host);
	if (*path) {
		::SendDirector("closed", path);
	}
	return false;
}

bool DirectorExtension::OnChar(char) {
	return false;
}

bool DirectorExtension::OnExecute(const char *cmd) {
	CheckEnvironment(host);
	::SendDirector("macro:run", cmd);
	return false;
}

bool DirectorExtension::OnSavePointReached() {
	return false;
}

bool DirectorExtension::OnSavePointLeft() {
	return false;
}

bool DirectorExtension::OnStyle(unsigned int, int, int, StyleWriter *) {
	return false;
}

// These should probably have arguments

bool DirectorExtension::OnDoubleClick() {
	return false;
}

bool DirectorExtension::OnUpdateUI() {
	return false;
}

bool DirectorExtension::OnMarginClick() {
	return false;
}

bool DirectorExtension::OnMacro(const char *command, const char *params) {
	SendDirector(command, params);
	return false;
}

bool DirectorExtension::SendProperty(const char *prop) {
	CheckEnvironment(host);
	if (*prop) {
		::SendDirector("property", prop);
	}
	return false;
}

void DirectorExtension::HandleStringMessage(const char *message) {
	// Message may contain multiple commands separated by '\n'
	// Reentrance trouble - if this function is reentered, the wCorrespondent may
	// be set to zero before time.
	StringList wlMessage(true);
	wlMessage.Set(message);
	for (int i = 0; i < wlMessage.len; i++) {
		// Message format is [:return address:]command:argument
		char *cmd = wlMessage[i];
		if (*cmd == ':') {
			// There is a return address
			char *colon = strchr(cmd + 1, ':');
			if (colon) {
				*colon = '\0';
				wCorrespondent = reinterpret_cast<HWND>(atoi(cmd + 1));
				cmd = colon + 1;
			}
		}
		if (isprefix(cmd, "identity:")) {
			char *arg = strchr(cmd, ':');
			if (arg)
				wDirector = reinterpret_cast<HWND>(atoi(arg + 1));
		} else if (isprefix(cmd, "closing:")) {
			wDirector = 0;
			if (startedByDirector) {
				shuttingDown = true;
				host->ShutDown();
				shuttingDown = false;
			}
		} else if (host) {
			host->Perform(cmd);
		}
		wCorrespondent = 0;
	}
}

#ifdef _MSC_VER
// Unreferenced inline functions are OK
#pragma warning(disable: 4514)
#endif
<commit_msg>Rename variable to avoid shadowing global.<commit_after>// SciTE - Scintilla based Text Editor
/** @file DirectorExtension.cxx
 ** Extension for communicating with a director program.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#include <string>
#include <vector>
#include <set>
#include <map>

#undef _WIN32_WINNT
#define _WIN32_WINNT  0x0500
#ifdef _MSC_VER
// windows.h, et al, use a lot of nameless struct/unions - can't fix it, so allow it
#pragma warning(disable: 4201)
#endif
#include <windows.h>
#ifdef _MSC_VER
// okay, that's done, don't allow it in our code
#pragma warning(default: 4201)
#endif
#include <commctrl.h>

#include "Scintilla.h"
#include "ILexer.h"

#include "GUI.h"
#include "SString.h"
#include "StringList.h"
#include "StringHelpers.h"
#include "FilePath.h"
#include "PropSetFile.h"
#include "Extender.h"
#include "DirectorExtension.h"
#include "SciTE.h"
#include "Mutex.h"
#include "JobQueue.h"
#include "Cookie.h"
#include "Worker.h"
#include "SciTEBase.h"

static ExtensionAPI *host = 0;
static HWND wDirector = 0;
static HWND wCorrespondent = 0;
static HWND wReceiver = 0;
static bool startedByDirector = false;
static bool shuttingDown = false;
unsigned int SDI = 0;

static void SendDirector(const char *verb, const char *arg = 0) {
	if ((wDirector != 0) || (wCorrespondent != 0)) {
		HWND wDestination = wCorrespondent;
		SString addressedMessage;
		if (wDestination) {
			addressedMessage += ":";
			SString address(reinterpret_cast<size_t>(wDestination));
			addressedMessage += address;
			addressedMessage += ":";
		} else {
			wDestination = wDirector;
		}
		addressedMessage += verb;
		addressedMessage += ":";
		if (arg)
			addressedMessage += arg;
		char *slashedMessage = Slash(addressedMessage.c_str(), false);
		if (slashedMessage) {
			COPYDATASTRUCT cds;
			cds.dwData = 0;
			cds.cbData = static_cast<int>(strlen(slashedMessage));
			cds.lpData = reinterpret_cast<void *>(
			                 const_cast<char *>(slashedMessage));
			::SendMessage(wDestination, WM_COPYDATA,
			              reinterpret_cast<WPARAM>(wReceiver),
			              reinterpret_cast<LPARAM>(&cds));
			delete []slashedMessage;
		}
	}
}

static void SendDirector(const char *verb, sptr_t arg) {
	SString s(static_cast<size_t>(arg));
	::SendDirector(verb, s.c_str());
}

static void CheckEnvironment(ExtensionAPI *phost) {
	if (phost && !shuttingDown) {
		if (!wDirector) {
			char *director = phost->Property("director.hwnd");
			if (director && *director) {
				startedByDirector = true;
				wDirector = reinterpret_cast<HWND>(atoi(director));
				// Director is just seen so identify this to it
				::SendDirector("identity", reinterpret_cast<sptr_t>(wReceiver));
			}
			delete []director;
		}
		SString sReceiver(reinterpret_cast<size_t>(wReceiver));
		phost->SetProperty("WindowID", sReceiver.c_str());
	}
}

static TCHAR DirectorExtension_ClassName[] = TEXT("DirectorExtension");

static LRESULT HandleCopyData(LPARAM lParam) {
	COPYDATASTRUCT *pcds = reinterpret_cast<COPYDATASTRUCT *>(lParam);
	// Copy into an temporary buffer to ensure \0 terminated
	if (pcds->lpData) {
		char *dataCopy = new char[pcds->cbData + 1];
		strncpy(dataCopy, reinterpret_cast<char *>(pcds->lpData), pcds->cbData);
		dataCopy[pcds->cbData] = '\0';
		DirectorExtension::Instance().HandleStringMessage(dataCopy);
		delete []dataCopy;
	}
	return 0;
}

LRESULT PASCAL DirectorExtension_WndProc(
    HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) {
	if (iMessage == WM_COPYDATA) {
		return HandleCopyData(lParam);
	} else if (iMessage == SDI) {
		return SDI;
	}
	return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}

static void DirectorExtension_Register(HINSTANCE hInstance) {
	WNDCLASS wndclass;
	wndclass.style = 0;
	wndclass.lpfnWndProc = DirectorExtension_WndProc;
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hInstance = hInstance;
	wndclass.hIcon = 0;
	wndclass.hCursor = NULL;
	wndclass.hbrBackground = NULL;
	wndclass.lpszMenuName = 0;
	wndclass.lpszClassName = DirectorExtension_ClassName;
	if (!::RegisterClass(&wndclass))
		::exit(FALSE);
}

DirectorExtension &DirectorExtension::Instance() {
	static DirectorExtension singleton;
	return singleton;
}

bool DirectorExtension::Initialise(ExtensionAPI *host_) {
	host = host_;
	SDI = ::RegisterWindowMessage(TEXT("SciTEDirectorInterface"));
	HINSTANCE hInstance = reinterpret_cast<HINSTANCE>(
	                          host->GetInstance());
	DirectorExtension_Register(hInstance);
	wReceiver = ::CreateWindow(
	                DirectorExtension_ClassName,
	                DirectorExtension_ClassName,
	                0,
	                0, 0, 0, 0,
	                0,
	                0,
	                hInstance,
	                0);
	if (!wReceiver)
		::exit(FALSE);
	// Make the frame window handle available so the director can activate it.
	::SetWindowLongPtr(wReceiver, GWLP_USERDATA,
		reinterpret_cast<LONG_PTR>((static_cast<SciTEBase*>(host))->GetID()));
	CheckEnvironment(host);
	return true;
}

bool DirectorExtension::Finalise() {
	::SendDirector("closing");
	if (wReceiver)
		::DestroyWindow(wReceiver);
	wReceiver = 0;
	return true;
}

bool DirectorExtension::Clear() {
	return false;
}

bool DirectorExtension::Load(const char *) {
	return false;
}

bool DirectorExtension::OnOpen(const char *path) {
	CheckEnvironment(host);
	if (*path) {
		::SendDirector("opened", path);
	}
	return false;
}

bool DirectorExtension::OnSwitchFile(const char *path) {
	CheckEnvironment(host);
	if (*path) {
		::SendDirector("switched", path);
	}
	return false;
}

bool DirectorExtension::OnSave(const char *path) {
	CheckEnvironment(host);
	if (*path) {
		::SendDirector("saved", path);
	}
	return false;
}

bool DirectorExtension::OnClose(const char *path) {
	CheckEnvironment(host);
	if (*path) {
		::SendDirector("closed", path);
	}
	return false;
}

bool DirectorExtension::OnChar(char) {
	return false;
}

bool DirectorExtension::OnExecute(const char *cmd) {
	CheckEnvironment(host);
	::SendDirector("macro:run", cmd);
	return false;
}

bool DirectorExtension::OnSavePointReached() {
	return false;
}

bool DirectorExtension::OnSavePointLeft() {
	return false;
}

bool DirectorExtension::OnStyle(unsigned int, int, int, StyleWriter *) {
	return false;
}

// These should probably have arguments

bool DirectorExtension::OnDoubleClick() {
	return false;
}

bool DirectorExtension::OnUpdateUI() {
	return false;
}

bool DirectorExtension::OnMarginClick() {
	return false;
}

bool DirectorExtension::OnMacro(const char *command, const char *params) {
	SendDirector(command, params);
	return false;
}

bool DirectorExtension::SendProperty(const char *prop) {
	CheckEnvironment(host);
	if (*prop) {
		::SendDirector("property", prop);
	}
	return false;
}

void DirectorExtension::HandleStringMessage(const char *message) {
	// Message may contain multiple commands separated by '\n'
	// Reentrance trouble - if this function is reentered, the wCorrespondent may
	// be set to zero before time.
	StringList wlMessage(true);
	wlMessage.Set(message);
	for (int i = 0; i < wlMessage.len; i++) {
		// Message format is [:return address:]command:argument
		char *cmd = wlMessage[i];
		if (*cmd == ':') {
			// There is a return address
			char *colon = strchr(cmd + 1, ':');
			if (colon) {
				*colon = '\0';
				wCorrespondent = reinterpret_cast<HWND>(atoi(cmd + 1));
				cmd = colon + 1;
			}
		}
		if (isprefix(cmd, "identity:")) {
			char *arg = strchr(cmd, ':');
			if (arg)
				wDirector = reinterpret_cast<HWND>(atoi(arg + 1));
		} else if (isprefix(cmd, "closing:")) {
			wDirector = 0;
			if (startedByDirector) {
				shuttingDown = true;
				host->ShutDown();
				shuttingDown = false;
			}
		} else if (host) {
			host->Perform(cmd);
		}
		wCorrespondent = 0;
	}
}

#ifdef _MSC_VER
// Unreferenced inline functions are OK
#pragma warning(disable: 4514)
#endif
<|endoftext|>