<commit_before>/*
 * Copyright 2010-2011 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
 * All rights reserved. Distributed under the terms of the MIT License.
 */

#include "HTGStatusBar.h"

HTGStatusBar::HTGStatusBar(BRect frame)
	: BView(BRect(frame.left, frame.Height()+1-B_H_SCROLL_BAR_HEIGHT, frame.right-B_V_SCROLL_BAR_WIDTH, frame.Height()), "StatusBar", B_FOLLOW_LEFT_RIGHT | B_FOLLOW_BOTTOM,  B_WILL_DRAW | B_FRAME_EVENTS)
{
	SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));

	BFont textFont;
	BFont currentFont;
	GetFont(&textFont);
	textFont.SetEncoding(B_UNICODE_UTF8);
	textFont.SetSize(textFont.Size()-2);
	SetFont(&textFont, B_FONT_ALL);

	status = "";
}

HTGStatusBar::~HTGStatusBar()
{

}

void
HTGStatusBar::AttachedToWindow()
{
   if ( Parent() )
      SetViewColor(Parent()->ViewColor());
   BView::AttachedToWindow();
}

void
HTGStatusBar::SetStatus(const char* str)
{
	status = str;
}

void
HTGStatusBar::Draw(BRect updateRect)
{
	/*Draw seperator*/
	SetHighColor(152, 152, 152); //Should find some B_COLOR for this
	StrokeLine(BPoint(Bounds().left, Bounds().top), BPoint(Bounds().right, Bounds().top));

	SetHighColor(16, 16, 16);
	MovePenTo(Bounds().right-StringWidth("Content from Twitter")-3, 11);
	DrawString("Content from Twitter");

	MovePenTo(3, 11);
	DrawString(status);
}
<commit_msg>Should update whole view on resize.<commit_after>/*
 * Copyright 2010-2011 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
 * All rights reserved. Distributed under the terms of the MIT License.
 */

#include "HTGStatusBar.h"

HTGStatusBar::HTGStatusBar(BRect frame)
	: BView(BRect(frame.left, frame.Height()+1-B_H_SCROLL_BAR_HEIGHT, frame.right-B_V_SCROLL_BAR_WIDTH, frame.Height()), "StatusBar", B_FOLLOW_LEFT_RIGHT | B_FOLLOW_BOTTOM,  B_WILL_DRAW | B_FULL_UPDATE_ON_RESIZE)
{
	SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));

	BFont textFont;
	BFont currentFont;
	GetFont(&textFont);
	textFont.SetEncoding(B_UNICODE_UTF8);
	textFont.SetSize(textFont.Size()-2);
	SetFont(&textFont, B_FONT_ALL);

	status = "";
}

HTGStatusBar::~HTGStatusBar()
{

}

void
HTGStatusBar::AttachedToWindow()
{
   if ( Parent() )
      SetViewColor(Parent()->ViewColor());
   BView::AttachedToWindow();
}

void
HTGStatusBar::SetStatus(const char* str)
{
	status = str;
}

void
HTGStatusBar::Draw(BRect updateRect)
{
	/*Draw seperator*/
	SetHighColor(152, 152, 152); //Should find some B_COLOR for this
	StrokeLine(BPoint(Bounds().left, Bounds().top), BPoint(Bounds().right, Bounds().top));

	SetHighColor(16, 16, 16);
	MovePenTo(Bounds().right-StringWidth("Content from Twitter")-3, 11);
	DrawString("Content from Twitter");

	MovePenTo(3, 11);
	DrawString(status);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004-2009  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "User.h"

class CNickServ : public CModule
{
public:
	MODCONSTRUCTOR(CNickServ)
	{
	}

	virtual ~CNickServ()
	{
	}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage)
	{
		if (sArgs.empty())
			m_sPass = GetNV("Password");
		else
			m_sPass = sArgs;

		return true;
	}

	virtual void OnModCommand(const CString& sCommand)
	{
		CString sCmdName = sCommand.Token(0).AsLower();
		if (sCmdName == "set") {
			CString sPass = sCommand.Token(1, true);
			m_sPass = sPass;
			SetNV("Password", m_sPass);
			PutModule("Password set");
		} else {
			PutModule("Commands: set <password>");
		}
	}

	void HandleMessage(CNick& Nick, const CString& sMessage)
	{
		if (!m_sPass.empty()
				&& Nick.GetNick().Equals("NickServ")
				&& sMessage.find("msg") != CString::npos
				&& sMessage.AsUpper().find("IDENTIFY") != CString::npos
				&& sMessage.find("help") == CString::npos) {
			PutIRC("PRIVMSG NickServ :IDENTIFY " + m_sPass);
		}
	}

	virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage)
	{
		HandleMessage(Nick, sMessage);
		return CONTINUE;
	}

	virtual EModRet OnPrivNotice(CNick& Nick, CString& sMessage)
	{
		HandleMessage(Nick, sMessage);
		return CONTINUE;
	}

private:
	CString	m_sPass;
};

MODULEDEFS(CNickServ, "Auths you with NickServ")
<commit_msg>Fix for the new OFTC syntax "authenticate yourself to services with the IDENTIFY command."<commit_after>/*
 * Copyright (C) 2004-2009  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "User.h"

class CNickServ : public CModule
{
public:
	MODCONSTRUCTOR(CNickServ)
	{
	}

	virtual ~CNickServ()
	{
	}

	virtual bool OnLoad(const CString& sArgs, CString& sMessage)
	{
		if (sArgs.empty())
			m_sPass = GetNV("Password");
		else
			m_sPass = sArgs;

		return true;
	}

	virtual void OnModCommand(const CString& sCommand)
	{
		CString sCmdName = sCommand.Token(0).AsLower();
		if (sCmdName == "set") {
			CString sPass = sCommand.Token(1, true);
			m_sPass = sPass;
			SetNV("Password", m_sPass);
			PutModule("Password set");
		} else {
			PutModule("Commands: set <password>");
		}
	}

	void HandleMessage(CNick& Nick, const CString& sMessage)
	{
		if (!m_sPass.empty()
				&& Nick.GetNick().Equals("NickServ")
				&& (sMessage.find("msg") != CString::npos
				 || sMessage.find("authenticate") != CString::npos)
				&& sMessage.AsUpper().find("IDENTIFY") != CString::npos
				&& sMessage.find("help") == CString::npos) {
			PutIRC("PRIVMSG NickServ :IDENTIFY " + m_sPass);
		}
	}

	virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage)
	{
		HandleMessage(Nick, sMessage);
		return CONTINUE;
	}

	virtual EModRet OnPrivNotice(CNick& Nick, CString& sMessage)
	{
		HandleMessage(Nick, sMessage);
		return CONTINUE;
	}

private:
	CString	m_sPass;
};

MODULEDEFS(CNickServ, "Auths you with NickServ")
<|endoftext|>


<commit_before>
#pragma optimize ("", off)
#include "priv.hh"

#include "Geo/pow.hh"

#include "Topology/impl.hh"
#include "Topology/merge.hh"
#include "Topology/shared.hh"
#include "Topology/split.hh"
#include "Utils/enum.hh"

namespace Boolean {

namespace {

const int SAFE_TOL_MULTIPLE_SQ = 3;

void remove_degenerate_edges(Topo::Wrap<Topo::Type::BODY>& _body)
{
  for (bool achange = true; achange; )
  {
    achange = false;
    Topo::Iterator<Topo::Type::BODY, Topo::Type::EDGE> it_ed(_body);
    for (auto edge : it_ed)
    {
      // Removes out degenerate edges.
      Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> vv(edge);
      if (vv.get(0) == vv.get(1))
        continue;
      Geo::Segment seg;
      edge->geom(seg);
      auto tol = edge->tolerance();
      if (Geo::length_square(seg[1] - seg[0]) >
        SAFE_TOL_MULTIPLE_SQ * Geo::sq(tol))
        continue;
      Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> it_ve(edge);
      achange |= Topo::merge(it_ve.get(0), it_ve.get(1));
    }
  }
}

MAKE_ENUM(DegType, NONE, SPLITA, MERGE, SPLITB);

DegType degenerate_triangle(
  const Topo::Wrap<Topo::Type::VERTEX> _verts[3])
{
  if (_verts[0] == _verts[2] || _verts[0] == _verts[1] ||
    _verts[1] == _verts[2])
    return DegType::NONE;
  Geo::Point pt[3];
  double tol = 0;
  for (auto i : { 0, 1, 2 })
  {
    _verts[i]->geom(pt[i]);
    tol = std::max(tol, _verts[i]->tolerance());
  }
  auto vec0 = pt[0] - pt[1];
  auto vec1 = pt[2] - pt[1];
  if (vec0 * vec1 < 0)
    return DegType::NONE;
  auto len0_sq = Geo::length_square(vec0);
  auto len1_sq = Geo::length_square(vec1);
  auto h_sq =
    Geo::length_square(vec0 % vec1) / std::max(len0_sq, len1_sq);
  if (h_sq > SAFE_TOL_MULTIPLE_SQ * Geo::sq(tol))
    return DegType::NONE;
  if (fabs(sqrt(len0_sq) - sqrt(len1_sq)) < sqrt(SAFE_TOL_MULTIPLE_SQ) * tol)
    return DegType::MERGE;
  return len0_sq > len1_sq ? DegType::SPLITA : DegType::SPLITB;
}

void remove_degenerate_triangles(
  Topo::Iterator<Topo::Type::BODY, Topo::Type::FACE>& it_fa)
{
  bool achange = false;
  for (auto face : it_fa)
  {
    Topo::Iterator<Topo::Type::FACE, Topo::Type::COEDGE> fc_it(face);
    if (fc_it.size() < 3)
      continue;
    auto& last_coed = *std::prev(fc_it.end());
    Topo::Iterator<Topo::Type::COEDGE, Topo::Type::VERTEX> cv_it(last_coed);
    Topo::Wrap<Topo::Type::VERTEX> verts[3];
    verts[0] = *(cv_it.begin());
    verts[1] = *(std::next(cv_it.begin()));
    for (auto coed : fc_it)
    {
      cv_it.reset(coed);
      verts[2] = *(std::next(cv_it.begin()));
      switch (degenerate_triangle(verts))
      {
      case DegType::MERGE:
        achange |= Topo::merge(verts[0], verts[2]);
        break;
      case DegType::SPLITA:
        achange |= Topo::split(verts[0], verts[1], verts[2]);
        break;
      case DegType::SPLITB:
        achange |= Topo::split(verts[1], verts[2], verts[0]);
        break;
      }
      std::copy(verts + 1, verts + 3, verts);
    }
  }
}

}//namespace

// Removes coincident consecutive vertices in face loops.
// Removes faces with less than 3 vertices.
bool remove_degeneracies(Topo::Wrap<Topo::Type::BODY>& _body)
{
  remove_degenerate_edges(_body);
  Topo::Iterator<Topo::Type::BODY, Topo::Type::FACE> it_fa(_body);
  remove_degenerate_triangles(it_fa);
  bool achange = false;
  for (auto face : it_fa)
  {
    if (!face.get())
      continue;
    bool loc_change;
    do {
      loc_change = false;
      auto n_verts = face->size(Topo::Direction::Down);
      if (n_verts >= 3)
      {
        auto prev_vert_ptr = face->get(Topo::Direction::Down, 0);
        for (size_t j = n_verts; j-- > 0; )
        {
          auto curr_vert_ptr = face->get(Topo::Direction::Down, j);
          if (curr_vert_ptr == prev_vert_ptr)
          {
            loc_change = true;
            face->remove_child(j); // curr_vert_ptr->remove();
          }
          else
            prev_vert_ptr = curr_vert_ptr;
        }
      }
      Topo::Iterator<Topo::Type::FACE, Topo::Type::COEDGE> fc_it(face);
      if (fc_it.size() >= 4)
      {
        Topo::Iterator<Topo::Type::COEDGE, Topo::Type::EDGE>
          prev_ed_it(*std::prev(fc_it.end()));
        auto prev_ed = *prev_ed_it.begin();
        std::vector<Topo::Wrap<Topo::Type::VERTEX>> rem_verts;
        for (auto ced : fc_it)
        {
          Topo::Iterator<Topo::Type::COEDGE, Topo::Type::EDGE> ed_it(ced);
          auto ed = *ed_it.begin();
          if (ed == prev_ed)
          {
            auto same_body_faces = [](Topo::Wrap<Topo::Type::EDGE> _ed)
            {
              Topo::Iterator<Topo::Type::EDGE, Topo::Type::FACE> ef_it(_ed);
              auto it = ef_it.begin();
              auto b = (*it)->get(Topo::Direction::Up, 0);
              while (++it != ef_it.end())
                if (b != (*it)->get(Topo::Direction::Up, 0))
                  return false;
              return true;
            };
            if (same_body_faces(ed))
            {
              Topo::Iterator<Topo::Type::COEDGE, Topo::Type::VERTEX> cv_it(ced);
              rem_verts.push_back(cv_it.get(0));
            }
          }
          prev_ed = ed;
        }
        for (auto v : rem_verts)
          face->remove_child(v.get());
        loc_change |= !rem_verts.empty();
      }
      achange |= loc_change;
    } while (loc_change);
    if (face->size(Topo::Direction::Down) < 3)
    {
      achange |= true;
      face->remove();
    }
  }
  return achange;
}

}<commit_msg>Degeneracy clean fix<commit_after>
#pragma optimize ("", off)
#include "priv.hh"

#include <Geo/point_in_polygon.hh>
#include "Geo/pow.hh"

#include "Topology/impl.hh"
#include "Topology/merge.hh"
#include "Topology/shared.hh"
#include "Topology/split.hh"
#include "Utils/enum.hh"

namespace Boolean {

namespace {

const int SAFE_TOL_MULTIPLE_SQ = 3;

void remove_degenerate_edges(Topo::Wrap<Topo::Type::BODY>& _body)
{
  for (bool achange = true; achange; )
  {
    achange = false;
    Topo::Iterator<Topo::Type::BODY, Topo::Type::EDGE> it_ed(_body);
    for (auto edge : it_ed)
    {
      // Removes out degenerate edges.
      Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> vv(edge);
      if (vv.get(0) == vv.get(1))
        continue;
      Geo::Segment seg;
      edge->geom(seg);
      auto tol = edge->tolerance();
      if (Geo::length_square(seg[1] - seg[0]) >
        SAFE_TOL_MULTIPLE_SQ * Geo::sq(tol))
        continue;
      Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> it_ve(edge);
      achange |= Topo::merge(it_ve.get(0), it_ve.get(1));
    }
  }
}

MAKE_ENUM(DegType, NONE, SPLITA, MERGE, SPLITB);

DegType degenerate_triangle(
  const Topo::Wrap<Topo::Type::VERTEX> _verts[3])
{
  if (_verts[0] == _verts[2] || _verts[0] == _verts[1] ||
    _verts[1] == _verts[2])
    return DegType::NONE;
  Geo::Point pt[3];
  double tol = 0;
  for (auto i : { 0, 1, 2 })
  {
    _verts[i]->geom(pt[i]);
    tol = std::max(tol, _verts[i]->tolerance());
  }
  auto vec0 = pt[0] - pt[1];
  auto vec1 = pt[2] - pt[1];
  if (vec0 * vec1 < 0)
    return DegType::NONE;
  auto len0_sq = Geo::length_square(vec0);
  auto len1_sq = Geo::length_square(vec1);
  auto h_sq =
    Geo::length_square(vec0 % vec1) / std::max(len0_sq, len1_sq);
  if (h_sq > SAFE_TOL_MULTIPLE_SQ * Geo::sq(tol))
    return DegType::NONE;
  if (fabs(sqrt(len0_sq) - sqrt(len1_sq)) < sqrt(SAFE_TOL_MULTIPLE_SQ) * tol)
    return DegType::MERGE;
  return len0_sq > len1_sq ? DegType::SPLITA : DegType::SPLITB;
}

void remove_degenerate_triangles(
  Topo::Iterator<Topo::Type::BODY, Topo::Type::FACE>& it_fa)
{
  bool achange = false;
  for (auto face : it_fa)
  {
    Topo::Iterator<Topo::Type::FACE, Topo::Type::COEDGE> fc_it(face);
    if (fc_it.size() < 3)
      continue;
    auto& last_coed = *std::prev(fc_it.end());
    Topo::Iterator<Topo::Type::COEDGE, Topo::Type::VERTEX> cv_it(last_coed);
    Topo::Wrap<Topo::Type::VERTEX> verts[3];
    verts[0] = *(cv_it.begin());
    verts[1] = *(std::next(cv_it.begin()));
    for (auto coed : fc_it)
    {
      cv_it.reset(coed);
      verts[2] = *(std::next(cv_it.begin()));
      switch (degenerate_triangle(verts))
      {
      case DegType::MERGE:
        achange |= Topo::merge(verts[0], verts[2]);
        break;
      case DegType::SPLITA:
        achange |= Topo::split(verts[0], verts[1], verts[2]);
        break;
      case DegType::SPLITB:
        achange |= Topo::split(verts[1], verts[2], verts[0]);
        break;
      }
      std::copy(verts + 1, verts + 3, verts);
    }
  }
}

bool external_spike(const Topo::Wrap<Topo::Type::FACE>& _face,
  const Topo::Wrap<Topo::Type::EDGE>& _ed)
{
  Topo::Iterator<Topo::Type::EDGE, Topo::Type::VERTEX> ev_it(_ed);
  Topo::Iterator<Topo::Type::FACE, Topo::Type::VERTEX> fv_it(_face);
  int dupl[2] = { 0, 0 };
  size_t ins = SIZE_MAX;
  std::vector<Topo::Wrap<Topo::Type::VERTEX>> other_vertices;
  for (auto v : fv_it)
  {
    int i = 0;
    for (; i < 2 && v != ev_it.get(i); ++i);
    if (i >= 2)
      other_vertices.push_back(v);
    else
    {
      ++dupl[i];
      if (ins == SIZE_MAX)
      {
        ins = other_vertices.size();
        other_vertices.emplace_back();
      }
    }
  }
  if (ins >= other_vertices.size())
    return false;
  size_t i = dupl[0] > dupl[1] ? 0 : 1;
  other_vertices[ins] = ev_it.get(i);
  Geo::Point deg_pt;
  ev_it.get(1 - i)->geom(deg_pt);
  std::vector<Geo::Point> polygon(other_vertices.size());
  for(i = 0; i < other_vertices.size(); ++i)
    other_vertices[i]->geom(polygon[i]);

  auto pt_class = Geo::PointInPolygon::classify(polygon, deg_pt);
  return pt_class == Geo::PointInPolygon::Outside;
}

bool unique_body_faces(Topo::Wrap<Topo::Type::EDGE> _ed)
{
  Topo::Iterator<Topo::Type::EDGE, Topo::Type::FACE> ef_it(_ed);
  auto it = ef_it.begin();
  auto b = (*it)->get(Topo::Direction::Up, 0);
  while (++it != ef_it.end())
    if (b != (*it)->get(Topo::Direction::Up, 0))
      return false;
  return true;
};

}//namespace

// Removes coincident consecutive vertices in face loops.
// Removes faces with less than 3 vertices.
bool remove_degeneracies(Topo::Wrap<Topo::Type::BODY>& _body)
{
  remove_degenerate_edges(_body);
  Topo::Iterator<Topo::Type::BODY, Topo::Type::FACE> it_fa(_body);
  remove_degenerate_triangles(it_fa);
  bool achange = false;
  for (auto face : it_fa)
  {
    if (!face.get())
      continue;
    bool loc_change;
    do {
      loc_change = false;
      auto n_verts = face->size(Topo::Direction::Down);
      if (n_verts >= 3)
      {
        auto prev_vert_ptr = face->get(Topo::Direction::Down, 0);
        for (size_t j = n_verts; j-- > 0; )
        {
          auto curr_vert_ptr = face->get(Topo::Direction::Down, j);
          if (curr_vert_ptr == prev_vert_ptr)
          {
            loc_change = true;
            face->remove_child(j); // curr_vert_ptr->remove();
          }
          else
            prev_vert_ptr = curr_vert_ptr;
        }
      }
      Topo::Iterator<Topo::Type::FACE, Topo::Type::COEDGE> fc_it(face);
      if (fc_it.size() >= 4)
      {
        Topo::Iterator<Topo::Type::COEDGE, Topo::Type::EDGE>
          prev_ed_it(*std::prev(fc_it.end()));
        auto prev_ed = *prev_ed_it.begin();
        std::vector<Topo::Wrap<Topo::Type::VERTEX>> rem_verts;
        for (auto ced : fc_it)
        {
          Topo::Iterator<Topo::Type::COEDGE, Topo::Type::EDGE> ed_it(ced);
          auto ed = *ed_it.begin();
          if (ed == prev_ed)
          {
            if (unique_body_faces(ed) || external_spike(face, ed))
            {
              Topo::Iterator<Topo::Type::COEDGE, Topo::Type::VERTEX> cv_it(ced);
              rem_verts.push_back(cv_it.get(0));
            }
          }
          prev_ed = ed;
        }
        for (auto v : rem_verts)
          face->remove_child(v.get());
        loc_change |= !rem_verts.empty();
      }
      achange |= loc_change;
    } while (loc_change);
    if (face->size(Topo::Direction::Down) < 3)
    {
      achange |= true;
      face->remove();
    }
  }
  return achange;
}

}<|endoftext|>


<commit_before>#include "BBE/BrotBoxEngine.h"
#include <iostream>

constexpr int WINDOW_WIDTH = 1280;
constexpr int WINDOW_HEIGHT = 720;

class MyGame : public bbe::Game
{
private:
	struct Balloon {
		float x;
		float y;
		float width;
		float height;
		float hue;
	};

	static constexpr int BALLOON_WIDTH = 40;
	static constexpr int BALLOON_HEIGHT = 60;

	bool gameover = false;
	int score = 0;

	bbe::Font font;
	bbe::Random random;
	bbe::Image background;
	bbe::List<Balloon> balloons;

	void addBalloon() {
		balloons.add(
			Balloon {
				random.randomFloat() * (WINDOW_WIDTH - BALLOON_WIDTH),
				WINDOW_HEIGHT,
				BALLOON_WIDTH,
				BALLOON_HEIGHT,
				randomBalloonHue()
			}
		);
	}

	float randomBalloonHue() {
		return random.randomFloat() * 360;
	}

	bool checkGameOver(const Balloon& b) {
		return (b.y <= font.getFontSize() + 40);
	}

	bool checkMousePosition(const Balloon& b) {
		return (getMouseY() < b.y + b.height && getMouseY() > b.y)
			&& (getMouseX() < b.x + b.width  && getMouseX() > b.x);
	}

public:
	virtual void onStart() override
	{
		font.load("arial.ttf", 100);
		background.load(BBE_APPLICATION_ASSET_PATH "/sky.jpg");
		addBalloon();
	}

	virtual void update(float timeSinceLastFrame) override
	{
		if (gameover) return;

		const size_t amountOfBalloons = balloons.getLength();
		for (size_t i = 0; i < amountOfBalloons; i++) {
			Balloon& b = balloons[i];
			if (checkGameOver(b)) {
				gameover = true;
			}

			if (checkMousePosition(b) && isMousePressed(bbe::MouseButton::LEFT)) {
				b.y = WINDOW_HEIGHT;
				b.x = random.randomFloat(WINDOW_WIDTH - b.width);
				b.hue = randomBalloonHue();
				score++;

				if (random.randomFloat()<0.2) {
					addBalloon();
				}
			}
			b.y-=timeSinceLastFrame*60;
		}
	}

	virtual void draw3D(bbe::PrimitiveBrush3D & brush) override
	{
	}

	virtual void draw2D(bbe::PrimitiveBrush2D& brush) override
	{
		brush.setColorRGB(1, 1, 1);
		brush.fillRect(bbe::Rectangle(0, 0, WINDOW_WIDTH, font.getFontSize() + 40));

		brush.setColorRGB(0, 0, 0);
		bbe::String currentScore = "Your Score: ";
		currentScore += score;
		brush.fillText(10, font.getFontSize() + 20, currentScore.getRaw(), font);

		brush.setColorRGB(0, 0, 0);
		brush.fillLine(0, font.getFontSize() + 40, WINDOW_WIDTH, font.getFontSize() + 40, 5);

		brush.setColorRGB(1, 1, 1);
		brush.drawImage(bbe::Rectangle(0, font.getFontSize() + 40, WINDOW_WIDTH, background.getHeight()), background);

		for (Balloon& b : balloons) {
			brush.setColorHSV(b.hue, 1, 1);
			brush.fillCircle(bbe::Circle(b.x, b.y, b.width, b.height));
		}

		if (gameover){
			brush.setColorRGB(1, 0, 0);
			brush.fillText(10, WINDOW_HEIGHT/2, "Game Over!", font);

		}
	}

	virtual void onEnd() override
	{
		background.destroy();
		font.destroy();
	}
};

int main()
{
	MyGame *mg = new MyGame();
	mg->start(WINDOW_WIDTH, WINDOW_HEIGHT, "Balloon Game");
	delete mg;
}
<commit_msg>Further ExampleBalloonGame simplification<commit_after>#include "BBE/BrotBoxEngine.h"
#include <iostream>

constexpr int WINDOW_WIDTH = 1280;
constexpr int WINDOW_HEIGHT = 720;

class MyGame : public bbe::Game
{
private:
	static inline bbe::Random random;
	struct Balloon {
		static constexpr float WIDTH = 40;
		static constexpr float HEIGHT = 60;
		float x = random.randomFloat(WINDOW_WIDTH - Balloon::WIDTH);
		float y = WINDOW_HEIGHT;
		float hue = random.randomFloat(360.f);
	};

	bool gameover = false;
	int score = 0;

	bbe::Font font;
	bbe::Image background;
	bbe::List<Balloon> balloons;

	void addBalloon() {
		balloons.add(Balloon());
	}

	bool checkGameOver(const Balloon& b) {
		return (b.y <= font.getFontSize() + 40);
	}

	bool checkMousePosition(const Balloon& b) {
		return (getMouseX() < b.x + Balloon::WIDTH  && getMouseX() > b.x)
		    && (getMouseY() < b.y + Balloon::HEIGHT && getMouseY() > b.y);
	}

public:
	virtual void onStart() override
	{
		font.load("arial.ttf", 100);
		background.load(BBE_APPLICATION_ASSET_PATH "/sky.jpg");
		addBalloon();
	}

	virtual void update(float timeSinceLastFrame) override
	{
		if (gameover) return;

		size_t amountOfBalloonsToAdd = 0;
		bool balloonClickedThisFrame = false;
		for (Balloon& b : balloons) {
			if (checkGameOver(b)) {
				gameover = true;
			}

			if (checkMousePosition(b) && isMousePressed(bbe::MouseButton::LEFT) && !balloonClickedThisFrame) {
				b = Balloon();
				score++;
				balloonClickedThisFrame = true;
				if (random.randomFloat()<0.2) {
					amountOfBalloonsToAdd++;
				}
			}

			b.y-=timeSinceLastFrame*60;
		}
		for (size_t i = 0; i < amountOfBalloonsToAdd; i++) {
			addBalloon();
		}
	}

	virtual void draw3D(bbe::PrimitiveBrush3D & brush) override
	{
	}

	virtual void draw2D(bbe::PrimitiveBrush2D& brush) override
	{
		brush.setColorRGB(1, 1, 1);
		brush.fillRect(bbe::Rectangle(0, 0, WINDOW_WIDTH, font.getFontSize() + 40));

		brush.setColorRGB(0, 0, 0);
		bbe::String currentScore = "Your Score: ";
		currentScore += score;
		brush.fillText(10, font.getFontSize() + 20, currentScore.getRaw(), font);

		brush.setColorRGB(0, 0, 0);
		brush.fillLine(0, font.getFontSize() + 40, WINDOW_WIDTH, font.getFontSize() + 40, 5);

		brush.setColorRGB(1, 1, 1);
		brush.drawImage(bbe::Rectangle(0, font.getFontSize() + 40, WINDOW_WIDTH, background.getHeight()), background);

		for (Balloon& b : balloons) {
			brush.setColorHSV(b.hue, 1, 1);
			brush.fillCircle(bbe::Circle(b.x, b.y, Balloon::WIDTH, Balloon::HEIGHT));
		}

		if (gameover){
			brush.setColorRGB(1, 0, 0);
			brush.fillText(10, WINDOW_HEIGHT/2, "Game Over!", font);

		}
	}

	virtual void onEnd() override
	{
		background.destroy();
		font.destroy();
	}
};

int main()
{
	MyGame *mg = new MyGame();
	mg->start(WINDOW_WIDTH, WINDOW_HEIGHT, "Balloon Game");
	delete mg;
}
<|endoftext|>


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

#ifndef _BASIC_MODSIZEEXCEEDED_HXX
#define _BASIC_MODSIZEEXCEEDED_HXX

#include <com/sun/star/task/XInteractionHandler.hpp>
#include <cppuhelper/implbase1.hxx>

class ModuleSizeExceeded : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >
{
    // c++ interface
    public:
    ModuleSizeExceeded( const com::sun::star::uno::Sequence< ::rtl::OUString>& sModules );

    sal_Bool isAbort() const;
    sal_Bool isApprove() const;

    // uno interface
    public:
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException ) { return m_lContinuations; }
    com::sun::star::uno::Any SAL_CALL getRequest() throw( com::sun::star::uno::RuntimeException )
    {
        return m_aRequest;
    }
    // member
    private:
    rtl::OUString m_sMods;
    com::sun::star::uno::Any m_aRequest;
    com::sun::star::uno::Sequence< com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation > > m_lContinuations;
    com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation > m_xAbort;
    com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation> m_xApprove;
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.2.112); FILE MERGED 2008/03/28 16:06:54 rt 1.2.112.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: modsizeexceeded.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _BASIC_MODSIZEEXCEEDED_HXX
#define _BASIC_MODSIZEEXCEEDED_HXX

#include <com/sun/star/task/XInteractionHandler.hpp>
#include <cppuhelper/implbase1.hxx>

class ModuleSizeExceeded : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >
{
    // c++ interface
    public:
    ModuleSizeExceeded( const com::sun::star::uno::Sequence< ::rtl::OUString>& sModules );

    sal_Bool isAbort() const;
    sal_Bool isApprove() const;

    // uno interface
    public:
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException ) { return m_lContinuations; }
    com::sun::star::uno::Any SAL_CALL getRequest() throw( com::sun::star::uno::RuntimeException )
    {
        return m_aRequest;
    }
    // member
    private:
    rtl::OUString m_sMods;
    com::sun::star::uno::Any m_aRequest;
    com::sun::star::uno::Sequence< com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation > > m_lContinuations;
    com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation > m_xAbort;
    com::sun::star::uno::Reference< com::sun::star::task::XInteractionContinuation> m_xApprove;
};

#endif

<|endoftext|>


<commit_before>
#include <iostream>
#include <fstream>
#include <sstream>

#include "allocore/ui/al_Parameter.hpp"
#include "allocore/io/al_File.hpp"

using namespace al;

// Parameter ------------------------------------------------------------------
Parameter::Parameter(std::string parameterName, std::string Group,
                     float defaultValue,
                     std::string prefix,
                     float min,
                     float max) :
    ParameterWrapper<float>(parameterName, Group, defaultValue, prefix, min, max)
{
	mFloatValue = defaultValue;
}

float Parameter::get()
{
	return mFloatValue;
}

void Parameter::setNoCalls(float value)
{
	if (value > mMax) value = mMax;
	if (value < mMin) value = mMin;
	if (mProcessCallback) {
		value = mProcessCallback(value, mProcessUdata);
	}

	mFloatValue = value;
}

void Parameter::set(float value)
{
	if (value > mMax) value = mMax;
	if (value < mMin) value = mMin;
	if (mProcessCallback) {
		value = mProcessCallback(value, mProcessUdata);
	}
	mFloatValue = value;
	for(int i = 0; i < mCallbacks.size(); ++i) {
		if (mCallbacks[i]) {
			mCallbacks[i](value, this, mCallbackUdata[i]);
		}
	}
}

// ParameterServer ------------------------------------------------------------

ParameterServer::ParameterServer(std::string oscAddress, int oscPort)
    : mServer(nullptr)
{
	mServer = new osc::Recv(oscPort, oscAddress.c_str());
	if (mServer) {
		mServer->handler(*this);
		mServer->start();
	} else {
		std::cout << "Error starting OSC server." << std::endl;
	}
}

ParameterServer::~ParameterServer()
{
	if (mServer) {
		mServer->stop();
		delete mServer;
	}
}

ParameterServer &ParameterServer::registerParameter(Parameter &param)
{
	mParameterLock.lock();
	mParameters.push_back(&param);
	mParameterLock.unlock();
	mListenerLock.lock();
	param.registerChangeCallback(ParameterServer::changeCallback,
	                           (void *) this);
	mListenerLock.unlock();
	return *this;
}

void ParameterServer::unregisterParameter(Parameter &param)
{
	mParameterLock.lock();
	std::vector<Parameter *>::iterator it = mParameters.begin();
	for(it = mParameters.begin(); it != mParameters.end(); it++) {
		if (*it == &param) {
			mParameters.erase(it);
		}
	}
	mParameterLock.unlock();
}

void ParameterServer::onMessage(osc::Message &m)
{
	std::string requestAddress = "/request";
	if(m.addressPattern() == requestAddress && m.typeTags() == "s") {
		std::string parameterAddress;
		m >> parameterAddress;
	}
	float val;
	m >> val;
	mParameterLock.lock();
	for (Parameter *p:mParameters) {
		if(m.addressPattern() == p->getFullAddress() && m.typeTags() == "f"){
			// Extract the data out of the packet
			p->set(val);
//			std::cout << "ParameterServer::onMessage" << val << std::endl;
		}
	}
	mParameterLock.unlock();
}

void ParameterServer::print()
{
	std::cout << "Parameter server listening on " << mServer->address()
	          << ":" << mServer->port() << std::endl;
	for (Parameter *p:mParameters) {
		std::cout << "Parameter " << p->getName() << " : " <<  p->getFullAddress() << std::endl;
	}
}

void ParameterServer::changeCallback(float value, void *sender, void *userData)
{
	ParameterServer *server = static_cast<ParameterServer *>(userData);
	Parameter *parameter = static_cast<Parameter *>(sender);
	server->notifyListeners(parameter->getFullAddress(), parameter->get());
}

<commit_msg>Set small timeout for Parameter OSC socket (as it runs asyncrhonously)<commit_after>
#include <iostream>
#include <fstream>
#include <sstream>

#include "allocore/ui/al_Parameter.hpp"
#include "allocore/io/al_File.hpp"

using namespace al;

// Parameter ------------------------------------------------------------------
Parameter::Parameter(std::string parameterName, std::string Group,
                     float defaultValue,
                     std::string prefix,
                     float min,
                     float max) :
    ParameterWrapper<float>(parameterName, Group, defaultValue, prefix, min, max)
{
	mFloatValue = defaultValue;
}

float Parameter::get()
{
	return mFloatValue;
}

void Parameter::setNoCalls(float value)
{
	if (value > mMax) value = mMax;
	if (value < mMin) value = mMin;
	if (mProcessCallback) {
		value = mProcessCallback(value, mProcessUdata);
	}

	mFloatValue = value;
}

void Parameter::set(float value)
{
	if (value > mMax) value = mMax;
	if (value < mMin) value = mMin;
	if (mProcessCallback) {
		value = mProcessCallback(value, mProcessUdata);
	}
	mFloatValue = value;
	for(int i = 0; i < mCallbacks.size(); ++i) {
		if (mCallbacks[i]) {
			mCallbacks[i](value, this, mCallbackUdata[i]);
		}
	}
}

// ParameterServer ------------------------------------------------------------

ParameterServer::ParameterServer(std::string oscAddress, int oscPort)
    : mServer(nullptr)
{
	mServer = new osc::Recv(oscPort, oscAddress.c_str(), 0.001); // Is 1ms wait OK?
	if (mServer) {
		mServer->handler(*this);
		mServer->start();
	} else {
		std::cout << "Error starting OSC server." << std::endl;
	}
}

ParameterServer::~ParameterServer()
{
	if (mServer) {
		mServer->stop();
		delete mServer;
	}
}

ParameterServer &ParameterServer::registerParameter(Parameter &param)
{
	mParameterLock.lock();
	mParameters.push_back(&param);
	mParameterLock.unlock();
	mListenerLock.lock();
	param.registerChangeCallback(ParameterServer::changeCallback,
	                           (void *) this);
	mListenerLock.unlock();
	return *this;
}

void ParameterServer::unregisterParameter(Parameter &param)
{
	mParameterLock.lock();
	std::vector<Parameter *>::iterator it = mParameters.begin();
	for(it = mParameters.begin(); it != mParameters.end(); it++) {
		if (*it == &param) {
			mParameters.erase(it);
		}
	}
	mParameterLock.unlock();
}

void ParameterServer::onMessage(osc::Message &m)
{
	std::string requestAddress = "/request";
	if(m.addressPattern() == requestAddress && m.typeTags() == "s") {
		std::string parameterAddress;
		m >> parameterAddress;
	}
	float val;
	m >> val;
	mParameterLock.lock();
	for (Parameter *p:mParameters) {
		if(m.addressPattern() == p->getFullAddress() && m.typeTags() == "f"){
			// Extract the data out of the packet
			p->set(val);
//			std::cout << "ParameterServer::onMessage" << val << std::endl;
		}
	}
	mParameterLock.unlock();
}

void ParameterServer::print()
{
	std::cout << "Parameter server listening on " << mServer->address()
	          << ":" << mServer->port() << std::endl;
	for (Parameter *p:mParameters) {
		std::cout << "Parameter " << p->getName() << " : " <<  p->getFullAddress() << std::endl;
	}
}

void ParameterServer::changeCallback(float value, void *sender, void *userData)
{
	ParameterServer *server = static_cast<ParameterServer *>(userData);
	Parameter *parameter = static_cast<Parameter *>(sender);
	server->notifyListeners(parameter->getFullAddress(), parameter->get());
}

<|endoftext|>


<commit_before>/// This Source Code Form is subject to the terms of the Mozilla Public
/// License, v. 2.0. If a copy of the MPL was not distributed with this
/// file, You can obtain one at http://mozilla.org/MPL/2.0/.

/// @Author Aart Stuurman

/// Class summary
/* template<u32 dimension, typename ValueType>
 * class Dynarray;
 *
 * Constructor(u32 size_x, u32 size_y, u32 size_z, ...)
 *     Construct the object with given sizes for each dimension.
 *
 * void Dimension()
 *     Get the dimension of the array.
 *     Equal to the template parameter.
 *
 * template<u32 dim>
 * u32 Size()
 *     Get the size in the given dimension.
 *     Equal to the argument provided in the constructor.
 *
 * ValueType& At(u32 x, u32 y, u32 z, ...)
 *     Access the dynarray element at the position of choice.*/

#ifndef ASTUURMAN_DYNARRAY_HPP
#define ASTUURMAN_DYNARRAY_HPP

#include <tuple>

// If you are using a C++14 compiler you can exchange this for the std index sequence.
#include "IntegerSequence.hpp"

namespace Astuurman {

    /// Define as you like.
    // 32 bit unsigned integer
    using u32 = unsigned long;
    // 64 bit unsigned integer
    using u64 = unsigned long long;

    /// If you have a C++14 compiler you can use the std index sequence instead.
    template<size_t... T>
    using indseq = index_sequence<T...>;
    template <std::size_t V>
    using make_indseq = make_index_sequence<V>;

    template<u32 dimension, typename ValueType, typename = make_indseq<dimension>>
    class Dynarray;

    template <u32 dimension, typename ValueType, std::size_t... Is>
    class Dynarray<dimension, ValueType, indseq<Is...>>
    {
        template<typename To, typename>
        using to = To;

        ValueType* value;
        std::tuple<to<u32, decltype(Is)>...> size;

        template<typename Head>
        u64 Multiply(Head head)
        {
            return head;
        }

        template<typename Head, typename... Tail>
        u64 Multiply(Head head, Tail... tail)
        {
            return head * Multiply(tail...);
        }

        template<u32 index, typename Head>
        u64 IndexOffset(Head head)
        {
            return 1;
        }

        template<u32 index, typename Head, typename... Tail>
        u64 IndexOffset(Head head, Tail... tail)
        {
            return std::get<index + 1>(size) * IndexOffset<index + 1, Tail...>(tail...);
        }

        template<u32 dimIndex, typename Head>
        u64 Index(Head head)
        {
            return head * IndexOffset<dimIndex, Head>(head);
        }

        template<u32 dimIndex = 0, typename Head, typename... Tail>
        u64 Index(Head head, Tail... tail)
        {
            return head * IndexOffset<dimIndex, Head, Tail...>(head, tail...) + Index<dimIndex + 1, Tail...>(tail...);
        }
    public:
        Dynarray(decltype(Is, u32{})... sizes)
        {
            value = new ValueType[Multiply(sizes...)]();
            size = std::make_tuple(sizes...);
        }

        ~Dynarray()
        {
            delete[] value;
        }

        constexpr u32 Dimension()
        {
            return dimension;
        }

        ValueType& At(to<u32, decltype(Is)>... indexes)
        {
            return value[Index(indexes...)];
        }

        template<u32 dim>
        u32 Size() const
        {
            return std::get<dim>(size);
        }
    };
}

#endif // ASTUURMAN_DYNARRAY_HPP
<commit_msg>Fixed issue where 1 dimensional array could not be indexed.<commit_after>/// This Source Code Form is subject to the terms of the Mozilla Public
/// License, v. 2.0. If a copy of the MPL was not distributed with this
/// file, You can obtain one at http://mozilla.org/MPL/2.0/.

/// @Author Aart Stuurman

/// Class summary
/* template<u32 dimension, typename ValueType>
 * class Dynarray;
 *
 * Constructor(u32 size_x, u32 size_y, u32 size_z, ...)
 *     Construct the object with given sizes for each dimension.
 *
 * void Dimension()
 *     Get the dimension of the array.
 *     Equal to the template parameter.
 *
 * template<u32 dim>
 * u32 Size()
 *     Get the size in the given dimension.
 *     Equal to the argument provided in the constructor.
 *
 * ValueType& At(u32 x, u32 y, u32 z, ...)
 *     Access the dynarray element at the position of choice.*/

#ifndef ASTUURMAN_DYNARRAY_HPP
#define ASTUURMAN_DYNARRAY_HPP

#include <tuple>

// If you are using a C++14 compiler you can exchange this for the std index sequence.
#include "IntegerSequence.hpp"

namespace Astuurman {

    /// Define as you like.
    // 32 bit unsigned integer
    using u32 = unsigned long;
    // 64 bit unsigned integer
    using u64 = unsigned long long;

    /// If you have a C++14 compiler you can use the std index sequence instead.
    template<size_t... T>
    using indseq = index_sequence<T...>;
    template <std::size_t V>
    using make_indseq = make_index_sequence<V>;

    template<u32 dimension, typename ValueType, typename = make_indseq<dimension>>
    class Dynarray;

    template <u32 dimension, typename ValueType, std::size_t... Is>
    class Dynarray<dimension, ValueType, indseq<Is...>>
    {
        template<typename To, typename>
        using to = To;

        ValueType* value;
        std::tuple<to<u32, decltype(Is)>...> size;

        template<typename Head>
        u64 Multiply(Head head)
        {
            return head;
        }

        template<typename Head, typename... Tail>
        u64 Multiply(Head head, Tail... tail)
        {
            return head * Multiply(tail...);
        }

        template<u32 index, typename Head>
        u64 IndexOffset(Head head)
        {
            return 1;
        }

        template<u32 index, typename Head, typename... Tail>
        u64 IndexOffset(Head head, Tail... tail)
        {
            return std::get<index + 1>(size) * IndexOffset<index + 1, Tail...>(tail...);
        }

        template<u32 dimIndex>
        u64 Index()
        {
            return 0;
        }

        template<u32 dimIndex = 0, typename Head, typename... Tail>
        u64 Index(Head head, Tail... tail)
        {
            return head * IndexOffset<dimIndex, Head, Tail...>(head, tail...) + Index<dimIndex + 1, Tail...>(tail...);
        }
    public:
        Dynarray(decltype(Is, u32{})... sizes)
        {
            value = new ValueType[Multiply(sizes...)]();
            size = std::make_tuple(sizes...);
        }

        ~Dynarray()
        {
            delete[] value;
        }

        constexpr u32 Dimension()
        {
            return dimension;
        }

        ValueType& At(to<u32, decltype(Is)>... indexes)
        {
            return value[Index(indexes...)];
        }

        template<u32 dim>
        u32 Size() const
        {
            return std::get<dim>(size);
        }
    };
}

#endif // ASTUURMAN_DYNARRAY_HPP
<|endoftext|>


<commit_before><commit_msg>warning C4805: unsafe mix of type bool and sal_Bool<commit_after><|endoftext|>


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

#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#ifndef _SBX_SBXOBJECT_HXX //autogen
#include <sbxobj.hxx>
#endif
#ifndef _SBXCLASS_HXX //autogen
#include <sbx.hxx>
#endif
#ifndef __SBX_SBXVARIABLE_HXX //autogen
#include <sbxvar.hxx>
#endif

//#include <osl/thread.h>
#ifndef _BASIC_TTRESHLP_HXX
#include "ttstrhlp.hxx"
#endif

#include "processw.hxx"

//#include "collelem.hxx"
// Makro MEMBER()
#include "macfix.hxx"

// Der Process hat folgende Elemente:
// 1) Properties:
//    Keine
// 2) Methoden:
//    SetImage( Filename )
//    BOOL Start
//    USHORT GetExitCode
//    BOOL IsRunning
//    BOOL WasGPF

// Diese Implementation ist ein Beispiel fuer eine tabellengesteuerte
// Version, die sehr viele Elemente enthalten kann. Die Elemente werden
// je nach Bedarf aus der Tabelle in das Objekt uebernommen.

// Das nArgs-Feld eines Tabelleneintrags ist wie folgt verschluesselt:

#define _ARGSMASK   0x00FF  // Bis zu 255 Argumente
#define _RWMASK     0x0F00  // Maske fuer R/W-Bits
#define _TYPEMASK   0xF000  // Maske fuer den Typ des Eintrags

#define _READ       0x0100  // kann gelesen werden
#define _BWRITE     0x0200  // kann as Lvalue verwendet werden
#define _LVALUE     _BWRITE  // kann as Lvalue verwendet werden
#define _READWRITE  0x0300  // beides
#define _OPT        0x0400  // TRUE: optionaler Parameter
#define _METHOD     0x1000  // Masken-Bit fuer eine Methode
#define _PROPERTY   0x2000  // Masken-Bit fuer eine Property
#define _COLL       0x4000  // Masken-Bit fuer eine Collection
                            // Kombination von oberen Bits:
#define _FUNCTION   0x1100  // Maske fuer Function
#define _LFUNCTION  0x1300  // Maske fuer Function, die auch als Lvalue geht
#define _ROPROP     0x2100  // Maske Read Only-Property
#define _WOPROP     0x2200  // Maske Write Only-Property
#define _RWPROP     0x2300  // Maske Read/Write-Property
#define _COLLPROP   0x4100  // Maske Read-Collection-Element

#define COLLNAME    "Elements"  // Name der Collection, hier mal hart verdrahtet

ProcessWrapper::Methods ProcessWrapper::aProcessMethods[] = {
// Imagedatei des Executables
{ "SetImage",                       SbxEMPTY,  1 | _FUNCTION, MEMBER(ProcessWrapper::PSetImage) },
    // Zwei Named Parameter
    { "Filename",SbxSTRING },
    { "Params",SbxSTRING, _OPT },
// Programm wird gestartet
{ "Start",                          SbxBOOL,   0 | _FUNCTION, MEMBER(ProcessWrapper::PStart) },
// ExitCode des Programms(nachdem es beendet ist)
{ "GetExitCode",                    SbxULONG,  0 | _FUNCTION, MEMBER(ProcessWrapper::PGetExitCode) },
// Programm luft noch
{ "IsRunning",                      SbxBOOL,   0 | _FUNCTION, MEMBER(ProcessWrapper::PIsRunning) },
// Programm mit GPF o.. abgebrochen
{ "WasGPF",                         SbxBOOL,   0 | _FUNCTION, MEMBER(ProcessWrapper::PWasGPF) },

{ NULL,     SbxNULL,            -1 }};  // Tabellenende

// Konstruktor fr den Process
ProcessWrapper::ProcessWrapper() : SbxObject( CUniString("Process") )
{
    pProcess = new Process();
    SetName( CUniString("Process") );
    pMethods = &aProcessMethods[0];
}

// Destruktor
ProcessWrapper::~ProcessWrapper()
{
    delete pProcess;
}

// Suche nach einem Element:
// Hier wird linear durch die Methodentabelle gegangen, bis eine
// passende Methode gefunden wurde.
// Wenn die Methode/Property nicht gefunden wurde, nur NULL ohne
// Fehlercode zurueckliefern, da so auch eine ganze Chain von
// Objekten nach der Methode/Property befragt werden kann.

SbxVariable* ProcessWrapper::Find( const String& rName, SbxClassType t )
{
    // Ist das Element bereits vorhanden?
    SbxVariable* pRes = SbxObject::Find( rName, t );
    if( !pRes && t != SbxCLASS_OBJECT )
    {
        // sonst suchen
        Methods* p = pMethods;
        short nIndex = 0;
        BOOL bFound = FALSE;
        while( p->nArgs != -1 )
        {
            if( rName.CompareIgnoreCaseToAscii( p->pName ) == COMPARE_EQUAL )
            {
                bFound = TRUE; break;
            }
            nIndex += ( p->nArgs & _ARGSMASK ) + 1;
            p = pMethods + nIndex;
        }
        if( bFound )
        {
            // Args-Felder isolieren:
            short nAccess = ( p->nArgs & _RWMASK ) >> 8;
            short nType   = ( p->nArgs & _TYPEMASK );
            String aName( p->pName, RTL_TEXTENCODING_ASCII_US );
            SbxClassType eCT = SbxCLASS_OBJECT;
            if( nType & _PROPERTY )
                eCT = SbxCLASS_PROPERTY;
            else if( nType & _METHOD )
                eCT = SbxCLASS_METHOD;
            pRes = Make( aName, eCT, p->eType );
            // Wir setzen den Array-Index + 1, da ja noch andere
            // Standard-Properties existieren, die auch aktiviert
            // werden muessen.
            pRes->SetUserData( nIndex + 1 );
            pRes->SetFlags( nAccess );
        }
    }
    return pRes;
}

// Aktivierung eines Elements oder Anfordern eines Infoblocks

void ProcessWrapper::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCT,
                             const SfxHint& rHint, const TypeId& rHT )
{
    const SbxHint* pHint = PTR_CAST(SbxHint,&rHint);
    if( pHint )
    {
        SbxVariable* pVar = pHint->GetVar();
        SbxArray* pPar = pVar->GetParameters();
        USHORT nIndex = (USHORT) pVar->GetUserData();
        // kein Index: weiterreichen!
        if( nIndex )
        {
            ULONG t = pHint->GetId();
            if( t == SBX_HINT_INFOWANTED )
                pVar->SetInfo( GetInfo( (short) pVar->GetUserData() ) );
            else
            {
                BOOL bWrite = FALSE;
                if( t == SBX_HINT_DATACHANGED )
                    bWrite = TRUE;
                if( t == SBX_HINT_DATAWANTED || bWrite )
                {
                    // Parameter-Test fuer Methoden:
                    USHORT nPar = pMethods[ --nIndex ].nArgs & 0x00FF;
                    // Element 0 ist der Returnwert
                    if( ( !pPar && nPar )
                     || ( pPar && pPar->Count() < nPar+1 ) )
                        SetError( SbxERR_WRONG_ARGS );
                    // Alles klar, man kann den Call ausfuehren
                    else
                    {
                        (this->*(pMethods[ nIndex ].pFunc))( pVar, pPar, bWrite );
                    }
                }
            }
        }
        SbxObject::SFX_NOTIFY( rBC, rBCT, rHint, rHT );
    }
}

// Zusammenbau der Infostruktur fuer einzelne Elemente

SbxInfo* ProcessWrapper::GetInfo( short nIdx )
{
    Methods* p = &pMethods[ nIdx ];
    // Wenn mal eine Hilfedatei zur Verfuegung steht:
    // SbxInfo* pInfo = new SbxInfo( Hilfedateiname, p->nHelpId );
    SbxInfo* pInfo = new SbxInfo;
    short nPar = p->nArgs & _ARGSMASK;
    for( short i = 0; i < nPar; i++ )
    {
        p++;
        String aName( p->pName, RTL_TEXTENCODING_ASCII_US );
        USHORT nFlags = ( p->nArgs >> 8 ) & 0x03;
        if( p->nArgs & _OPT )
            nFlags |= SBX_OPTIONAL;
        pInfo->AddParam( aName, p->eType, nFlags );
    }
    return pInfo;
}

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

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

// Properties und Methoden legen beim Get (bPut = FALSE) den Returnwert
// im Element 0 des Argv ab; beim Put (bPut = TRUE) wird der Wert aus
// Element 0 gespeichert.

// Die Methoden:
void ProcessWrapper::PSetImage( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite )
{ // Imagedatei des Executables
    if ( pPar->Count() >= 2 )
        pProcess->SetImage(pPar->Get( 1 )->GetString(), pPar->Get( 2 )->GetString() );
    else
        pProcess->SetImage(pPar->Get( 1 )->GetString(), String() );
}

void ProcessWrapper::PStart( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite )
{ // Programm wird gestartet
    pVar->PutBool( pProcess->Start() );
}

void ProcessWrapper::PGetExitCode( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite )
{ // ExitCode des Programms(nachdem es beendet ist)
    pVar->PutULong( pProcess->GetExitCode() );
}

void ProcessWrapper::PIsRunning( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite )
{ // Programm luft noch
    pVar->PutBool( pProcess->IsRunning() );
}

void ProcessWrapper::PWasGPF( SbxVariable* pVar, SbxArray* pPar, BOOL bWrite )
{ // Programm mit GPF o.. abgebrochen
    pVar->PutBool( pProcess->WasGPF() );
}

// Die Factory legt unser Objekte an.

SbxObject* ProcessFactory::CreateObject( const String& rClass )
{
    if( rClass.CompareIgnoreCaseToAscii( "Process" ) == COMPARE_EQUAL )
        return new ProcessWrapper();
    return NULL;
}

<commit_msg>INTEGRATION: CWS warnings01 (1.3.28); FILE MERGED 2005/11/18 09:57:04 gh 1.3.28.1: linux warnings (some more)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: processw.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 17:37:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#ifndef _SBX_SBXOBJECT_HXX //autogen
#include <sbxobj.hxx>
#endif
#ifndef _SBXCLASS_HXX //autogen
#include <sbx.hxx>
#endif
#ifndef __SBX_SBXVARIABLE_HXX //autogen
#include <sbxvar.hxx>
#endif

//#include <osl/thread.h>
#ifndef _BASIC_TTRESHLP_HXX
#include "ttstrhlp.hxx"
#endif

#include "processw.hxx"

//#include "collelem.hxx"
// Makro MEMBER()
#include "macfix.hxx"

// Der Process hat folgende Elemente:
// 1) Properties:
//    Keine
// 2) Methoden:
//    SetImage( Filename )
//    BOOL Start
//    USHORT GetExitCode
//    BOOL IsRunning
//    BOOL WasGPF

// Diese Implementation ist ein Beispiel fuer eine tabellengesteuerte
// Version, die sehr viele Elemente enthalten kann. Die Elemente werden
// je nach Bedarf aus der Tabelle in das Objekt uebernommen.

// Das nArgs-Feld eines Tabelleneintrags ist wie folgt verschluesselt:

#define _ARGSMASK   0x00FF  // Bis zu 255 Argumente
#define _RWMASK     0x0F00  // Maske fuer R/W-Bits
#define _TYPEMASK   0xF000  // Maske fuer den Typ des Eintrags

#define _READ       0x0100  // kann gelesen werden
#define _BWRITE     0x0200  // kann as Lvalue verwendet werden
#define _LVALUE     _BWRITE  // kann as Lvalue verwendet werden
#define _READWRITE  0x0300  // beides
#define _OPT        0x0400  // TRUE: optionaler Parameter
#define _METHOD     0x1000  // Masken-Bit fuer eine Methode
#define _PROPERTY   0x2000  // Masken-Bit fuer eine Property
#define _COLL       0x4000  // Masken-Bit fuer eine Collection
                            // Kombination von oberen Bits:
#define _FUNCTION   0x1100  // Maske fuer Function
#define _LFUNCTION  0x1300  // Maske fuer Function, die auch als Lvalue geht
#define _ROPROP     0x2100  // Maske Read Only-Property
#define _WOPROP     0x2200  // Maske Write Only-Property
#define _RWPROP     0x2300  // Maske Read/Write-Property
#define _COLLPROP   0x4100  // Maske Read-Collection-Element

#define COLLNAME    "Elements"  // Name der Collection, hier mal hart verdrahtet

ProcessWrapper::Methods ProcessWrapper::aProcessMethods[] = {
// Imagedatei des Executables
{ "SetImage",                       SbxEMPTY,  1 | _FUNCTION, MEMBER(ProcessWrapper::PSetImage) },
    // Zwei Named Parameter
    { "Filename",SbxSTRING, 0 , NULL },
    { "Params",SbxSTRING, _OPT , NULL },
// Programm wird gestartet
{ "Start",                          SbxBOOL,   0 | _FUNCTION, MEMBER(ProcessWrapper::PStart) },
// ExitCode des Programms(nachdem es beendet ist)
{ "GetExitCode",                    SbxULONG,  0 | _FUNCTION, MEMBER(ProcessWrapper::PGetExitCode) },
// Programm luft noch
{ "IsRunning",                      SbxBOOL,   0 | _FUNCTION, MEMBER(ProcessWrapper::PIsRunning) },
// Programm mit GPF o.. abgebrochen
{ "WasGPF",                         SbxBOOL,   0 | _FUNCTION, MEMBER(ProcessWrapper::PWasGPF) },

{ NULL,     SbxNULL,            -1, NULL }};  // Tabellenende

// Konstruktor fr den Process
ProcessWrapper::ProcessWrapper() : SbxObject( CUniString("Process") )
{
    pProcess = new Process();
    SetName( CUniString("Process") );
    pMethods = &aProcessMethods[0];
}

// Destruktor
ProcessWrapper::~ProcessWrapper()
{
    delete pProcess;
}

// Suche nach einem Element:
// Hier wird linear durch die Methodentabelle gegangen, bis eine
// passende Methode gefunden wurde.
// Wenn die Methode/Property nicht gefunden wurde, nur NULL ohne
// Fehlercode zurueckliefern, da so auch eine ganze Chain von
// Objekten nach der Methode/Property befragt werden kann.

SbxVariable* ProcessWrapper::Find( const String& rName, SbxClassType t )
{
    // Ist das Element bereits vorhanden?
    SbxVariable* pRes = SbxObject::Find( rName, t );
    if( !pRes && t != SbxCLASS_OBJECT )
    {
        // sonst suchen
        Methods* p = pMethods;
        short nIndex = 0;
        BOOL bFound = FALSE;
        while( p->nArgs != -1 )
        {
            if( rName.EqualsIgnoreCaseAscii( p->pName ) )
            {
                bFound = TRUE; break;
            }
            nIndex += ( p->nArgs & _ARGSMASK ) + 1;
            p = pMethods + nIndex;
        }
        if( bFound )
        {
            // Args-Felder isolieren:
            short nAccess = ( p->nArgs & _RWMASK ) >> 8;
            short nType   = ( p->nArgs & _TYPEMASK );
            String aMethodName( p->pName, RTL_TEXTENCODING_ASCII_US );
            SbxClassType eCT = SbxCLASS_OBJECT;
            if( nType & _PROPERTY )
                eCT = SbxCLASS_PROPERTY;
            else if( nType & _METHOD )
                eCT = SbxCLASS_METHOD;
            pRes = Make( aMethodName, eCT, p->eType );
            // Wir setzen den Array-Index + 1, da ja noch andere
            // Standard-Properties existieren, die auch aktiviert
            // werden muessen.
            pRes->SetUserData( nIndex + 1 );
            pRes->SetFlags( nAccess );
        }
    }
    return pRes;
}

// Aktivierung eines Elements oder Anfordern eines Infoblocks

void ProcessWrapper::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCT,
                             const SfxHint& rHint, const TypeId& rHT )
{
    const SbxHint* pHint = PTR_CAST(SbxHint,&rHint);
    if( pHint )
    {
        SbxVariable* pVar = pHint->GetVar();
        SbxArray* pNotifyPar = pVar->GetParameters();
        USHORT nIndex = (USHORT) pVar->GetUserData();
        // kein Index: weiterreichen!
        if( nIndex )
        {
            ULONG t = pHint->GetId();
            if( t == SBX_HINT_INFOWANTED )
                pVar->SetInfo( GetInfo( (short) pVar->GetUserData() ) );
            else
            {
                BOOL bWrite = FALSE;
                if( t == SBX_HINT_DATACHANGED )
                    bWrite = TRUE;
                if( t == SBX_HINT_DATAWANTED || bWrite )
                {
                    // Parameter-Test fuer Methoden:
                    USHORT nPar = pMethods[ --nIndex ].nArgs & 0x00FF;
                    // Element 0 ist der Returnwert
                    if( ( !pNotifyPar && nPar )
                     || ( pNotifyPar && pNotifyPar->Count() < nPar+1 ) )
                        SetError( SbxERR_WRONG_ARGS );
                    // Alles klar, man kann den Call ausfuehren
                    else
                    {
                        (this->*(pMethods[ nIndex ].pFunc))( pVar, pNotifyPar, bWrite );
                    }
                }
            }
        }
        SbxObject::SFX_NOTIFY( rBC, rBCT, rHint, rHT );
    }
}

// Zusammenbau der Infostruktur fuer einzelne Elemente

SbxInfo* ProcessWrapper::GetInfo( short nIdx )
{
    Methods* p = &pMethods[ nIdx ];
    // Wenn mal eine Hilfedatei zur Verfuegung steht:
    // SbxInfo* pResultInfo = new SbxInfo( Hilfedateiname, p->nHelpId );
    SbxInfo* pResultInfo = new SbxInfo;
    short nPar = p->nArgs & _ARGSMASK;
    for( short i = 0; i < nPar; i++ )
    {
        p++;
        String aMethodName( p->pName, RTL_TEXTENCODING_ASCII_US );
        USHORT nInfoFlags = ( p->nArgs >> 8 ) & 0x03;
        if( p->nArgs & _OPT )
            nInfoFlags |= SBX_OPTIONAL;
        pResultInfo->AddParam( aMethodName, p->eType, nInfoFlags );
    }
    return pResultInfo;
}

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

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

// Properties und Methoden legen beim Get (bPut = FALSE) den Returnwert
// im Element 0 des Argv ab; beim Put (bPut = TRUE) wird der Wert aus
// Element 0 gespeichert.

// Die Methoden:
void ProcessWrapper::PSetImage( SbxVariable* pVar, SbxArray* pMethodePar, BOOL bWriteIt )
{ // Imagedatei des Executables
    (void) pVar; /* avoid warning about unused parameter */
    (void) bWriteIt; /* avoid warning about unused parameter */
    if ( pMethodePar->Count() >= 2 )
        pProcess->SetImage(pMethodePar->Get( 1 )->GetString(), pMethodePar->Get( 2 )->GetString() );
    else
        pProcess->SetImage(pMethodePar->Get( 1 )->GetString(), String() );
}

void ProcessWrapper::PStart( SbxVariable* pVar, SbxArray* pMethodePar, BOOL bWriteIt )
{ // Programm wird gestartet
    (void) pMethodePar; /* avoid warning about unused parameter */
    (void) bWriteIt; /* avoid warning about unused parameter */
    pVar->PutBool( pProcess->Start() );
}

void ProcessWrapper::PGetExitCode( SbxVariable* pVar, SbxArray* pMethodePar, BOOL bWriteIt )
{ // ExitCode des Programms(nachdem es beendet ist)
    (void) pMethodePar; /* avoid warning about unused parameter */
    (void) bWriteIt; /* avoid warning about unused parameter */
    pVar->PutULong( pProcess->GetExitCode() );
}

void ProcessWrapper::PIsRunning( SbxVariable* pVar, SbxArray* pMethodePar, BOOL bWriteIt )
{ // Programm luft noch
    (void) pMethodePar; /* avoid warning about unused parameter */
    (void) bWriteIt; /* avoid warning about unused parameter */
    pVar->PutBool( pProcess->IsRunning() );
}

void ProcessWrapper::PWasGPF( SbxVariable* pVar, SbxArray* pMethodePar, BOOL bWriteIt )
{ // Programm mit GPF o.. abgebrochen
    (void) pMethodePar; /* avoid warning about unused parameter */
    (void) bWriteIt; /* avoid warning about unused parameter */
    pVar->PutBool( pProcess->WasGPF() );
}

// Die Factory legt unser Objekte an.

SbxObject* ProcessFactory::CreateObject( const String& rClass )
{
    if( rClass.CompareIgnoreCaseToAscii( "Process" ) == COMPARE_EQUAL )
        return new ProcessWrapper();
    return NULL;
}

<|endoftext|>


<commit_before>// transcode.cpp
//
// Warning!  Contains ifdef hackery
//
///////////////////////////////////

#ifdef _MSC_VER
#pragma warning(disable: 4244)
#endif

#include <iostream>
#include <Utils/convert_adaptor.h>
#include <Utils/utf8iso88591codecvt.h>
#include <Utils/iso88591utf8codecvt.h>
#include <Utils/rot13codecvt.h>
#include <Utils/base64codecvt.h>
#include <Utils/utf8ucs2codecvt.h>
#include <Utils/utf16utf8codecvt.h>
#include <Utils/utf16beucs2codecvt.h>
#include <Utils/utf16leucs2codecvt.h>

#include <fstream>
std::ifstream inputFile;
std::ofstream outputFile;

using namespace Arabica::convert;
iconvert_adaptor<char> iByteConvertor(std::cin);
oconvert_adaptor<char> oByteConvertor(std::cout);
bool needWCharIntermediary = false;

#ifndef ARABICA_NO_WCHAR_T
typedef iconvert_adaptor<wchar_t, std::char_traits<wchar_t>, char, std::char_traits<char> > Widener;
typedef oconvert_adaptor<wchar_t, std::char_traits<wchar_t>, char, std::char_traits<char> > Narrower;

Widener iCharAdaptor(iByteConvertor);
Narrower oCharAdaptor(oByteConvertor);
#endif

void wchar_transcode();
void byte_transcode();
bool processArgs(int argc, const char* argv[]);
bool imbueInput(int& argn, int argc, const char* argv[]);
bool imbueOutput(int& argn, int argc, const char* argv[]);

int main(int argc, const char* argv[])
{
  if(!processArgs(argc, argv))
  {
    std::cerr << argv[0] << "\n"
              << "  [(-ie|--input-encoding) input-encoding]\n"
              << "  [(-oe|--output-encoding) output-encoding]\n"
              << "  [(-i|--input) input-filename]\n"
              << "  [(-o|--output) output-filename]"
              << std::endl;
    return 0;
  }

  if(needWCharIntermediary)
    wchar_transcode();
  else
    byte_transcode();

  return 0;
} // main

void wchar_transcode()
{
#ifndef ARABICA_NO_WCHAR_T
  int count = 0;
  wchar_t c = iCharAdaptor.get();
  while(!iCharAdaptor.eof())
  {
    oCharAdaptor << c;

    if(count == 1024)
    {
      oCharAdaptor.flush();
      oByteConvertor.flush();
      count = 0;
    } // if ...

    c = iCharAdaptor.get();
  }
  oCharAdaptor.flush();
  oByteConvertor.flush();
#endif
} // wchar_transcode

void byte_transcode()
{
  int count = 0;
  char c = iByteConvertor.get();
  while(!iByteConvertor.eof())
  {
    oByteConvertor << c;

    if(count == 1024)
    {
      oByteConvertor.flush();
      count = 0;
    } // if ...

    c = iByteConvertor.get();
  } // while

  oByteConvertor.flush();
} // byte_transcode

bool processArgs(int argc, const char* argv[])
{
  for(int i = 1; i < argc; ++i)
  {
    std::string io(argv[i]);

    if(io == "-ie" || io == "--input-encoding")
    {
      if(!(imbueInput(i, argc, argv)))
        return false;
    }
    else if(io == "-oe" || io == "--output-encoding")
    {
      if(!(imbueOutput(i, argc, argv)))
        return false;
    }
    else if(io == "-i" || io == "--input")
    {
      ++i;
      if(i >= argc)
        return false;
      inputFile.open(argv[i], std::ios_base::in | std::ios_base::binary);
      iByteConvertor.set_stream(inputFile);
    }
    else if(io == "-o" || io == "--output")
    {
      ++i;
      if(i >= argc)
        return false;
      outputFile.open(argv[i], std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);
      oByteConvertor.set_stream(outputFile);
    }
    else
      return false;
  }
  return true;
} // processArgs

template<class Facet>
std::locale addFacet(const std::locale& base, Facet* facet)
{
#ifndef ARABICA_VS6_WORKAROUND
  return std::locale(base, facet);
#else
  return std::locale(std::_Addfac(base, facet));
#endif
} // addFacet

bool imbueInput(int& argn, int argc, const char* argv[])
{
  ++argn;
  if(argn >= argc)
    return false;

  std::string cvt(argv[argn]);

  if(cvt == "rot13")
    iByteConvertor.imbue(addFacet(iByteConvertor.getloc(), new rot13codecvt()));
  else if(cvt == "base64")
    iByteConvertor.imbue(addFacet(iByteConvertor.getloc(), new base64codecvt()));
#ifndef ARABICA_NO_WCHAR_T
  else if(cvt == "utf8")
    iCharAdaptor.imbue(addFacet(iCharAdaptor.getloc(), new utf8ucs2codecvt()));
  else if(cvt == "utf16be")
    iCharAdaptor.imbue(addFacet(iCharAdaptor.getloc(), new utf16beucs2codecvt()));
  else if(cvt == "utf16le")
    iCharAdaptor.imbue(addFacet(iCharAdaptor.getloc(), new utf16leucs2codecvt()));
#endif
  else
  {
    std::cerr << cvt << " is not a valid input encoding." << std::endl;
    return false;
  }

#ifndef ARABICA_NO_WCHAR_T
  if((cvt == "utf8") ||
      (cvt == "utf16be") ||
      (cvt == "utf16le"))
    needWCharIntermediary = true;
#endif

  return true;
} // imbueInput

bool imbueOutput(int& argn, int argc, const char* argv[])
{
  ++argn;
  if(argn >= argc)
    return false;

  std::string cvt(argv[argn]);
  if(cvt == "rot13")
    oByteConvertor.imbue(addFacet(oByteConvertor.getloc(), new rot13codecvt()));
  else if(cvt == "base64")
    oByteConvertor.imbue(addFacet(oByteConvertor.getloc(), new base64codecvt()));
#ifndef ARABICA_NO_WCHAR_T
  else if(cvt == "utf8")
    oCharAdaptor.imbue(addFacet(oCharAdaptor.getloc(), new utf8ucs2codecvt()));
  else if(cvt == "utf16be")
    oCharAdaptor.imbue(addFacet(oCharAdaptor.getloc(), new utf16beucs2codecvt()));
  else if(cvt == "utf16le")
    oCharAdaptor.imbue(addFacet(oCharAdaptor.getloc(), new utf16leucs2codecvt()));
#endif
  else
  {
    std::cerr << cvt << " is not a valid output encoding." << std::endl;
    return false;
  }

#ifndef ARABICA_NO_WCHAR_T
    if((cvt == "utf8") ||
       (cvt == "utf16be") ||
       (cvt == "utf16le"))
      needWCharIntermediary = true;
#endif

  return true;
} // imbueOutputs

<commit_msg>corrected VS warnings<commit_after>// transcode.cpp
//
// Warning!  Contains ifdef hackery
//
///////////////////////////////////

#ifdef _MSC_VER
#pragma warning(disable: 4244 4996)
#endif

#include <iostream>
#include <Utils/convert_adaptor.h>
#include <Utils/utf8iso88591codecvt.h>
#include <Utils/iso88591utf8codecvt.h>
#include <Utils/rot13codecvt.h>
#include <Utils/base64codecvt.h>
#include <Utils/utf8ucs2codecvt.h>
#include <Utils/utf16utf8codecvt.h>
#include <Utils/utf16beucs2codecvt.h>
#include <Utils/utf16leucs2codecvt.h>

#include <fstream>
std::ifstream inputFile;
std::ofstream outputFile;

using namespace Arabica::convert;
iconvert_adaptor<char> iByteConvertor(std::cin);
oconvert_adaptor<char> oByteConvertor(std::cout);
bool needWCharIntermediary = false;

#ifndef ARABICA_NO_WCHAR_T
typedef iconvert_adaptor<wchar_t, std::char_traits<wchar_t>, char, std::char_traits<char> > Widener;
typedef oconvert_adaptor<wchar_t, std::char_traits<wchar_t>, char, std::char_traits<char> > Narrower;

Widener iCharAdaptor(iByteConvertor);
Narrower oCharAdaptor(oByteConvertor);
#endif

void wchar_transcode();
void byte_transcode();
bool processArgs(int argc, const char* argv[]);
bool imbueInput(int& argn, int argc, const char* argv[]);
bool imbueOutput(int& argn, int argc, const char* argv[]);

int main(int argc, const char* argv[])
{
  if(!processArgs(argc, argv))
  {
    std::cerr << argv[0] << "\n"
              << "  [(-ie|--input-encoding) input-encoding]\n"
              << "  [(-oe|--output-encoding) output-encoding]\n"
              << "  [(-i|--input) input-filename]\n"
              << "  [(-o|--output) output-filename]"
              << std::endl;
    return 0;
  }

  if(needWCharIntermediary)
    wchar_transcode();
  else
    byte_transcode();

  return 0;
} // main

void wchar_transcode()
{
#ifndef ARABICA_NO_WCHAR_T
  int count = 0;
  wchar_t c = iCharAdaptor.get();
  while(!iCharAdaptor.eof())
  {
    oCharAdaptor << c;

    if(count == 1024)
    {
      oCharAdaptor.flush();
      oByteConvertor.flush();
      count = 0;
    } // if ...

    c = iCharAdaptor.get();
  }
  oCharAdaptor.flush();
  oByteConvertor.flush();
#endif
} // wchar_transcode

void byte_transcode()
{
  int count = 0;
  char c = iByteConvertor.get();
  while(!iByteConvertor.eof())
  {
    oByteConvertor << c;

    if(count == 1024)
    {
      oByteConvertor.flush();
      count = 0;
    } // if ...

    c = iByteConvertor.get();
  } // while

  oByteConvertor.flush();
} // byte_transcode

bool processArgs(int argc, const char* argv[])
{
  for(int i = 1; i < argc; ++i)
  {
    std::string io(argv[i]);

    if(io == "-ie" || io == "--input-encoding")
    {
      if(!(imbueInput(i, argc, argv)))
        return false;
    }
    else if(io == "-oe" || io == "--output-encoding")
    {
      if(!(imbueOutput(i, argc, argv)))
        return false;
    }
    else if(io == "-i" || io == "--input")
    {
      ++i;
      if(i >= argc)
        return false;
      inputFile.open(argv[i], std::ios_base::in | std::ios_base::binary);
      iByteConvertor.set_stream(inputFile);
    }
    else if(io == "-o" || io == "--output")
    {
      ++i;
      if(i >= argc)
        return false;
      outputFile.open(argv[i], std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);
      oByteConvertor.set_stream(outputFile);
    }
    else
      return false;
  }
  return true;
} // processArgs

template<class Facet>
std::locale addFacet(const std::locale& base, Facet* facet)
{
#ifndef ARABICA_VS6_WORKAROUND
  return std::locale(base, facet);
#else
  return std::locale(std::_Addfac(base, facet));
#endif
} // addFacet

bool imbueInput(int& argn, int argc, const char* argv[])
{
  ++argn;
  if(argn >= argc)
    return false;

  std::string cvt(argv[argn]);

  if(cvt == "rot13")
    iByteConvertor.imbue(addFacet(iByteConvertor.getloc(), new rot13codecvt()));
  else if(cvt == "base64")
    iByteConvertor.imbue(addFacet(iByteConvertor.getloc(), new base64codecvt()));
#ifndef ARABICA_NO_WCHAR_T
  else if(cvt == "utf8")
    iCharAdaptor.imbue(addFacet(iCharAdaptor.getloc(), new utf8ucs2codecvt()));
  else if(cvt == "utf16be")
    iCharAdaptor.imbue(addFacet(iCharAdaptor.getloc(), new utf16beucs2codecvt()));
  else if(cvt == "utf16le")
    iCharAdaptor.imbue(addFacet(iCharAdaptor.getloc(), new utf16leucs2codecvt()));
#endif
  else
  {
    std::cerr << cvt << " is not a valid input encoding." << std::endl;
    return false;
  }

#ifndef ARABICA_NO_WCHAR_T
  if((cvt == "utf8") ||
      (cvt == "utf16be") ||
      (cvt == "utf16le"))
    needWCharIntermediary = true;
#endif

  return true;
} // imbueInput

bool imbueOutput(int& argn, int argc, const char* argv[])
{
  ++argn;
  if(argn >= argc)
    return false;

  std::string cvt(argv[argn]);
  if(cvt == "rot13")
    oByteConvertor.imbue(addFacet(oByteConvertor.getloc(), new rot13codecvt()));
  else if(cvt == "base64")
    oByteConvertor.imbue(addFacet(oByteConvertor.getloc(), new base64codecvt()));
#ifndef ARABICA_NO_WCHAR_T
  else if(cvt == "utf8")
    oCharAdaptor.imbue(addFacet(oCharAdaptor.getloc(), new utf8ucs2codecvt()));
  else if(cvt == "utf16be")
    oCharAdaptor.imbue(addFacet(oCharAdaptor.getloc(), new utf16beucs2codecvt()));
  else if(cvt == "utf16le")
    oCharAdaptor.imbue(addFacet(oCharAdaptor.getloc(), new utf16leucs2codecvt()));
#endif
  else
  {
    std::cerr << cvt << " is not a valid output encoding." << std::endl;
    return false;
  }

#ifndef ARABICA_NO_WCHAR_T
    if((cvt == "utf8") ||
       (cvt == "utf16be") ||
       (cvt == "utf16le"))
      needWCharIntermediary = true;
#endif

  return true;
} // imbueOutputs

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004-2012  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/znc.h>

class CSendRaw_Mod: public CModule {
	void SendClient(const CString& sLine) {
		CUser *pUser = CZNC::Get().FindUser(sLine.Token(1));

		if (pUser) {
			CIRCNetwork *pNetwork = pUser->FindNetwork(sLine.Token(2));

			if (pNetwork) {
				pNetwork->PutUser(sLine.Token(3, true));
				PutModule("Sent [" + sLine.Token(3, true) + "] to " + pUser->GetUserName() + "/" + pNetwork->GetName());
			} else {
				PutModule("Network [" + sLine.Token(2) + "] not found for user [" + sLine.Token(1) + "]");
			}
		} else {
			PutModule("User [" + sLine.Token(1) + "] not found");
		}
	}

	void SendServer(const CString& sLine) {
		CUser *pUser = CZNC::Get().FindUser(sLine.Token(1));

		if (pUser) {
			CIRCNetwork *pNetwork = pUser->FindNetwork(sLine.Token(2));

			if (pNetwork) {
				pNetwork->PutIRC(sLine.Token(3, true));
				PutModule("Sent [" + sLine.Token(3, true) + "] to IRC Server of " + pUser->GetUserName() + "/" + pNetwork->GetName());
			} else {
				PutModule("Network [" + sLine.Token(2) + "] not found for user [" + sLine.Token(1) + "]");
			}
		} else {
			PutModule("User [" + sLine.Token(1) + "] not found");
		}
	}

public:
	virtual ~CSendRaw_Mod() {}

	virtual bool OnLoad(const CString& sArgs, CString& sErrorMsg) {
		if (!m_pUser->IsAdmin()) {
			sErrorMsg = "You must have admin privileges to load this module";
			return false;
		}

		return true;
	}

	virtual CString GetWebMenuTitle() { return "Send Raw"; }
	virtual bool WebRequiresAdmin() { return true; }

	virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) {
		if (sPageName == "index") {
			if (WebSock.IsPost()) {
				CUser *pUser = CZNC::Get().FindUser(WebSock.GetParam("user").Token(0, false, "/"));
				if (!pUser) {
					WebSock.GetSession()->AddError("User not found");
					return true;
				}

				CIRCNetwork *pNetwork = pUser->FindNetwork(WebSock.GetParam("user").Token(1, false, "/"));
				if (!pNetwork) {
					WebSock.GetSession()->AddError("Network not found");
					return true;
				}

				bool bToServer = WebSock.GetParam("send_to") == "server";
				const CString sLine = WebSock.GetParam("line");

				Tmpl["user"] = pUser->GetUserName();
				Tmpl[bToServer ? "to_server" : "to_client"] = "true";
				Tmpl["line"] = sLine;

				if (bToServer) {
					pNetwork->PutIRC(sLine);
				} else {
					pNetwork->PutUser(sLine);
				}

				WebSock.GetSession()->AddSuccess("Line sent");
			}

			const map<CString,CUser*>& msUsers = CZNC::Get().GetUserMap();
			for (map<CString,CUser*>::const_iterator it = msUsers.begin(); it != msUsers.end(); ++it) {
				CTemplate& l = Tmpl.AddRow("UserLoop");
				l["Username"] = (*it->second).GetUserName();

				vector<CIRCNetwork*> vNetworks = (*it->second).GetNetworks();
				for (vector<CIRCNetwork*>::const_iterator it2 = vNetworks.begin(); it2 != vNetworks.end(); ++it2) {
					CTemplate& NetworkLoop = l.AddRow("NetworkLoop");
					NetworkLoop["Username"] = (*it->second).GetUserName();
					NetworkLoop["Network"] = (*it2)->GetName();
				}
			}

			return true;
		}

		return false;
	}

	MODCONSTRUCTOR(CSendRaw_Mod) {
		AddHelpCommand();
		AddCommand("Client",          static_cast<CModCommand::ModCmdFunc>(&CSendRaw_Mod::SendClient),
			"[user] [network] [data to send]",  "The data will be sent to the user's IRC client(s)");
		AddCommand("Server",            static_cast<CModCommand::ModCmdFunc>(&CSendRaw_Mod::SendServer),
			"[user] [network] [data to send]",  "The data will be sent to the IRC server the user is connected to");
	}
};

USERMODULEDEFS(CSendRaw_Mod, "Lets you send some raw IRC lines as/to someone else")
<commit_msg>send_raw: Add a command to send a line to the current client<commit_after>/*
 * Copyright (C) 2004-2012  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/znc.h>

class CSendRaw_Mod: public CModule {
	void SendClient(const CString& sLine) {
		CUser *pUser = CZNC::Get().FindUser(sLine.Token(1));

		if (pUser) {
			CIRCNetwork *pNetwork = pUser->FindNetwork(sLine.Token(2));

			if (pNetwork) {
				pNetwork->PutUser(sLine.Token(3, true));
				PutModule("Sent [" + sLine.Token(3, true) + "] to " + pUser->GetUserName() + "/" + pNetwork->GetName());
			} else {
				PutModule("Network [" + sLine.Token(2) + "] not found for user [" + sLine.Token(1) + "]");
			}
		} else {
			PutModule("User [" + sLine.Token(1) + "] not found");
		}
	}

	void SendServer(const CString& sLine) {
		CUser *pUser = CZNC::Get().FindUser(sLine.Token(1));

		if (pUser) {
			CIRCNetwork *pNetwork = pUser->FindNetwork(sLine.Token(2));

			if (pNetwork) {
				pNetwork->PutIRC(sLine.Token(3, true));
				PutModule("Sent [" + sLine.Token(3, true) + "] to IRC Server of " + pUser->GetUserName() + "/" + pNetwork->GetName());
			} else {
				PutModule("Network [" + sLine.Token(2) + "] not found for user [" + sLine.Token(1) + "]");
			}
		} else {
			PutModule("User [" + sLine.Token(1) + "] not found");
		}
	}

	void CurrentClient(const CString& sLine) {
		CString sData = sLine.Token(1, true);
		m_pClient->PutClient(sData);
	}

public:
	virtual ~CSendRaw_Mod() {}

	virtual bool OnLoad(const CString& sArgs, CString& sErrorMsg) {
		if (!m_pUser->IsAdmin()) {
			sErrorMsg = "You must have admin privileges to load this module";
			return false;
		}

		return true;
	}

	virtual CString GetWebMenuTitle() { return "Send Raw"; }
	virtual bool WebRequiresAdmin() { return true; }

	virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) {
		if (sPageName == "index") {
			if (WebSock.IsPost()) {
				CUser *pUser = CZNC::Get().FindUser(WebSock.GetParam("user").Token(0, false, "/"));
				if (!pUser) {
					WebSock.GetSession()->AddError("User not found");
					return true;
				}

				CIRCNetwork *pNetwork = pUser->FindNetwork(WebSock.GetParam("user").Token(1, false, "/"));
				if (!pNetwork) {
					WebSock.GetSession()->AddError("Network not found");
					return true;
				}

				bool bToServer = WebSock.GetParam("send_to") == "server";
				const CString sLine = WebSock.GetParam("line");

				Tmpl["user"] = pUser->GetUserName();
				Tmpl[bToServer ? "to_server" : "to_client"] = "true";
				Tmpl["line"] = sLine;

				if (bToServer) {
					pNetwork->PutIRC(sLine);
				} else {
					pNetwork->PutUser(sLine);
				}

				WebSock.GetSession()->AddSuccess("Line sent");
			}

			const map<CString,CUser*>& msUsers = CZNC::Get().GetUserMap();
			for (map<CString,CUser*>::const_iterator it = msUsers.begin(); it != msUsers.end(); ++it) {
				CTemplate& l = Tmpl.AddRow("UserLoop");
				l["Username"] = (*it->second).GetUserName();

				vector<CIRCNetwork*> vNetworks = (*it->second).GetNetworks();
				for (vector<CIRCNetwork*>::const_iterator it2 = vNetworks.begin(); it2 != vNetworks.end(); ++it2) {
					CTemplate& NetworkLoop = l.AddRow("NetworkLoop");
					NetworkLoop["Username"] = (*it->second).GetUserName();
					NetworkLoop["Network"] = (*it2)->GetName();
				}
			}

			return true;
		}

		return false;
	}

	MODCONSTRUCTOR(CSendRaw_Mod) {
		AddHelpCommand();
		AddCommand("Client",          static_cast<CModCommand::ModCmdFunc>(&CSendRaw_Mod::SendClient),
			"[user] [network] [data to send]",  "The data will be sent to the user's IRC client(s)");
		AddCommand("Server",          static_cast<CModCommand::ModCmdFunc>(&CSendRaw_Mod::SendServer),
			"[user] [network] [data to send]",  "The data will be sent to the IRC server the user is connected to");
		AddCommand("Current",         static_cast<CModCommand::ModCmdFunc>(&CSendRaw_Mod::CurrentClient),
			"[data to send]",                   "The data will be sent to your current client");
	}
};

USERMODULEDEFS(CSendRaw_Mod, "Lets you send some raw IRC lines as/to someone else")
<|endoftext|>


<commit_before>
/****************************************************************************\
 * Copyright (C) 2017 Scandy
 *
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
 * PURPOSE.
 *
\****************************************************************************/

/**
 * \file basic_usage.cpp
 * \brief Shows to create a ScandyCore isntance and attach a TestViewport to it.
 * This basic_usage example shows to create a ScandyCore isntance and attach
 * a TestViewport to it. It then starts the visualizer and runs until closed
 * by the user.
 */

// include scandycore so we can make 3D magic happen
#include <scandy/core/IScandyCore.h>
#include <scandy_license.h>

#include <thread>
#include <iostream>

using namespace scandy::core;
using namespace std;

int main(int argc, char *argv[]) {
  // Create the ScandyCore instance with a Visualizer window of 400x400
  auto core = IScandyCore::factoryCreate(400,400);
  if(!core) {
    std::cerr << "ERROR creating ScandyCore" << std::endl;
    return (int) scandy::core::Status::EXCEPTION_IN_HANDLER;;
  }

  // We need to set the ScandyCore license to our internal license
  auto status = core->setLicense(scandy_core_license);
  if(status != Status::SUCCESS) {
    std::cerr << "ERROR could not set license" << std::endl;
    return (int) status;
  }

  // read data from the attached the Pico Flex
  status = core->initializeScanner(ScannerType::PICO_FLEXX);
  if(status != Status::SUCCESS) {
    std::cerr << "ERROR could not find attached usb Pico Flexx depth sensor" << std::endl;
    return (int) status;
  }

  // Get a reference to the ScandyCore Visualizer
  auto viz = core->getVisualizer();
  if(!viz) {
    std::cerr << "ERROR getting ScandyCore Visualizer" << std::endl;
    return (int) scandy::core::Status::NO_VISUALIZER_FOUND;
  }

  // Start SLAM to process the depth data in the rrf file.
  status = core->startPreview();

  // The visualizer window must run in the main thread.  Create a background
  // thread to kill the visualizer thread after the entire file has been processed.
  std::thread slam_thread([core, viz]() {

    auto status = core->startScanning();
    if(status != Status::SUCCESS) {
      std::cerr << "ERROR starting scanner" << std::endl;
      abort();
    }

    // continue to scan until user cancels
    std::cout << "Press 'q' to stop scanning: ";
    int ch;
    do {
      std::cin >> ch;
      std::cout << ch;
    }
    while(ch != 'q');

    status = core->stopScanning();
    if(status != Status::SUCCESS) {
      std::cerr << "ERROR stopping scanner" << std::endl;
      abort();
    }

    viz->stop();
    viz->join();
  });

  // Start the Visualizer. This will not return return until the window is closed by the user.
  viz->start();

  // The Visualizer will continue running until the window is closed by the user.
  slam_thread.join();

  // create the mesh
  status = core->createVisualizer(400,400, 1, 1);
  if(status != Status::SUCCESS) {
    std::cerr << "ERROR could not create visualizer" << std::endl;
    return (int) status;
  }
  viz = core->getVisualizer();

  // generate the mesh
  status = core->generateMesh();
  if(status != Status::SUCCESS) {
    std::cerr << "ERROR could not generate mesh" << std::endl;
    return (int) status;
  }

  // save mesh
  status = core->saveMesh("temp.ply");
  if(status != Status::SUCCESS) {
    std::cerr << "ERROR could not save mesh" << std::endl;
    return (int) status;
  }

  std::cout << "Saved mesh to temp.ply" << std::endl;

  // view mesh
  viz->start();

  return 0;
}
<commit_msg>CORE-421 Update basic usage mesh generate to fix reading q char<commit_after>
/****************************************************************************\
 * Copyright (C) 2017 Scandy
 *
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
 * PURPOSE.
 *
\****************************************************************************/

/**
 * \file basic_usage.cpp
 * \brief Shows to create a ScandyCore isntance and attach a TestViewport to it.
 * This basic_usage example shows to create a ScandyCore isntance and attach
 * a TestViewport to it. It then starts the visualizer and runs until closed
 * by the user.
 */

// include scandycore so we can make 3D magic happen
#include <scandy/core/IScandyCore.h>
#include <scandy_license.h>

#include <thread>
#include <iostream>

using namespace scandy::core;
using namespace std;

int main(int argc, char *argv[]) {
  // Create the ScandyCore instance with a Visualizer window of 400x400
  auto core = IScandyCore::factoryCreate(400,400);
  if(!core) {
    std::cerr << "ERROR creating ScandyCore" << std::endl;
    return (int) scandy::core::Status::EXCEPTION_IN_HANDLER;;
  }

  // We need to set the ScandyCore license to our internal license
  auto status = core->setLicense(scandy_core_license);
  if(status != Status::SUCCESS) {
    std::cerr << "ERROR could not set license" << std::endl;
    return (int) status;
  }

  // read data from the attached the Pico Flex
  status = core->initializeScanner(ScannerType::PICO_FLEXX);
  if(status != Status::SUCCESS) {
    std::cerr << "ERROR could not find attached usb Pico Flexx depth sensor" << std::endl;
    return (int) status;
  }

  // Get a reference to the ScandyCore Visualizer
  auto viz = core->getVisualizer();
  if(!viz) {
    std::cerr << "ERROR getting ScandyCore Visualizer" << std::endl;
    return (int) scandy::core::Status::NO_VISUALIZER_FOUND;
  }

  // Start SLAM to process the depth data in the rrf file.
  status = core->startPreview();

  // The visualizer window must run in the main thread.  Create a background
  // thread to kill the visualizer thread after the entire file has been processed.
  std::thread slam_thread([core, viz]() {

    auto status = core->startScanning();
    if(status != Status::SUCCESS) {
      std::cerr << "ERROR starting scanner" << std::endl;
      abort();
    }

    // continue to scan until user cancels
    std::cout << "Press 'q' to stop scanning: ";
    char ch;
    do {
      std::cin >> ch;
    }
    while(ch != 'q');

    status = core->stopScanning();
    if(status != Status::SUCCESS) {
      std::cerr << "ERROR stopping scanner" << std::endl;
      abort();
    }

    viz->stop();
    viz->join();
  });

  // Start the Visualizer. This will not return return until the window is closed by the user.
  viz->start();

  // The Visualizer will continue running until the window is closed by the user.
  slam_thread.join();

  // create the mesh
  status = core->createVisualizer(400,400, 1, 1);
  if(status != Status::SUCCESS) {
    std::cerr << "ERROR could not create visualizer" << std::endl;
    return (int) status;
  }
  viz = core->getVisualizer();

  // generate the mesh
  status = core->generateMesh();
  if(status != Status::SUCCESS) {
    std::cerr << "ERROR could not generate mesh" << std::endl;
    return (int) status;
  }

  // save mesh
  status = core->saveMesh("temp.ply");
  if(status != Status::SUCCESS) {
    std::cerr << "ERROR could not save mesh" << std::endl;
    return (int) status;
  }

  std::cout << "Saved mesh to temp.ply" << std::endl;

  // view mesh
  viz->start();

  return 0;
}
<|endoftext|>