<commit_before>#include<iostream>
#include<cassert>
#include<thread>
#include<chrono>

#include "ics3/ics"

void testAngle();
void testBaudrate();
void testEepParam();
void testID();
void testParameter();
void testICS3();
void testIcsMove(ics::ICS3&, const ics::ID&);
void testIcsParam(ics::ICS3&, const ics::ID&);
void testIcsEeprom(ics::ICS3&, const ics::ID&);

template<typename Iter> constexpr void dump(Iter&& begin, Iter&& end) noexcept;

int main() {
  testAngle();
  testBaudrate();
  testEepParam();
  testID();
  testParameter();
  testICS3();
  return 0;
}

void testAngle() {
  std::cout << std::endl << "angle test section" << std::endl;
  // constexpr test
  constexpr auto defDeg = ics::Angle::newDegree();
  constexpr auto defRad = ics::Angle::newRadian();
  static_assert(defDeg == 0, "Angle default cast error");
  static_assert(defRad.get() == 0, "Angle default get() error");
  static_assert(defDeg.getRaw() == 7500, "Angle default must is 7500");
  static_assert(defDeg.getRaw() == defRad.getRaw(), "Angle have different default");
  constexpr auto degree1 = ics::Angle::newDegree(90);
  constexpr auto radian1 = ics::Angle::newRadian(M_PI / 2);
  static_assert(degree1.getRaw() == radian1.getRaw(), "difference: 90 deg <-> pi/2 rad");
  constexpr auto degree2 = ics::Angle::newDegree(30);
  constexpr auto radian2 = ics::Angle::newRadian(M_PI / 6);
  static_assert(degree2.getRaw() == radian2.getRaw(), "difference: 30 deg <-> pi/6 rad");
  try {
    ics::Angle::newDegree(136);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }

  // runtime test
  auto degree = ics::Angle::newDegree(0);
  auto radian = ics::Angle::newRadian(0);
  assert(degree.getRaw() == radian.getRaw());
  degree.set(90);
  radian.set(M_PI / 2);
  assert(degree.getRaw() == radian.getRaw());
  degree.set(-60);
  radian.set(-M_PI / 3);
  assert(degree.getRaw() == radian.getRaw());
  try {
    degree.set(150);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
  try {
    radian.set(M_PI);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
}

void testBaudrate() {
  std::cout << std::endl << "Baudrate test section" << std::endl;
  // constexpr test
  constexpr auto baudrate115200 = ics::Baudrate::RATE115200();
  static_assert(baudrate115200 == B115200, "Baudrate: not equal B115200");
  static_assert(baudrate115200.getRomData() == 10, "Baudrate: romdata error");
  static_assert(baudrate115200.get() == B115200, "Baudrate: get method error");
}

void testEepParam() {
  std::cout << std::endl << "EepParam test section" << std::endl;
  // constexpr test
  constexpr auto current = ics::EepParam::current();
  static_assert(63 == current.get(), "current error");
  constexpr auto stretch = ics::EepParam::stretch(244);
  static_assert(244 == stretch.get(), "strech error");
  try {
    ics::EepParam::flag(10);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }

  // runtime test
  auto speed = ics::EepParam::speed();
  assert(127 == speed.get());
  speed.set(100);
  assert(100 == speed.get());
  try {
    speed.set(200);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
}

void testID() {
  std::cout << std::endl << "ID test section" << std::endl;
  constexpr ics::ID id {0};
  static_assert(id == 0, "id 0 error");
  static_assert(id.get() == 0, "id 0 error by get");
  constexpr ics::ID id31 {31};
  static_assert(id31 == 31, "id 31 error");
  static_assert(id31.get() == 31, "id 31 error by get");
  try {
    ics::ID id32 {32}; // if constexpr, compile error
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
  try {
    ics::ID error {static_cast<unsigned char>(-1)}; // if constexpr, compile error
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
}

void testParameter() {
  std::cout << std::endl << "parameter test section" << std::endl;
  // constexpr test
  constexpr auto stretch = ics::Parameter::stretch();
  static_assert(30 == stretch.get(), "stretch error");
  static_assert(30 == stretch, "stretch error by cast");
  static_assert(0x01 == stretch.getSubcommand(), "stretch error by subcommand");
  constexpr auto speed = ics::Parameter::speed(100);
  static_assert(100 == speed.get(), "speed error");
  static_assert(100 == speed, "speed error by cast");
  static_assert(0x02 == speed.getSubcommand(), "speed error by subcommand");
  try {
    ics::Parameter::temperature(0);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }

  // runtime test
  auto current = ics::Parameter::current();
  assert(63 == current.get());
  assert(0x03 == current.getSubcommand());
  current.set(30);
  assert(30 == current);
  current = 10;
  assert(10 == current);
  try {
    current.set(70);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
  try {
    current = 64;
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
}

void testICS3() {
  std::cout << std::endl << "ICS3 test section" << std::endl;
  constexpr const char*const path = "/dev/ttyUSB0";
  constexpr auto baudrate = ics::Baudrate::RATE115200();
  constexpr ics::ID id {2};
  try {
    ics::ICS3 ics {path, baudrate};
    testIcsMove(ics, id);
    testIcsParam(ics, id);
    testIcsEeprom(ics, id);
  } catch (std::runtime_error& e) {
    std::cout << e.what() << std::endl;
  }
}

void testIcsMove(ics::ICS3& ics, const ics::ID& id) {
  std::cout << "ICS3 'move' and 'free' method test section"  << std::endl;
  auto degree = ics::Angle::newDegree();
  std::cout << "move to " << degree << "[deg]" << std::endl;
  auto nowPos = ics.move(id, degree);
  std::cout << "now pos is " << nowPos << "[deg]" << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  degree = 50;
  std::cout << "move to " << degree << "[deg]" << std::endl;
  nowPos = ics.move(id, degree);
  std::cout << "now pos is " << nowPos << "[deg]" << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  degree = -50;
  std::cout << "move to " << degree << "[deg]" << std::endl;
  nowPos = ics.move(id, degree);
  std::cout << "now pos is " << nowPos << "[deg]" << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  degree = 0;
  std::cout << "move to " << degree << "[deg]" << std::endl;
  nowPos = ics.move(id, degree);
  std::cout << "now pos is " << nowPos << "[deg]" << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  std::cout << "free torque" << std::endl;
  nowPos = ics.free(id);
  std::cout << "now pos is " << nowPos << "[deg]" << std::endl;
}

void testIcsParam(ics::ICS3& ics, const ics::ID& id) {
  auto defaultStretch = ics.get(id, ics::Parameter::stretch());
  std::cout << "default stretch is " << static_cast<int>(defaultStretch) << std::endl;
  constexpr uint8_t writeNumber {31};
  ics.set(id, ics::Parameter::stretch(writeNumber));
  auto newStretch = ics.get(id, defaultStretch);
  ics.set(id, defaultStretch); // before checking, restore data.
  assert(newStretch == 31);
  assert(defaultStretch == ics.get(id, defaultStretch));
}

void testIcsEeprom(ics::ICS3& ics, const ics::ID& id) {
  std::cout << "ics 'getRom' and 'setRom' test section" << std::endl;
  auto rom = ics.getRom(id);
  auto defaultStretch = rom.get(ics::EepParam::stretch());
  std::cout << "default stretch is " << defaultStretch << std::endl;
}

template<typename Iter> constexpr void dump(Iter&& begin, Iter&& end) noexcept {
  while (begin != end) std::cout << *begin << ", ";
  std::cout << std::endl;
}
<commit_msg>Update testcode for readability<commit_after>#include<iostream>
#include<cassert>
#include<thread>
#include<chrono>

#include "ics3/ics"

void testAngle();
void testBaudrate();
void testEepParam();
void testID();
void testParameter();
void testICS3();
void testIcsMove(ics::ICS3&, const ics::ID&);
void testIcsParam(ics::ICS3&, const ics::ID&);
void testIcsEeprom(ics::ICS3&, const ics::ID&);

template<typename Iter> constexpr void dump(Iter&& begin, Iter&& end) noexcept;

int main() {
  testAngle();
  testBaudrate();
  testEepParam();
  testID();
  testParameter();
  testICS3();
  return 0;
}

void testAngle() {
  std::cout << std::endl << "angle test section" << std::endl;
  // constexpr test
  constexpr auto defDeg = ics::Angle::newDegree();
  constexpr auto defRad = ics::Angle::newRadian();
  static_assert(defDeg == 0, "Angle default cast error");
  static_assert(defRad.get() == 0, "Angle default get() error");
  static_assert(defDeg.getRaw() == 7500, "Angle default must is 7500");
  static_assert(defDeg.getRaw() == defRad.getRaw(), "Angle have different default");
  constexpr auto degree1 = ics::Angle::newDegree(90);
  constexpr auto radian1 = ics::Angle::newRadian(M_PI / 2);
  static_assert(degree1.getRaw() == radian1.getRaw(), "difference: 90 deg <-> pi/2 rad");
  constexpr auto degree2 = ics::Angle::newDegree(30);
  constexpr auto radian2 = ics::Angle::newRadian(M_PI / 6);
  static_assert(degree2.getRaw() == radian2.getRaw(), "difference: 30 deg <-> pi/6 rad");
  try {
    ics::Angle::newDegree(136);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }

  // runtime test
  auto degree = ics::Angle::newDegree(0);
  auto radian = ics::Angle::newRadian(0);
  assert(degree.getRaw() == radian.getRaw());
  degree.set(90);
  radian.set(M_PI / 2);
  assert(degree.getRaw() == radian.getRaw());
  degree.set(-60);
  radian.set(-M_PI / 3);
  assert(degree.getRaw() == radian.getRaw());
  try {
    degree.set(150);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
  try {
    radian.set(M_PI);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
}

void testBaudrate() {
  std::cout << std::endl << "Baudrate test section" << std::endl;
  // constexpr test
  constexpr auto baudrate115200 = ics::Baudrate::RATE115200();
  static_assert(baudrate115200 == B115200, "Baudrate: not equal B115200");
  static_assert(baudrate115200.getRomData() == 10, "Baudrate: romdata error");
  static_assert(baudrate115200.get() == B115200, "Baudrate: get method error");
}

void testEepParam() {
  std::cout << std::endl << "EepParam test section" << std::endl;
  // constexpr test
  constexpr auto current = ics::EepParam::current();
  static_assert(63 == current.get(), "current error");
  constexpr auto stretch = ics::EepParam::stretch(244);
  static_assert(244 == stretch.get(), "strech error");
  try {
    ics::EepParam::flag(10);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }

  // runtime test
  auto speed = ics::EepParam::speed();
  assert(127 == speed.get());
  speed.set(100);
  assert(100 == speed.get());
  try {
    speed.set(200);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
}

void testID() {
  std::cout << std::endl << "ID test section" << std::endl;
  constexpr ics::ID id {0};
  static_assert(id == 0, "id 0 error");
  static_assert(id.get() == 0, "id 0 error by get");
  constexpr ics::ID id31 {31};
  static_assert(id31 == 31, "id 31 error");
  static_assert(id31.get() == 31, "id 31 error by get");
  try {
    ics::ID id32 {32}; // if constexpr, compile error
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
  try {
    ics::ID error {static_cast<unsigned char>(-1)}; // if constexpr, compile error
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
}

void testParameter() {
  std::cout << std::endl << "parameter test section" << std::endl;
  // constexpr test
  constexpr auto stretch = ics::Parameter::stretch();
  static_assert(30 == stretch.get(), "stretch error");
  static_assert(30 == stretch, "stretch error by cast");
  static_assert(0x01 == stretch.getSubcommand(), "stretch error by subcommand");
  constexpr auto speed = ics::Parameter::speed(100);
  static_assert(100 == speed.get(), "speed error");
  static_assert(100 == speed, "speed error by cast");
  static_assert(0x02 == speed.getSubcommand(), "speed error by subcommand");
  try {
    ics::Parameter::temperature(0);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }

  // runtime test
  auto current = ics::Parameter::current();
  assert(63 == current.get());
  assert(0x03 == current.getSubcommand());
  current.set(30);
  assert(30 == current);
  current = 10;
  assert(10 == current);
  try {
    current.set(70);
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
  try {
    current = 64;
    assert(false);
  } catch (std::invalid_argument& e) {
    std::cout << e.what() << std::endl;
  }
}

void testICS3() {
  std::cout << std::endl << "ICS3 test section" << std::endl;
  constexpr const char*const path = "/dev/ttyUSB0";
  constexpr auto baudrate = ics::Baudrate::RATE115200();
  constexpr ics::ID id {2};
  try {
    ics::ICS3 ics {path, baudrate};
    testIcsMove(ics, id);
    testIcsParam(ics, id);
    testIcsEeprom(ics, id);
  } catch (std::runtime_error& e) {
    std::cout << e.what() << std::endl;
  }
}

void testIcsMove(ics::ICS3& ics, const ics::ID& id) {
  std::cout << "ICS3 'move' and 'free' method test section"  << std::endl;
  auto degree = ics::Angle::newDegree();
  std::cout << "move to " << degree << "[deg]" << std::endl;
  auto nowPos = ics.move(id, degree);
  std::cout << "now pos is " << nowPos << "[deg]" << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  degree = 50;
  std::cout << "move to " << degree << "[deg]" << std::endl;
  nowPos = ics.move(id, degree);
  std::cout << "now pos is " << nowPos << "[deg]" << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  degree = -50;
  std::cout << "move to " << degree << "[deg]" << std::endl;
  nowPos = ics.move(id, degree);
  std::cout << "now pos is " << nowPos << "[deg]" << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  degree = 0;
  std::cout << "move to " << degree << "[deg]" << std::endl;
  nowPos = ics.move(id, degree);
  std::cout << "now pos is " << nowPos << "[deg]" << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  std::cout << "free torque" << std::endl;
  nowPos = ics.free(id);
  std::cout << "now pos is " << nowPos << "[deg]" << std::endl;
}

void testIcsParam(ics::ICS3& ics, const ics::ID& id) {
  std::cout << "ICS3 'get' and 'set' method test section"  << std::endl;
  auto defaultStretch = ics.get(id, ics::Parameter::stretch());
  std::cout << "default stretch is " << static_cast<int>(defaultStretch) << std::endl;
  constexpr uint8_t writeNumber {31};
  ics.set(id, ics::Parameter::stretch(writeNumber));
  auto newStretch = ics.get(id, defaultStretch);
  ics.set(id, defaultStretch); // before checking, restore data.
  assert(newStretch == 31);
  assert(defaultStretch == ics.get(id, defaultStretch));
}

void testIcsEeprom(ics::ICS3& ics, const ics::ID& id) {
  std::cout << "ics 'getRom' and 'setRom' test section" << std::endl;
  auto rom = ics.getRom(id);
  auto defaultStretch = rom.get(ics::EepParam::stretch());
  std::cout << "default stretch is " << defaultStretch << std::endl;
}

template<typename Iter> constexpr void dump(Iter&& begin, Iter&& end) noexcept {
  while (begin != end) std::cout << *begin << ", ";
  std::cout << std::endl;
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "Collider.h"
#include "Explosion.h"
#include "ColliderManager.h"

//Base Class of All Explosions
bool Explosion::init()
{
	explosion = ParticleExplosion::create();
	this->addChild(explosion);
	isFlying = true;
	lifeTime = 2 * Director::getInstance()->getFrameRate();
	return true;
}

void Explosion::Act()
{
	if (lifeTime > 0)
	{
		lifeTime--;
	}
	else
	{
		SetFlying(false);
		removeFromParent();
		ColliderManager::GetInstance()->EraseCollider(this);
	}
}

bool Explosion::IsFlying()
{
	return isFlying;
}

void Explosion::SetFlying(bool flag)
{
	isFlying = flag;
}

bool Explosion::IsBullet()
{
	return false;
}

void Explosion::SetPosition(Point pos)
{
	setPosition(pos);
	explosion->setPosition(0,0);
}

<commit_msg>0,0 -> Point::ZERO<commit_after>#include "stdafx.h"
#include "Collider.h"
#include "Explosion.h"
#include "ColliderManager.h"

//Base Class of All Explosions
bool Explosion::init()
{
	explosion = ParticleExplosion::create();
	this->addChild(explosion);
	isFlying = true;
	lifeTime = 2 * Director::getInstance()->getFrameRate();
	return true;
}

void Explosion::Act()
{
	if (lifeTime > 0)
	{
		lifeTime--;
	}
	else
	{
		SetFlying(false);
		removeFromParent();
		ColliderManager::GetInstance()->EraseCollider(this);
	}
}

bool Explosion::IsFlying()
{
	return isFlying;
}

void Explosion::SetFlying(bool flag)
{
	isFlying = flag;
}

bool Explosion::IsBullet()
{
	return false;
}

void Explosion::SetPosition(Point pos)
{
	setPosition(pos);
	explosion->setPosition(Point::ZERO);
}

<|endoftext|>


<commit_before>#include "test.hpp"
#include <sys/stat.h>
#include <string>
#include <stdio.h>
Test::Test(string k)
{

}

bool Test::execute(vector<string> path)
{
	string flag;
	string newPath;
	struct stat buf;
	int validPath;
	bool valid = false;

	if (path[0].at(0) == '-')
	{
		flag = path[0];
		newPath = path[1];
	}
	else
	{
		flag = "-e";
		newPath = path[0];
	}

	if (flag.size() > 2)
	{
		cout << "Invalid flag type, setting flag -e" << endl;
		flag = "-e";
	}

	validPath = stat((char*)newPath.c_str(), &buf);
	if (validPath == -1)
	{
		perror("stat");
		return false;
	}
	else if (validPath == 0)
	{
		valid = true;
	}
	else
	{
		cout << "Path does not exist" << endl;
		return false;
	}

	if (flag == "-e")
	{
		cout << "(True)" << endl;
	}
	else if (flag == "-f")
	{
		valid = S_ISREG(buf.st_mode);
		if (valid)
		{
			cout << "(True)" << endl;
		}
		else
		{
			cout << "(False)" << endl;
		}
	}
	else if (flag == "-d")
	{
		valid = S_ISDIR(buf.st_mode);
		if (valid)
		{
			cout << "(True)" << endl;
		}
		else
		{
			cout << "(False)" << endl;
		}
	}
	else
	{
		cout << "Not a valid flag.  Setting flag to -e" << endl;
		cout << "(True)" << endl;
		valid = true;
	}

	return valid;

}
<commit_msg>added debugging for test<commit_after>#include "test.hpp"
#include <sys/stat.h>
#include <string>
#include <stdio.h>
Test::Test(string k)
{

}

bool Test::execute(vector<string> path)
{
	string flag;
	string newPath;
	struct stat buf;
	int validPath;
	bool valid = false;

	if (path[0].at(0) == '-')
	{
		cout << "FLAG HERE: " << path[0] << endl;
		flag = path[0];
		newPath = path[1];
	}
	else
	{
		flag = "-e";
		newPath = path[0];
	}

	if (flag.size() > 2)
	{
		cout << "FLAG SIZE: " << flag.size() << endl;
		cout << "Invalid flag type, setting flag -e" << endl;
		flag = "-e";
	}

	validPath = stat((char*)newPath.c_str(), &buf);
	if (validPath == -1)
	{
		perror("stat");
		return false;
	}
	else if (validPath == 0)
	{
		valid = true;
	}
	else
	{
		cout << "Path does not exist" << endl;
		return false;
	}

	if (flag == "-e")
	{
		cout << "(True)" << endl;
	}
	else if (flag == "-f")
	{
		valid = S_ISREG(buf.st_mode);
		if (valid)
		{
			cout << "(True)" << endl;
		}
		else
		{
			cout << "(False)" << endl;
		}
	}
	else if (flag == "-d")
	{
		valid = S_ISDIR(buf.st_mode);
		if (valid)
		{
			cout << "(True)" << endl;
		}
		else
		{
			cout << "(False)" << endl;
		}
	}
	else
	{
		cout << "Not a valid flag.  Setting flag to -e" << endl;
		cout << "(True)" << endl;
		valid = true;
	}

	return valid;

}
<|endoftext|>


<commit_before>#include <fstream>

#include <assert.h>
#include <getopt.h>

#include <boost/filesystem.hpp>

#include "util.hpp"

using namespace std;
using namespace boost::filesystem;

void run_tests() {
  /*****************************************************************************
   * line_iterator
   */

  ifstream f3("test/simple/threelines.txt");
  ifstream f4("test/simple/fourlines.txt");

  assert(distance(line_iterator(&f3), line_iterator()) == 3);
  assert(distance(line_iterator(&f4), line_iterator()) == 4);

  /*****************************************************************************
   * file_line_iterator
   */

  {
    recursive_directory_iterator rdi("test/simple");

    size_t count = 0;
    for (file_line_iterator it(&rdi), end; it != end; ++it)
      count++;
    assert(count == 7);
  }

  {
    recursive_directory_iterator rdi("data");
    size_t count = 0;
    for (file_line_iterator it(&rdi), end; it != end; ++it)
      count++;
    assert(count == 688892);
  }

  {
    vector<string> expected, actual;
    expected.push_back("coffee");
    expected.push_back("beer");
    expected.push_back("whiskey");
    expected.push_back("purple drank");
    expected.push_back("foo");
    expected.push_back("bar");
    expected.push_back("baz");

    recursive_directory_iterator rdi("test/simple");

    for (file_line_iterator it(&rdi), end; it != end; ++it)
      actual.push_back(*it);

    assert(expected == actual);
  }

  /*****************************************************************************
   * tuple_iterator
   */

  {
    recursive_directory_iterator rdi("test/subset");
    file_line_iterator fli(&rdi);

    size_t count = 0;
    for (tuple_iterator ti(&fli), end; ti != end; ++ti)
      count++;
    assert(count == 783);
  }

  {
    recursive_directory_iterator rdi("test/subset");
    file_line_iterator fli(&rdi);
    vector<string> tuples;

    for (tuple_iterator ti(&fli), end; ti != end; ++ti)
      tuples.push_back(*ti);

    assert(tuples[0] == "Pierre/NNP");
    assert(tuples[1] == "Vinken/NNP");
    assert(tuples[2] == ",/,");
    assert(tuples[3] == "61/CD");
    assert(tuples[4] == "years/NNS");
    assert(tuples[780] == "today/NN");
    assert(tuples[781] == "./.");
    assert(tuples[782] == "''/''");
  }

  /*****************************************************************************
   * sentence_iterator
   */

  {
    recursive_directory_iterator rdi("test/subset");
    file_line_iterator fli(&rdi);
    tuple_iterator ti(&fli);

    size_t count = 0;
    for (sentence_iterator si(&ti), end; si != end; ++si)
      count++;
    assert(count == 33);
  }

  {
    recursive_directory_iterator rdi("data");
    file_line_iterator fli(&rdi);
    tuple_iterator ti(&fli);

    size_t count = 0;
    for (sentence_iterator si(&ti), end; si != end; ++si)
      count++;

    assert(count == 45280);
  }

  // this test fails because we're not handling the case where closing quotes
  // come after a period. woldn't be too hard, but i don't know if it's worth
  // it.
  /* { */
  /*   recursive_directory_iterator rdi("data"); */
  /*   file_line_iterator fli(&rdi); */
  /*   tuple_iterator ti(&fli); */
  /*   vector<sentence> result; */

  /*   for (sentence_iterator si(&ti), end; si != end; ++si) */
  /*     result.push_back(*si); */

  /*   cout << "end: " << result.back().back().first << endl; */
  /*   assert(result.back().back().first == "''"); */
  /* } */
}

int main(int argc, char* argv[]) {
  char opt;

  while ((opt = getopt(argc, argv, "c")) != -1) {
    switch (opt) {
      default: /* '?' */
        cerr << "USAGE: " << argv[0] << endl;
        exit(EXIT_FAILURE);
    }
  }

  run_tests();

  return 0;
}
<commit_msg>added memory leak test<commit_after>#include <fstream>

#include <assert.h>
#include <getopt.h>

#include <boost/filesystem.hpp>

#include "util.hpp"

using namespace std;
using namespace boost::filesystem;

void run_tests() {
  /*****************************************************************************
   * line_iterator
   */

  ifstream f3("test/simple/threelines.txt");
  ifstream f4("test/simple/fourlines.txt");

  assert(distance(line_iterator(&f3), line_iterator()) == 3);
  assert(distance(line_iterator(&f4), line_iterator()) == 4);

  /*****************************************************************************
   * file_line_iterator
   */

  {
    recursive_directory_iterator rdi("test/simple");

    size_t count = 0;
    for (file_line_iterator it(&rdi), end; it != end; ++it)
      count++;
    assert(count == 7);
  }

  {
    recursive_directory_iterator rdi("data");
    size_t count = 0;
    for (file_line_iterator it(&rdi), end; it != end; ++it)
      count++;
    assert(count == 688892);
  }

  {
    vector<string> expected, actual;
    expected.push_back("coffee");
    expected.push_back("beer");
    expected.push_back("whiskey");
    expected.push_back("purple drank");
    expected.push_back("foo");
    expected.push_back("bar");
    expected.push_back("baz");

    recursive_directory_iterator rdi("test/simple");

    for (file_line_iterator it(&rdi), end; it != end; ++it)
      actual.push_back(*it);

    assert(expected == actual);
  }

  /*****************************************************************************
   * tuple_iterator
   */

  {
    recursive_directory_iterator rdi("test/subset");
    file_line_iterator fli(&rdi);

    size_t count = 0;
    for (tuple_iterator ti(&fli), end; ti != end; ++ti)
      count++;
    assert(count == 783);
  }

  {
    recursive_directory_iterator rdi("test/subset");
    file_line_iterator fli(&rdi);
    vector<string> tuples;

    for (tuple_iterator ti(&fli), end; ti != end; ++ti)
      tuples.push_back(*ti);

    assert(tuples[0] == "Pierre/NNP");
    assert(tuples[1] == "Vinken/NNP");
    assert(tuples[2] == ",/,");
    assert(tuples[3] == "61/CD");
    assert(tuples[4] == "years/NNS");
    assert(tuples[780] == "today/NN");
    assert(tuples[781] == "./.");
    assert(tuples[782] == "''/''");
  }

  /*****************************************************************************
   * sentence_iterator
   */

  {
    recursive_directory_iterator rdi("test/subset");
    file_line_iterator fli(&rdi);
    tuple_iterator ti(&fli);

    size_t count = 0;
    for (sentence_iterator si(&ti), end; si != end; ++si)
      count++;
    assert(count == 33);
  }

  {
    recursive_directory_iterator rdi("data");
    file_line_iterator fli(&rdi);
    tuple_iterator ti(&fli);

    size_t count = 0;
    for (sentence_iterator si(&ti), end; si != end; ++si)
      count++;

    assert(count == 45280);
  }

  // this test fails because we're not handling the case where closing quotes
  // come after a period. woldn't be too hard, but i don't know if it's worth
  // it.
  /* { */
  /*   recursive_directory_iterator rdi("data"); */
  /*   file_line_iterator fli(&rdi); */
  /*   tuple_iterator ti(&fli); */
  /*   vector<sentence> result; */

  /*   for (sentence_iterator si(&ti), end; si != end; ++si) */
  /*     result.push_back(*si); */

  /*   cout << "end: " << result.back().back().first << endl; */
  /*   assert(result.back().back().first == "''"); */
  /* } */
}

int memoryLeakTest() {
  while (true) {
    recursive_directory_iterator rdi("data");
    file_line_iterator fli(&rdi);
    tuple_iterator ti(&fli);

    for (sentence_iterator si(&ti), end; si != end; ++si) {}
  }

  return 0;
}

int main(int argc, char* argv[]) {
  char opt;
  bool memoryLeakTestFlag = false;

  while ((opt = getopt(argc, argv, "m")) != -1) {
    switch (opt) {
      case 'm':
        memoryLeakTestFlag = true;
        break;
      default: /* '?' */
        cerr << "USAGE: " << argv[0] << endl;
        exit(EXIT_FAILURE);
    }
  }

  if (memoryLeakTestFlag)
    return memoryLeakTest();

  run_tests();

  return 0;
}
<|endoftext|>


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

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// QT includes
#include <QChildEvent>
#include <QDebug>
#include <QDialogButtonBox>
#include <QEvent>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QListView>
#include <QPushButton>
#include <QTreeView>

// CTK includes
#include "ctkFileDialog.h"

//------------------------------------------------------------------------------
class ctkFileDialogPrivate
{
  Q_DECLARE_PUBLIC(ctkFileDialog);
protected:
  ctkFileDialog* const q_ptr;
public:
  ctkFileDialogPrivate(ctkFileDialog& object);
  void init();
  void observeAcceptButton();

  QPushButton* acceptButton()const;
  QListView* listView()const;
  QTreeView* treeView()const;

  bool AcceptButtonEnable;
  bool AcceptButtonState;
  bool IgnoreEvent;
  bool UsingNativeDialog;
};

//------------------------------------------------------------------------------
ctkFileDialogPrivate::ctkFileDialogPrivate(ctkFileDialog& object)
  :q_ptr(&object)
{
  this->IgnoreEvent = false;
  this->AcceptButtonEnable = true;
  this->AcceptButtonState = true;
  this->UsingNativeDialog = true;
}

//------------------------------------------------------------------------------
void ctkFileDialogPrivate::init()
{
  Q_Q(ctkFileDialog);
  this->UsingNativeDialog = !(q->options() & QFileDialog::DontUseNativeDialog);
  if (!(this->UsingNativeDialog))
  {
    this->observeAcceptButton();

    QObject::connect(this->listView()->selectionModel(),
                    SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
                    q, SLOT(onSelectionChanged()));
  }
}

//------------------------------------------------------------------------------
QPushButton* ctkFileDialogPrivate::acceptButton()const
{
  Q_Q(const ctkFileDialog);
  if (this->UsingNativeDialog)
  {
    return NULL;  // Native dialog does not supporting modifying or getting widget elements.
  }
  QDialogButtonBox* buttonBox = q->findChild<QDialogButtonBox*>();
  Q_ASSERT(buttonBox);
  QDialogButtonBox::StandardButton button =
    (q->acceptMode() == QFileDialog::AcceptOpen ? QDialogButtonBox::Open : QDialogButtonBox::Save);
  return buttonBox->button(button);
}

//------------------------------------------------------------------------------
QListView* ctkFileDialogPrivate::listView()const
{
  Q_Q(const ctkFileDialog);
  QListView* listView= q->findChild<QListView*>("listView");
  Q_ASSERT(listView);
  return listView;
}

//------------------------------------------------------------------------------
QTreeView* ctkFileDialogPrivate::treeView()const
{
  Q_Q(const ctkFileDialog);
  QTreeView* treeView = q->findChild<QTreeView*>();
  Q_ASSERT(treeView);
  return treeView;
}

//------------------------------------------------------------------------------
void ctkFileDialogPrivate::observeAcceptButton()
{
  Q_Q(ctkFileDialog);
  QPushButton* button = this->acceptButton();
  Q_ASSERT(button);
  this->AcceptButtonState =
    button->isEnabledTo(qobject_cast<QWidget*>(button->parent()));
  // TODO: catching the event of the enable state is not enough, if the user
  // double click on the file, the dialog will be accepted, that event should
  // be intercepted as well
  button->installEventFilter(q);
}

//------------------------------------------------------------------------------
ctkFileDialog::ctkFileDialog(QWidget *parentWidget,
              const QString &caption,
              const QString &directory,
              const QString &filter)
  :QFileDialog(parentWidget, caption, directory, filter)
  , d_ptr(new ctkFileDialogPrivate(*this))
{
  Q_D(ctkFileDialog);

  d->init();
}

//------------------------------------------------------------------------------
ctkFileDialog::~ctkFileDialog()
{
}

//------------------------------------------------------------------------------
void ctkFileDialog::setBottomWidget(QWidget* widget, const QString& label)
{
  Q_D(ctkFileDialog);
  if (d->UsingNativeDialog)
  {
    return;  // Native dialog does not supporting modifying or getting widget elements.
  }
  QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout());
  QWidget* oldBottomWidget = this->bottomWidget();
  // remove the old widget from the layout if any
  if (oldBottomWidget)
    {
    if (oldBottomWidget == widget)
      {
      return;
      }
    gridLayout->removeWidget(oldBottomWidget);
    delete oldBottomWidget;
    }
  if (widget == 0)
    {
    return;
    }
  if (!label.isEmpty())
    {
    gridLayout->addWidget(new QLabel(label), 4, 0);
    gridLayout->addWidget(widget,4, 1,1, 1);
    }
  else
    {
    gridLayout->addWidget(widget,4, 0,1, 2);
    }
  // The dialog button box is no longer spanned on 2 rows but on 3 rows if
  // there is a "bottom widget"
  QDialogButtonBox* buttonBox = this->findChild<QDialogButtonBox*>();
  Q_ASSERT(buttonBox);
  gridLayout->removeWidget(buttonBox);
  gridLayout->addWidget(buttonBox, 2, 2, widget ? 3 : 2, 1);
}

//------------------------------------------------------------------------------
QWidget* ctkFileDialog::bottomWidget()const
{
  QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout());
  QLayoutItem* item = gridLayout ? gridLayout->itemAtPosition(4,1) : NULL;
  return item ? item->widget() : 0;
}

//------------------------------------------------------------------------------
void ctkFileDialog::setSelectionMode(QAbstractItemView::SelectionMode mode)
{
  Q_D(ctkFileDialog);
  if (d->UsingNativeDialog)
  {
    return;  // Native dialog does not support modifying or getting widget elements.
  }
  foreach(QAbstractItemView* view, QList<QAbstractItemView*>()
          << d->listView()
          << d->treeView()
          )
    {
    view->setSelectionMode(mode);
    }
}

//------------------------------------------------------------------------------
QAbstractItemView::SelectionMode ctkFileDialog::selectionMode() const
{
  Q_D(const ctkFileDialog);
  return d->listView()->selectionMode();
}

//------------------------------------------------------------------------------
void ctkFileDialog::clearSelection()
{
  Q_D(ctkFileDialog);
  foreach(QAbstractItemView* view, QList<QAbstractItemView*>()
          << d->listView()
          << d->treeView()
          )
    {
    view->clearSelection();
    }
}

//------------------------------------------------------------------------------
void ctkFileDialog::setAcceptButtonEnable(bool enable)
{
  Q_D(ctkFileDialog);
  d->AcceptButtonEnable = enable;
  d->IgnoreEvent = true;
  d->acceptButton()->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState);
  d->IgnoreEvent = false;
}

//------------------------------------------------------------------------------
bool ctkFileDialog::eventFilter(QObject *obj, QEvent *event)
{
  Q_D(ctkFileDialog);
  QPushButton* button = d->acceptButton();
  QDialogButtonBox* dialogButtonBox = qobject_cast<QDialogButtonBox*>(obj);
  if (obj == button && event->type() == QEvent::EnabledChange &&
      !d->IgnoreEvent)
    {
    d->IgnoreEvent = true;
    d->AcceptButtonState = button->isEnabledTo(qobject_cast<QWidget*>(button->parent()));
    button->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState);
    d->IgnoreEvent = false;
    }
  else if (obj == button && event->type() == QEvent::Destroy)
    {
    // The accept button is deleted probably because setAcceptMode() is being called.
    // observe the parent to check when the accept button is added back
    obj->parent()->installEventFilter(this);
    }
  else if (dialogButtonBox && event->type() == QEvent::ChildAdded)
    {
    dynamic_cast<QChildEvent*>(event)->child()->installEventFilter(this);
    }
  return QFileDialog::eventFilter(obj, event);
}

//------------------------------------------------------------------------------
void ctkFileDialog::onSelectionChanged()
{
  emit this->fileSelectionChanged(this->selectedFiles());
}

//------------------------------------------------------------------------------
void ctkFileDialog::accept()
{
  QLineEdit* fileNameEdit = qobject_cast<QLineEdit*>(this->sender());
  if (fileNameEdit)
    {
    QFileInfo info(fileNameEdit->text());
    if (info.isDir())
      {
      setDirectory(info.absoluteFilePath());
      return;
      }
    }
  // Don't accept read-only directories if we are in AcceptSave mode.
  if ((this->fileMode() == Directory) &&
      this->acceptMode() == AcceptSave)
    {
    QStringList files = this->selectedFiles();
    QString fn = files.first();
    QFileInfo info(fn);
    if (info.isDir() && !info.isWritable())
      {
      this->setDirectory(info.absoluteFilePath());
      return;
      }
    }
  this->Superclass::accept();
}
<commit_msg>STYLE: Remove extra parenthesis around logic<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// QT includes
#include <QChildEvent>
#include <QDebug>
#include <QDialogButtonBox>
#include <QEvent>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QListView>
#include <QPushButton>
#include <QTreeView>

// CTK includes
#include "ctkFileDialog.h"

//------------------------------------------------------------------------------
class ctkFileDialogPrivate
{
  Q_DECLARE_PUBLIC(ctkFileDialog);
protected:
  ctkFileDialog* const q_ptr;
public:
  ctkFileDialogPrivate(ctkFileDialog& object);
  void init();
  void observeAcceptButton();

  QPushButton* acceptButton()const;
  QListView* listView()const;
  QTreeView* treeView()const;

  bool AcceptButtonEnable;
  bool AcceptButtonState;
  bool IgnoreEvent;
  bool UsingNativeDialog;
};

//------------------------------------------------------------------------------
ctkFileDialogPrivate::ctkFileDialogPrivate(ctkFileDialog& object)
  :q_ptr(&object)
{
  this->IgnoreEvent = false;
  this->AcceptButtonEnable = true;
  this->AcceptButtonState = true;
  this->UsingNativeDialog = true;
}

//------------------------------------------------------------------------------
void ctkFileDialogPrivate::init()
{
  Q_Q(ctkFileDialog);
  this->UsingNativeDialog = !(q->options() & QFileDialog::DontUseNativeDialog);
  if (!this->UsingNativeDialog)
  {
    this->observeAcceptButton();

    QObject::connect(this->listView()->selectionModel(),
                    SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
                    q, SLOT(onSelectionChanged()));
  }
}

//------------------------------------------------------------------------------
QPushButton* ctkFileDialogPrivate::acceptButton()const
{
  Q_Q(const ctkFileDialog);
  if (this->UsingNativeDialog)
  {
    return NULL;  // Native dialog does not supporting modifying or getting widget elements.
  }
  QDialogButtonBox* buttonBox = q->findChild<QDialogButtonBox*>();
  Q_ASSERT(buttonBox);
  QDialogButtonBox::StandardButton button =
    (q->acceptMode() == QFileDialog::AcceptOpen ? QDialogButtonBox::Open : QDialogButtonBox::Save);
  return buttonBox->button(button);
}

//------------------------------------------------------------------------------
QListView* ctkFileDialogPrivate::listView()const
{
  Q_Q(const ctkFileDialog);
  QListView* listView= q->findChild<QListView*>("listView");
  Q_ASSERT(listView);
  return listView;
}

//------------------------------------------------------------------------------
QTreeView* ctkFileDialogPrivate::treeView()const
{
  Q_Q(const ctkFileDialog);
  QTreeView* treeView = q->findChild<QTreeView*>();
  Q_ASSERT(treeView);
  return treeView;
}

//------------------------------------------------------------------------------
void ctkFileDialogPrivate::observeAcceptButton()
{
  Q_Q(ctkFileDialog);
  QPushButton* button = this->acceptButton();
  Q_ASSERT(button);
  this->AcceptButtonState =
    button->isEnabledTo(qobject_cast<QWidget*>(button->parent()));
  // TODO: catching the event of the enable state is not enough, if the user
  // double click on the file, the dialog will be accepted, that event should
  // be intercepted as well
  button->installEventFilter(q);
}

//------------------------------------------------------------------------------
ctkFileDialog::ctkFileDialog(QWidget *parentWidget,
              const QString &caption,
              const QString &directory,
              const QString &filter)
  :QFileDialog(parentWidget, caption, directory, filter)
  , d_ptr(new ctkFileDialogPrivate(*this))
{
  Q_D(ctkFileDialog);

  d->init();
}

//------------------------------------------------------------------------------
ctkFileDialog::~ctkFileDialog()
{
}

//------------------------------------------------------------------------------
void ctkFileDialog::setBottomWidget(QWidget* widget, const QString& label)
{
  Q_D(ctkFileDialog);
  if (d->UsingNativeDialog)
  {
    return;  // Native dialog does not supporting modifying or getting widget elements.
  }
  QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout());
  QWidget* oldBottomWidget = this->bottomWidget();
  // remove the old widget from the layout if any
  if (oldBottomWidget)
    {
    if (oldBottomWidget == widget)
      {
      return;
      }
    gridLayout->removeWidget(oldBottomWidget);
    delete oldBottomWidget;
    }
  if (widget == 0)
    {
    return;
    }
  if (!label.isEmpty())
    {
    gridLayout->addWidget(new QLabel(label), 4, 0);
    gridLayout->addWidget(widget,4, 1,1, 1);
    }
  else
    {
    gridLayout->addWidget(widget,4, 0,1, 2);
    }
  // The dialog button box is no longer spanned on 2 rows but on 3 rows if
  // there is a "bottom widget"
  QDialogButtonBox* buttonBox = this->findChild<QDialogButtonBox*>();
  Q_ASSERT(buttonBox);
  gridLayout->removeWidget(buttonBox);
  gridLayout->addWidget(buttonBox, 2, 2, widget ? 3 : 2, 1);
}

//------------------------------------------------------------------------------
QWidget* ctkFileDialog::bottomWidget()const
{
  QGridLayout* gridLayout = qobject_cast<QGridLayout*>(this->layout());
  QLayoutItem* item = gridLayout ? gridLayout->itemAtPosition(4,1) : NULL;
  return item ? item->widget() : 0;
}

//------------------------------------------------------------------------------
void ctkFileDialog::setSelectionMode(QAbstractItemView::SelectionMode mode)
{
  Q_D(ctkFileDialog);
  if (d->UsingNativeDialog)
  {
    return;  // Native dialog does not support modifying or getting widget elements.
  }
  foreach(QAbstractItemView* view, QList<QAbstractItemView*>()
          << d->listView()
          << d->treeView()
          )
    {
    view->setSelectionMode(mode);
    }
}

//------------------------------------------------------------------------------
QAbstractItemView::SelectionMode ctkFileDialog::selectionMode() const
{
  Q_D(const ctkFileDialog);
  return d->listView()->selectionMode();
}

//------------------------------------------------------------------------------
void ctkFileDialog::clearSelection()
{
  Q_D(ctkFileDialog);
  foreach(QAbstractItemView* view, QList<QAbstractItemView*>()
          << d->listView()
          << d->treeView()
          )
    {
    view->clearSelection();
    }
}

//------------------------------------------------------------------------------
void ctkFileDialog::setAcceptButtonEnable(bool enable)
{
  Q_D(ctkFileDialog);
  d->AcceptButtonEnable = enable;
  d->IgnoreEvent = true;
  d->acceptButton()->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState);
  d->IgnoreEvent = false;
}

//------------------------------------------------------------------------------
bool ctkFileDialog::eventFilter(QObject *obj, QEvent *event)
{
  Q_D(ctkFileDialog);
  QPushButton* button = d->acceptButton();
  QDialogButtonBox* dialogButtonBox = qobject_cast<QDialogButtonBox*>(obj);
  if (obj == button && event->type() == QEvent::EnabledChange &&
      !d->IgnoreEvent)
    {
    d->IgnoreEvent = true;
    d->AcceptButtonState = button->isEnabledTo(qobject_cast<QWidget*>(button->parent()));
    button->setEnabled(d->AcceptButtonEnable && d->AcceptButtonState);
    d->IgnoreEvent = false;
    }
  else if (obj == button && event->type() == QEvent::Destroy)
    {
    // The accept button is deleted probably because setAcceptMode() is being called.
    // observe the parent to check when the accept button is added back
    obj->parent()->installEventFilter(this);
    }
  else if (dialogButtonBox && event->type() == QEvent::ChildAdded)
    {
    dynamic_cast<QChildEvent*>(event)->child()->installEventFilter(this);
    }
  return QFileDialog::eventFilter(obj, event);
}

//------------------------------------------------------------------------------
void ctkFileDialog::onSelectionChanged()
{
  emit this->fileSelectionChanged(this->selectedFiles());
}

//------------------------------------------------------------------------------
void ctkFileDialog::accept()
{
  QLineEdit* fileNameEdit = qobject_cast<QLineEdit*>(this->sender());
  if (fileNameEdit)
    {
    QFileInfo info(fileNameEdit->text());
    if (info.isDir())
      {
      setDirectory(info.absoluteFilePath());
      return;
      }
    }
  // Don't accept read-only directories if we are in AcceptSave mode.
  if ((this->fileMode() == Directory) &&
      this->acceptMode() == AcceptSave)
    {
    QStringList files = this->selectedFiles();
    QString fn = files.first();
    QFileInfo info(fn);
    if (info.isDir() && !info.isWritable())
      {
      this->setDirectory(info.absoluteFilePath());
      return;
      }
    }
  this->Superclass::accept();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stddef.h>
#include <libpstack/dwarf.h>
#include <libpstack/proc.h>
#include <python2.7/Python.h>
#include <python2.7/frameobject.h>

Elf_Addr
doPyThread(Process &proc, std::ostream &os, Elf_Addr ptr)
{
    PyThreadState state;
    proc.io->readObj(ptr, &state);
    PyFrameObject frame;
    os << "\tthread " << ptr << std::endl;
    for (Elf_Addr framePtr = reinterpret_cast<Elf_Addr>(state.frame);
            framePtr != 0;
            framePtr = reinterpret_cast<Elf_Addr>(frame.f_back)) {
        proc.io->readObj(framePtr, &frame);
        PyCodeObject code;
        PyStringObject function;
        proc.io->readObj(reinterpret_cast<Elf_Addr>(frame.f_code), &code);
        auto func = proc.io->readString(reinterpret_cast<Elf_Addr>(code.co_name) + offsetof(PyStringObject, ob_sval));
        auto file = proc.io->readString(reinterpret_cast<Elf_Addr>(code.co_filename) + offsetof(PyStringObject, ob_sval));
        os << "\t\t" << func << " in " << file << ":" << frame.f_lineno << "\n";
    }
    return reinterpret_cast<Elf_Addr>(state.next);
}

Elf32_Addr
doPyInterp(Process &proc, std::ostream &os, Elf_Addr ptr)
{
    PyInterpreterState state;
    proc.io->readObj(ptr, &state);
    os << "interpreter " << ptr << std::endl;
    for (Elf_Addr tsp = reinterpret_cast<Elf_Addr>(state.tstate_head); tsp; ) {
        tsp = doPyThread(proc, os, tsp);
    }
    return reinterpret_cast<Elf_Addr>(state.next);
}
    /*
    PyThreadState *tstate = PyThreadState_GET();
    if (nullptr != tstate && nullptr != tstate->frame) {
	PyFrameObject *frame = tstate->frame;

	printf("Python stack trace:\n");
	while (nullptr != frame) {
	    // int line = frame->f_lineno;
	    int line = PyCode_Addr2Line(frame->f_code, frame->f_lasti);
	    const char *filename = PyString_AsString(frame->f_code->co_filename);
	    const char *funcname = PyString_AsString(frame->f_code->co_name);
	    printf("    %s(%d): %s\n", filename, line, funcname);
	    frame = frame->f_back;
	}
    }
*/

std::ostream &
pythonStack(Process &proc, std::ostream &os, const PstackOptions &)
{
    // Find the python library.
    for (auto &o : proc.objects) {
        std::string module = stringify(*o.object->io);
        if (module.find("python") != std::string::npos) {
            auto dwarf = proc.imageCache.getDwarf(ElfObject::getDebug(o.object));
            if (dwarf) {
                std::clog << "searching  " << module << std::endl;
                for (auto u : dwarf->getUnits()) {
                    for (const DwarfEntry *compile : u->entries) {
                        if (compile->type->tag == DW_TAG_compile_unit) {
                            for (const DwarfEntry *var : compile->children) {
                                if (var->type->tag == DW_TAG_variable && var->name() == "interp_head") {
                                    DwarfExpressionStack evalStack;
                                    auto addr = evalStack.eval(proc, var->attrForName(DW_AT_location), 0, o.reloc);
                                    Elf_Addr ptr;
                                    for (proc.io->readObj(addr, &ptr); ptr; ) {
                                        ptr = doPyInterp(proc, os, ptr);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    return os;
}

<commit_msg>Remove junk<commit_after>#include <iostream>
#include <stddef.h>
#include <libpstack/dwarf.h>
#include <libpstack/proc.h>
#include <python2.7/Python.h>
#include <python2.7/frameobject.h>

Elf_Addr
doPyThread(Process &proc, std::ostream &os, Elf_Addr ptr)
{
    PyThreadState state;
    proc.io->readObj(ptr, &state);
    PyFrameObject frame;
    os << "\tthread " << ptr << std::endl;
    for (Elf_Addr framePtr = reinterpret_cast<Elf_Addr>(state.frame);
            framePtr != 0;
            framePtr = reinterpret_cast<Elf_Addr>(frame.f_back)) {
        proc.io->readObj(framePtr, &frame);
        PyCodeObject code;
        PyStringObject function;
        proc.io->readObj(reinterpret_cast<Elf_Addr>(frame.f_code), &code);
        auto func = proc.io->readString(reinterpret_cast<Elf_Addr>(code.co_name) + offsetof(PyStringObject, ob_sval));
        auto file = proc.io->readString(reinterpret_cast<Elf_Addr>(code.co_filename) + offsetof(PyStringObject, ob_sval));
        os << "\t\t" << func << " in " << file << ":" << frame.f_lineno << "\n";
    }
    return reinterpret_cast<Elf_Addr>(state.next);
}

Elf32_Addr
doPyInterp(Process &proc, std::ostream &os, Elf_Addr ptr)
{
    PyInterpreterState state;
    proc.io->readObj(ptr, &state);
    os << "interpreter " << ptr << std::endl;
    for (Elf_Addr tsp = reinterpret_cast<Elf_Addr>(state.tstate_head); tsp; ) {
        tsp = doPyThread(proc, os, tsp);
    }
    return reinterpret_cast<Elf_Addr>(state.next);
}

std::ostream &
pythonStack(Process &proc, std::ostream &os, const PstackOptions &)
{
    // Find the python library.
    for (auto &o : proc.objects) {
        std::string module = stringify(*o.object->io);
        if (module.find("python") != std::string::npos) {
            auto dwarf = proc.imageCache.getDwarf(ElfObject::getDebug(o.object));
            if (dwarf) {
                for (auto u : dwarf->getUnits()) {
                    for (const DwarfEntry *compile : u->entries) {
                        if (compile->type->tag == DW_TAG_compile_unit) {
                            for (const DwarfEntry *var : compile->children) {
                                if (var->type->tag == DW_TAG_variable && var->name() == "interp_head") {
                                    DwarfExpressionStack evalStack;
                                    auto addr = evalStack.eval(proc, var->attrForName(DW_AT_location), 0, o.reloc);
                                    Elf_Addr ptr;
                                    for (proc.io->readObj(addr, &ptr); ptr; ) {
                                        ptr = doPyInterp(proc, os, ptr);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    return os;
}

<|endoftext|>


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

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QApplication>
#include <QPointer>
#include <QStyleFactory>

// CTK includes
#include "ctkProxyStyle.h"

// ----------------------------------------------------------------------------
class ctkProxyStylePrivate
{
  Q_DECLARE_PUBLIC(ctkProxyStyle)
protected:
  ctkProxyStyle* const q_ptr;
public:
  void setProxyStyle(QProxyStyle* proxy, QStyle *style)const;
  void setBaseStyle(QProxyStyle* proxyStyle, QStyle* baseStyle)const;
private:
  ctkProxyStylePrivate(ctkProxyStyle& object);
  mutable bool InEnsureBaseStyle;
  mutable QPointer <QStyle> baseStyle;
};

// ----------------------------------------------------------------------------
ctkProxyStylePrivate::ctkProxyStylePrivate(ctkProxyStyle& object)
  : q_ptr(&object)
  , InEnsureBaseStyle(false)
{
}

// ----------------------------------------------------------------------------
void ctkProxyStylePrivate::setProxyStyle(QProxyStyle* proxy, QStyle *style)const
{
  if (style->proxy() == proxy)
    {
    return;
    }
  this->setBaseStyle(proxy, style);
}
// ----------------------------------------------------------------------------
void ctkProxyStylePrivate::setBaseStyle(QProxyStyle* proxy, QStyle *style)const
{
  if (proxy->baseStyle() == style &&
      style->proxy() == proxy)
    {
    return;
    }
  QObject* parent = style->parent();
  QStyle* oldStyle = proxy->baseStyle();
  QObject* oldParent = oldStyle ? oldStyle->parent() : 0;
  if (oldParent == proxy)
    {
    oldStyle->setParent(0);// make sure setBaseStyle doesn't delete baseStyle
    }
  proxy->setBaseStyle(style);
  style->setParent(parent);
  if (oldParent == proxy)
    {
    oldStyle->setParent(oldParent);
    }
  //if (style == qApp->style())
  //  {
  //  style->setParent(qApp); // don't delete the application style.
  //  }
}

// ----------------------------------------------------------------------------
ctkProxyStyle::ctkProxyStyle(QStyle *style)
  : d_ptr(new ctkProxyStylePrivate(*this))
{
  Q_D(ctkProxyStyle);
  d->baseStyle = style;
  this->setBaseStyle(style);
}

// ----------------------------------------------------------------------------
ctkProxyStyle::~ctkProxyStyle()
{
  Q_D(ctkProxyStyle);
  if (d->baseStyle == qApp->style())
    {
    d->baseStyle->setParent(qApp); // don't delete the application style.
    }
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::ensureBaseStyle() const
{
  Q_D(const ctkProxyStyle);
  d->baseStyle = this->baseStyle();
  if (d->InEnsureBaseStyle)
    {
    //return;
    }
  d->InEnsureBaseStyle = true;
  // Set the proxy to the entire hierarchy.
  QProxyStyle* proxyStyle = const_cast<QProxyStyle*>(qobject_cast<const QProxyStyle*>(
    this->proxy() ? this->proxy() : this));
  QStyle* proxyBaseStyle = proxyStyle->baseStyle(); // calls ensureBaseStyle
  QStyle* baseStyle = proxyBaseStyle;
  while (baseStyle)
    {
    d->setProxyStyle(proxyStyle, baseStyle);// set proxy on itself to all children
    QProxyStyle* proxy = qobject_cast<QProxyStyle*>(baseStyle);
    baseStyle = proxy ? proxy->baseStyle() : 0;
    }
  d->setBaseStyle(proxyStyle, proxyBaseStyle);
  d->InEnsureBaseStyle = false;
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->drawPrimitive(element, option, painter, widget);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->drawControl(element, option, painter, widget);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->drawComplexControl(control, option, painter, widget);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::drawItemText(QPainter *painter, const QRect &rect, int flags, const QPalette &pal, bool enabled,
                               const QString &text, QPalette::ColorRole textRole) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->drawItemText(painter, rect, flags, pal, enabled, text, textRole);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, const QPixmap &pixmap) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->drawItemPixmap(painter, rect, alignment, pixmap);
}

// ----------------------------------------------------------------------------
QSize ctkProxyStyle::sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->sizeFromContents(type, option, size, widget);
}

// ----------------------------------------------------------------------------
QRect ctkProxyStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->subElementRect(element, option, widget);
}

// ----------------------------------------------------------------------------
QRect ctkProxyStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *option, SubControl sc, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->subControlRect(cc, option, sc, widget);
}

// ----------------------------------------------------------------------------
QRect ctkProxyStyle::itemTextRect(const QFontMetrics &fm, const QRect &r, int flags, bool enabled, const QString &text) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->itemTextRect(fm, r, flags, enabled, text);
}

// ----------------------------------------------------------------------------
QRect ctkProxyStyle::itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->itemPixmapRect(r, flags, pixmap);
}

// ----------------------------------------------------------------------------
QStyle::SubControl ctkProxyStyle::hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option, const QPoint &pos, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->hitTestComplexControl(control, option, pos, widget);
}

// ----------------------------------------------------------------------------
int ctkProxyStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->styleHint(hint, option, widget, returnData);
}

// ----------------------------------------------------------------------------
int ctkProxyStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->pixelMetric(metric, option, widget);
}

// ----------------------------------------------------------------------------
QPixmap ctkProxyStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->standardPixmap(standardPixmap, opt, widget);
}

// ----------------------------------------------------------------------------
QPixmap ctkProxyStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *opt) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->generatedIconPixmap(iconMode, pixmap, opt);
}

// ----------------------------------------------------------------------------
QPalette ctkProxyStyle::standardPalette() const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->standardPalette();
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::polish(QWidget *widget)
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->polish(widget);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::polish(QPalette &pal)
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->polish(pal);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::polish(QApplication *app)
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->polish(app);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::unpolish(QWidget *widget)
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->unpolish(widget);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::unpolish(QApplication *app)
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->unpolish(app);
}

// ----------------------------------------------------------------------------
bool ctkProxyStyle::event(QEvent *e)
{
    Q_D(const ctkProxyStyle);
    if (e->type() != QEvent::ParentChange &&
        e->type() != QEvent::ChildRemoved &&
        e->type() != QEvent::ChildAdded)
      {
      this->ensureBaseStyle();
      }
    return !d->baseStyle.isNull() ? d->baseStyle->event(e) : false;
}

// ----------------------------------------------------------------------------
QIcon ctkProxyStyle::standardIconImplementation(StandardPixmap standardIcon,
                                              const QStyleOption *option,
                                              const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->standardIcon(standardIcon, option, widget);
}

// ----------------------------------------------------------------------------
int ctkProxyStyle::layoutSpacingImplementation(QSizePolicy::ControlType control1,
                                             QSizePolicy::ControlType control2,
                                             Qt::Orientation orientation,
                                             const QStyleOption *option,
                                             const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->layoutSpacing(control1, control2, orientation, option, widget);
}
<commit_msg>Cleanup ctkProxyStyle unused variable/code<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QApplication>
#include <QPointer>
#include <QStyleFactory>

// CTK includes
#include "ctkProxyStyle.h"

// ----------------------------------------------------------------------------
class ctkProxyStylePrivate
{
  Q_DECLARE_PUBLIC(ctkProxyStyle)
protected:
  ctkProxyStyle* const q_ptr;
public:
  void setProxyStyle(QProxyStyle* proxy, QStyle *style)const;
  void setBaseStyle(QProxyStyle* proxyStyle, QStyle* baseStyle)const;
private:
  ctkProxyStylePrivate(ctkProxyStyle& object);
  mutable QPointer <QStyle> baseStyle;
};

// ----------------------------------------------------------------------------
ctkProxyStylePrivate::ctkProxyStylePrivate(ctkProxyStyle& object)
  : q_ptr(&object)
{
}

// ----------------------------------------------------------------------------
void ctkProxyStylePrivate::setProxyStyle(QProxyStyle* proxy, QStyle *style)const
{
  if (style->proxy() == proxy)
    {
    return;
    }
  this->setBaseStyle(proxy, style);
}
// ----------------------------------------------------------------------------
void ctkProxyStylePrivate::setBaseStyle(QProxyStyle* proxy, QStyle *style)const
{
  if (proxy->baseStyle() == style &&
      style->proxy() == proxy)
    {
    return;
    }
  QObject* parent = style->parent();
  QStyle* oldStyle = proxy->baseStyle();
  QObject* oldParent = oldStyle ? oldStyle->parent() : 0;
  if (oldParent == proxy)
    {
    oldStyle->setParent(0);// make sure setBaseStyle doesn't delete baseStyle
    }
  proxy->setBaseStyle(style);
  style->setParent(parent);
  if (oldParent == proxy)
    {
    oldStyle->setParent(oldParent);
    }
}

// ----------------------------------------------------------------------------
ctkProxyStyle::ctkProxyStyle(QStyle *style)
  : d_ptr(new ctkProxyStylePrivate(*this))
{
  Q_D(ctkProxyStyle);
  d->baseStyle = style;
  this->setBaseStyle(style);
}

// ----------------------------------------------------------------------------
ctkProxyStyle::~ctkProxyStyle()
{
  Q_D(ctkProxyStyle);
  if (d->baseStyle == qApp->style())
    {
    d->baseStyle->setParent(qApp); // don't delete the application style.
    }
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::ensureBaseStyle() const
{
  Q_D(const ctkProxyStyle);
  d->baseStyle = this->baseStyle();
  // Set the proxy to the entire hierarchy.
  QProxyStyle* proxyStyle = const_cast<QProxyStyle*>(qobject_cast<const QProxyStyle*>(
    this->proxy() ? this->proxy() : this));
  QStyle* proxyBaseStyle = proxyStyle->baseStyle(); // calls ensureBaseStyle
  QStyle* baseStyle = proxyBaseStyle;
  while (baseStyle)
    {
    d->setProxyStyle(proxyStyle, baseStyle);// set proxy on itself to all children
    QProxyStyle* proxy = qobject_cast<QProxyStyle*>(baseStyle);
    baseStyle = proxy ? proxy->baseStyle() : 0;
    }
  d->setBaseStyle(proxyStyle, proxyBaseStyle);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->drawPrimitive(element, option, painter, widget);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->drawControl(element, option, painter, widget);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->drawComplexControl(control, option, painter, widget);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::drawItemText(QPainter *painter, const QRect &rect, int flags, const QPalette &pal, bool enabled,
                               const QString &text, QPalette::ColorRole textRole) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->drawItemText(painter, rect, flags, pal, enabled, text, textRole);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, const QPixmap &pixmap) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->drawItemPixmap(painter, rect, alignment, pixmap);
}

// ----------------------------------------------------------------------------
QSize ctkProxyStyle::sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->sizeFromContents(type, option, size, widget);
}

// ----------------------------------------------------------------------------
QRect ctkProxyStyle::subElementRect(SubElement element, const QStyleOption *option, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->subElementRect(element, option, widget);
}

// ----------------------------------------------------------------------------
QRect ctkProxyStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *option, SubControl sc, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->subControlRect(cc, option, sc, widget);
}

// ----------------------------------------------------------------------------
QRect ctkProxyStyle::itemTextRect(const QFontMetrics &fm, const QRect &r, int flags, bool enabled, const QString &text) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->itemTextRect(fm, r, flags, enabled, text);
}

// ----------------------------------------------------------------------------
QRect ctkProxyStyle::itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->itemPixmapRect(r, flags, pixmap);
}

// ----------------------------------------------------------------------------
QStyle::SubControl ctkProxyStyle::hitTestComplexControl(ComplexControl control, const QStyleOptionComplex *option, const QPoint &pos, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->hitTestComplexControl(control, option, pos, widget);
}

// ----------------------------------------------------------------------------
int ctkProxyStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->styleHint(hint, option, widget, returnData);
}

// ----------------------------------------------------------------------------
int ctkProxyStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->pixelMetric(metric, option, widget);
}

// ----------------------------------------------------------------------------
QPixmap ctkProxyStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt, const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->standardPixmap(standardPixmap, opt, widget);
}

// ----------------------------------------------------------------------------
QPixmap ctkProxyStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *opt) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->generatedIconPixmap(iconMode, pixmap, opt);
}

// ----------------------------------------------------------------------------
QPalette ctkProxyStyle::standardPalette() const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->standardPalette();
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::polish(QWidget *widget)
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->polish(widget);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::polish(QPalette &pal)
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->polish(pal);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::polish(QApplication *app)
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->polish(app);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::unpolish(QWidget *widget)
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->unpolish(widget);
}

// ----------------------------------------------------------------------------
void ctkProxyStyle::unpolish(QApplication *app)
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    d->baseStyle->unpolish(app);
}

// ----------------------------------------------------------------------------
bool ctkProxyStyle::event(QEvent *e)
{
    Q_D(const ctkProxyStyle);
    if (e->type() != QEvent::ParentChange &&
        e->type() != QEvent::ChildRemoved &&
        e->type() != QEvent::ChildAdded)
      {
      this->ensureBaseStyle();
      }
    return !d->baseStyle.isNull() ? d->baseStyle->event(e) : false;
}

// ----------------------------------------------------------------------------
QIcon ctkProxyStyle::standardIconImplementation(StandardPixmap standardIcon,
                                              const QStyleOption *option,
                                              const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->standardIcon(standardIcon, option, widget);
}

// ----------------------------------------------------------------------------
int ctkProxyStyle::layoutSpacingImplementation(QSizePolicy::ControlType control1,
                                             QSizePolicy::ControlType control2,
                                             Qt::Orientation orientation,
                                             const QStyleOption *option,
                                             const QWidget *widget) const
{
    Q_D(const ctkProxyStyle);
    this->ensureBaseStyle();
    return d->baseStyle->layoutSpacing(control1, control2, orientation, option, widget);
}
<|endoftext|>


<commit_before>/*!
  \file main.cpp
  \author Sho Ikeda

  Copyright (c) 2015-2018 Sho Ikeda
  This software is released under the MIT License.
  http://opensource.org/licenses/mit-license.php
  */

// Standard C++ library
#include <cstdlib>
#include <functional>
#include <memory>
// Qt
#ifdef QT_WIDGETS_LIB
#include <QApplication>
#else // QT_WIDGETS_LIB
#include <QGuiApplication>
#endif // QT_WIDGETS_LIB
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QDateTime>
#include <QDir>
#include <QFileInfo>
#include <QFont>
#include <QGuiApplication>
#include <QScopedPointer>
#include <QString>
#include <QtGlobal>
#include <QQmlApplicationEngine>
#include <QUrl>
// Zisc
#include "zisc/error.hpp"
#include "zisc/utility.hpp"
// Nanairo
#include "NanairoCore/nanairo_core_config.hpp"
#include "NanairoGui/gui_engine.hpp"
#include "NanairoGui/nanairo_gui_config.hpp"
#include "NanairoGui/Renderer/cui_renderer_manager.hpp"
#include "NanairoGui/Renderer/scene_document.hpp"

namespace {

/*!
  */
enum class RendererManagerType
{
  kCui,
  kGui
};

/*!
  */
struct NanairoParameters
{
  QString scene_file_path_;
  QString output_path_;
  RendererManagerType manager_type_ = RendererManagerType::kGui;
  bool is_saving_scene_binary_enabled_ = false;
};

//! Initialize Qt settings
void initQt() noexcept;

//! Process command-line parameters
std::unique_ptr<NanairoParameters> processCommandLine(
    const QCoreApplication& application) noexcept;

//! Make a renderer runner
std::function<int ()> makeRenderRunner(
    const QCoreApplication& application,
    const NanairoParameters& parameters) noexcept;

} // namespace

/*!
  \details
  No detailed.
  */
int main(int argc, char** argv)
{
  // Initialize application
  QScopedPointer<QGuiApplication> application{
#ifdef QT_WIDGETS_LIB
    new QApplication{argc, argv}
#else // QT_WIDGETS_LIB
    new QGuiApplication{argc, argv}
#endif // QT_WIDGETS_LIB
    };
  initQt();

  // Parse command line arguments
  const auto parameters = processCommandLine(*application);
  // Make a render runner
  const auto render_runner = makeRenderRunner(*application, *parameters);
  // Launch render runner
  return render_runner();
}

namespace {

/*!
  */
void initQt() noexcept
{
  // Application info
  QGuiApplication::setApplicationName(
      nanairo::GuiConfig::applicationName().c_str());
  QGuiApplication::setApplicationVersion(
      nanairo::CoreConfig::versionString().c_str());

  // Qt properties
  QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

  // Random seed
  {
    const qint64 time = QDateTime::currentMSecsSinceEpoch();
    const qint32* array = zisc::treatAs<const qint32*>(&time);
    const qint32 seed = std::abs(array[0] ^ array[1]);
    qsrand(zisc::cast<uint>(seed));
  }
}

/*!
  \details
  No detailed.
  */
std::unique_ptr<NanairoParameters> processCommandLine(
    const QCoreApplication& application) noexcept
{
  QCommandLineParser parser;

  // Application description
  const auto application_description = QStringLiteral(
      "Nanairo is a physically plausible spectral renderer.");
  parser.setApplicationDescription(application_description);

  // Help and version setting
  parser.addHelpOption();
  parser.addVersionOption();

  // Options
  // Rendering mode
  QCommandLineOption renderer_mode_option{
      {"r", "renderermode"},
      "Choose gui/cui renderer to run.",
      "mode",
      "gui"};
  parser.addOption(renderer_mode_option);
  // Working directory
  QCommandLineOption working_directory_option{
      {"w", "workingdirectory"},
      "Set the current working directory of Nanairo application.",
      "path"};
  parser.addOption(working_directory_option);
  // Scene file
  QCommandLineOption scene_file_path_option{
      {"s", "scenefile"},
      "Specify the rendering scene for cui rendering.",
      "path",
      ":/NanairoGui/scene/DefaultScene.nana"};
  parser.addOption(scene_file_path_option);
  // Output path
  QCommandLineOption output_path_option{
      {"o", "outputfilepath"},
      "Specify the output path of rendered images.",
      "path",
      "results"};
  parser.addOption(output_path_option);
  // Scene binary
  QCommandLineOption scene_binary_option{
      {"b", "savescenebinary"},
      "Enable saving scene binary file when rendering."};
  parser.addOption(scene_binary_option);

  // Process parameters
  parser.process(application);

  // Set parameters
  auto parameters = std::make_unique<NanairoParameters>();
  // Rendering mode
  {
    const auto mode = parser.value(renderer_mode_option);
    if (mode == "gui")
      parameters->manager_type_ = RendererManagerType::kGui;
    else if (mode == "cui")
      parameters->manager_type_ = RendererManagerType::kCui;
    else
      zisc::raiseError("Invalid renderer mode is specified: ", mode.toStdString());
  }
  // Working directory
  if (parser.isSet(working_directory_option)) {
    const auto dir = parser.value(working_directory_option);
    const bool result = QDir::setCurrent(dir);
    if (!result)
      zisc::raiseError("Invalid working directory is specified: ", dir.toStdString());
  }
  // Scene file path
  {
    const auto file_path = parser.value(scene_file_path_option);
    QString error_message;
    if (!nanairo::SceneDocument::isSceneDocument(file_path, error_message))
      zisc::raiseError(error_message.toStdString());
    parameters->scene_file_path_ = file_path;
  }
  // Output path
  {
    const auto output_path = parser.value(output_path_option);
    QDir::current().mkpath(output_path);
    const QFileInfo output_dir{output_path};
    if (!output_dir.isWritable())
      zisc::raiseError("The output dir isn't writable: ", output_path.toStdString());
    parameters->output_path_ = output_dir.canonicalFilePath();
  }
  // Scene binary
  if (parser.isSet(scene_binary_option)) {
    parameters->is_saving_scene_binary_enabled_ = true;
  }

  return parameters;
}

/*!
  */
std::function<int ()> makeRenderRunner(
    const QCoreApplication& application,
    const NanairoParameters& parameters) noexcept
{
  std::function<int ()> render_runner;
  switch (parameters.manager_type_) {
    case RendererManagerType::kGui: {
      render_runner = [&application, &parameters]()
      {
        // Initialize GUI
        nanairo::GuiEngine engine;
        engine.load(QUrl{"qrc:/NanairoGui/NMainWindow.qml"});
        auto& manager = engine.rendererManager();
        manager.enableSavingSceneBinary(parameters.is_saving_scene_binary_enabled_);
        manager.setOutputPath(parameters.output_path_);
        return application.exec();
      };
      break;
    }
    case RendererManagerType::kCui: {
      render_runner = [&parameters]()
      {
        nanairo::CuiRendererManager manager;
        manager.enableSavingSceneBinary(parameters.is_saving_scene_binary_enabled_);
        manager.invokeRendering(parameters.scene_file_path_);
        manager.setOutputPath(parameters.output_path_);
        return 0;
      };
      break;
    }
    default:
      break;
  }
  return render_runner;
}

} // namespace
<commit_msg>Fix the CUI renderer<commit_after>/*!
  \file main.cpp
  \author Sho Ikeda

  Copyright (c) 2015-2018 Sho Ikeda
  This software is released under the MIT License.
  http://opensource.org/licenses/mit-license.php
  */

// Standard C++ library
#include <cstdlib>
#include <functional>
#include <memory>
// Qt
#ifdef QT_WIDGETS_LIB
#include <QApplication>
#else // QT_WIDGETS_LIB
#include <QGuiApplication>
#endif // QT_WIDGETS_LIB
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QDateTime>
#include <QDir>
#include <QFileInfo>
#include <QFont>
#include <QGuiApplication>
#include <QScopedPointer>
#include <QString>
#include <QtGlobal>
#include <QQmlApplicationEngine>
#include <QUrl>
// Zisc
#include "zisc/error.hpp"
#include "zisc/utility.hpp"
// Nanairo
#include "NanairoCore/nanairo_core_config.hpp"
#include "NanairoGui/gui_engine.hpp"
#include "NanairoGui/nanairo_gui_config.hpp"
#include "NanairoGui/Renderer/cui_renderer_manager.hpp"
#include "NanairoGui/Renderer/scene_document.hpp"

namespace {

/*!
  */
enum class RendererManagerType
{
  kCui,
  kGui
};

/*!
  */
struct NanairoParameters
{
  QString scene_file_path_;
  QString output_path_;
  RendererManagerType manager_type_ = RendererManagerType::kGui;
  bool is_saving_scene_binary_enabled_ = false;
};

//! Initialize Qt settings
void initQt() noexcept;

//! Process command-line parameters
std::unique_ptr<NanairoParameters> processCommandLine(
    const QCoreApplication& application) noexcept;

//! Make a renderer runner
std::function<int ()> makeRenderRunner(
    const QCoreApplication& application,
    const NanairoParameters& parameters) noexcept;

} // namespace

/*!
  \details
  No detailed.
  */
int main(int argc, char** argv)
{
  // Initialize application
  QScopedPointer<QGuiApplication> application{
#ifdef QT_WIDGETS_LIB
    new QApplication{argc, argv}
#else // QT_WIDGETS_LIB
    new QGuiApplication{argc, argv}
#endif // QT_WIDGETS_LIB
    };
  initQt();

  // Parse command line arguments
  const auto parameters = processCommandLine(*application);
  // Make a render runner
  const auto render_runner = makeRenderRunner(*application, *parameters);
  // Launch render runner
  return render_runner();
}

namespace {

/*!
  */
void initQt() noexcept
{
  // Application info
  QGuiApplication::setApplicationName(
      nanairo::GuiConfig::applicationName().c_str());
  QGuiApplication::setApplicationVersion(
      nanairo::CoreConfig::versionString().c_str());

  // Qt properties
  QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

  // Random seed
  {
    const qint64 time = QDateTime::currentMSecsSinceEpoch();
    const qint32* array = zisc::treatAs<const qint32*>(&time);
    const qint32 seed = std::abs(array[0] ^ array[1]);
    qsrand(zisc::cast<uint>(seed));
  }
}

/*!
  \details
  No detailed.
  */
std::unique_ptr<NanairoParameters> processCommandLine(
    const QCoreApplication& application) noexcept
{
  QCommandLineParser parser;

  // Application description
  const auto application_description = QStringLiteral(
      "Nanairo is a physically plausible spectral renderer.");
  parser.setApplicationDescription(application_description);

  // Help and version setting
  parser.addHelpOption();
  parser.addVersionOption();

  // Options
  // Rendering mode
  QCommandLineOption renderer_mode_option{
      {"r", "renderermode"},
      "Choose gui/cui renderer to run.",
      "mode",
      "gui"};
  parser.addOption(renderer_mode_option);
  // Working directory
  QCommandLineOption working_directory_option{
      {"w", "workingdirectory"},
      "Set the current working directory of Nanairo application.",
      "path"};
  parser.addOption(working_directory_option);
  // Scene file
  QCommandLineOption scene_file_path_option{
      {"s", "scenefile"},
      "Specify the rendering scene for cui rendering.",
      "path",
      ":/NanairoGui/scene/DefaultScene.nana"};
  parser.addOption(scene_file_path_option);
  // Output path
  QCommandLineOption output_path_option{
      {"o", "outputfilepath"},
      "Specify the output path of rendered images.",
      "path",
      "results"};
  parser.addOption(output_path_option);
  // Scene binary
  QCommandLineOption scene_binary_option{
      {"b", "savescenebinary"},
      "Enable saving scene binary file when rendering."};
  parser.addOption(scene_binary_option);

  // Process parameters
  parser.process(application);

  // Set parameters
  auto parameters = std::make_unique<NanairoParameters>();
  // Rendering mode
  {
    const auto mode = parser.value(renderer_mode_option);
    if (mode == "gui")
      parameters->manager_type_ = RendererManagerType::kGui;
    else if (mode == "cui")
      parameters->manager_type_ = RendererManagerType::kCui;
    else
      zisc::raiseError("Invalid renderer mode is specified: ", mode.toStdString());
  }
  // Working directory
  if (parser.isSet(working_directory_option)) {
    const auto dir = parser.value(working_directory_option);
    const bool result = QDir::setCurrent(dir);
    if (!result)
      zisc::raiseError("Invalid working directory is specified: ", dir.toStdString());
  }
  // Scene file path
  {
    const auto file_path = parser.value(scene_file_path_option);
    QString error_message;
    if (!nanairo::SceneDocument::isSceneDocument(file_path, error_message))
      zisc::raiseError(error_message.toStdString());
    parameters->scene_file_path_ = file_path;
  }
  // Output path
  {
    const auto output_path = parser.value(output_path_option);
    QDir::current().mkpath(output_path);
    const QFileInfo output_dir{output_path};
    if (!output_dir.isWritable())
      zisc::raiseError("The output dir isn't writable: ", output_path.toStdString());
    parameters->output_path_ = output_dir.canonicalFilePath();
  }
  // Scene binary
  if (parser.isSet(scene_binary_option)) {
    parameters->is_saving_scene_binary_enabled_ = true;
  }

  return parameters;
}

/*!
  */
std::function<int ()> makeRenderRunner(
    const QCoreApplication& application,
    const NanairoParameters& parameters) noexcept
{
  std::function<int ()> render_runner;
  switch (parameters.manager_type_) {
    case RendererManagerType::kGui: {
      render_runner = [&application, &parameters]()
      {
        // Initialize GUI
        nanairo::GuiEngine engine;
        engine.load(QUrl{"qrc:/NanairoGui/NMainWindow.qml"});
        auto& manager = engine.rendererManager();
        manager.enableSavingSceneBinary(parameters.is_saving_scene_binary_enabled_);
        manager.setOutputPath(parameters.output_path_);
        return application.exec();
      };
      break;
    }
    case RendererManagerType::kCui: {
      render_runner = [&parameters]()
      {
        nanairo::CuiRendererManager manager;
        manager.enableSavingSceneBinary(parameters.is_saving_scene_binary_enabled_);
        manager.setOutputPath(parameters.output_path_);
        manager.invokeRendering(parameters.scene_file_path_);
        return 0;
      };
      break;
    }
    default:
      break;
  }
  return render_runner;
}

} // namespace
<|endoftext|>


<commit_before>#include <stdio.h>

#include <SFML/Window/Mouse.hpp>
#include <SFML/Graphics/RectangleShape.hpp>

#include "gui/ng/button.hpp"

namespace namelessgui
{

	Button::Button(sf::RenderWindow* window, float width, float height, std::string text,
		const sf::Texture* textureactive,
		const sf::Texture* textureinactive,
		const sf::Texture* texturehover)
	: RectangularWidget(window, width, height),
	  _label(new Label(window)),
	  _image(new RectangularWidget(window, 48, 48)),
	  _state(ES_INACTIVE),
	  _defaultfont(new sf::Font())
	{
		_defaultfont->loadFromFile("./res/font/Knigqst.ttf");
		this->_label->setFont(*_defaultfont);
		this->_label->setCharacterSize(25);
		this->_label->setText(text);

		if(textureactive != NULL && textureinactive != NULL && texturehover != NULL)
			setTextures(textureactive, textureinactive, texturehover);

		for(int i = 0; i < 3; ++i)
			_textures[i] = 0;

		// Connect signals to slots
		this->signalleftmousebuttonpressed.connect(std::bind(&Button::leftMousebuttonPressedSlot, this));
		this->signalmouseentered.connect(std::bind(&Button::mouseEnteredSlot, this));
		this->signalclicked.connect(std::bind(&Button::clickedSlot, this));
		this->signalmouseleft.connect(std::bind(&Button::mouseLeftSlot, this));

		this->setFillColor(sf::Color(60, 60, 60, 255));
		this->setOutlineColor(sf::Color(30, 30, 30, 255));
		this->setOutlineThickness(2.0f);
	}

	Button::~Button()
	{}

	void Button::setText(std::string text)
	{
		this->_label->setText(text);
	}

	void Button::setState(Button::STATES state)
	{
		this->_state = state;
	}

	Button::STATES Button::getState() const
	{
		return _state;
	}

	void Button::setPosition(float x, float y)
	{
		RectangularWidget::setPosition(x, y);
		_image->setPosition(x, y);
		if(_image->getTexture() != NULL)
		{
			_label->setPosition(x + _image->getSize().x, y);
		}
		else
		{
			_label->setPosition(x, y);
		}
	}

	void Button::setPosition(const sf::Vector2f& position)
	{
		setPosition(position.x, position.y);

	}

	void Button::setTextures(const sf::Texture* textureinactive,
		const sf::Texture* textureactive, const sf::Texture* texturehover)
	{
		_textures[ES_INACTIVE] = textureinactive;
		_textures[ES_ACTIVE] = textureactive;
		_textures[ES_HOVER] = texturehover;
		updateSprite();
	}

	void Button::updateSprite()
	{
		if(_textures[_state] != 0)
		{
			_image->setTexture(_textures[_state], true);
			setPosition(getPosition());
		}
	}

	void Button::draw(sf::RenderTarget& target, sf::RenderStates states) const
    {
		target.draw(static_cast<sf::RectangleShape>(*this));
		target.draw(*_label);
		target.draw(static_cast<sf::RectangleShape>(*_image));
    }

	void Button::leftMousebuttonPressedSlot()
	{
		_state = ES_ACTIVE;
		this->setFillColor(sf::Color(50, 50, 50, 255));
		updateSprite();
	}

	void Button::mouseEnteredSlot()
	{
		_state = ES_HOVER;
		this->setFillColor(sf::Color(80, 80, 80, 255));
		updateSprite();
	}

	void Button::clickedSlot()
	{
		_state = ES_HOVER;
		this->setFillColor(sf::Color(60, 60, 60, 255));
		updateSprite();
	}

	void Button::mouseLeftSlot()
	{
		_state = ES_INACTIVE;
		this->setFillColor(sf::Color(60, 60, 60, 255));
		updateSprite();
	}

}
<commit_msg>Removed useless code from Button.<commit_after>#include <stdio.h>

#include <SFML/Window/Mouse.hpp>
#include <SFML/Graphics/RectangleShape.hpp>

#include "gui/ng/button.hpp"

namespace namelessgui
{

	Button::Button(sf::RenderWindow* window, float width, float height, std::string text,
		const sf::Texture* textureactive,
		const sf::Texture* textureinactive,
		const sf::Texture* texturehover)
	: RectangularWidget(window, width, height),
	  _label(new Label(window)),
	  _image(new RectangularWidget(window, 48, 48)),
	  _state(ES_INACTIVE),
	  _defaultfont(new sf::Font())
	{
		_defaultfont->loadFromFile("./res/font/Knigqst.ttf");
		this->_label->setFont(*_defaultfont);
		this->_label->setCharacterSize(25);
		this->_label->setText(text);

		if(textureactive != NULL && textureinactive != NULL && texturehover != NULL)
			setTextures(textureactive, textureinactive, texturehover);

		for(int i = 0; i < 3; ++i)
			_textures[i] = 0;

		// Connect signals to slots
		this->signalleftmousebuttonpressed.connect(std::bind(&Button::leftMousebuttonPressedSlot, this));
		this->signalmouseentered.connect(std::bind(&Button::mouseEnteredSlot, this));
		this->signalclicked.connect(std::bind(&Button::clickedSlot, this));
		this->signalmouseleft.connect(std::bind(&Button::mouseLeftSlot, this));

		this->setFillColor(sf::Color(60, 60, 60, 255));
		this->setOutlineColor(sf::Color(30, 30, 30, 255));
		this->setOutlineThickness(2.0f);
	}

	Button::~Button()
	{}

	void Button::setText(std::string text)
	{
		this->_label->setText(text);
	}

	void Button::setState(Button::STATES state)
	{
		this->_state = state;
	}

	Button::STATES Button::getState() const
	{
		return _state;
	}

	void Button::setPosition(float x, float y)
	{
		RectangularWidget::setPosition(x, y);
		_image->setPosition(x, y);
		if(_image->getTexture() != NULL)
		{
			_label->setPosition(x + _image->getSize().x, y);
		}
		else
		{
			_label->setPosition(x, y);
		}
	}

	void Button::setPosition(const sf::Vector2f& position)
	{
		setPosition(position.x, position.y);

	}

	void Button::setTextures(const sf::Texture* textureinactive,
		const sf::Texture* textureactive, const sf::Texture* texturehover)
	{
		_textures[ES_INACTIVE] = textureinactive;
		_textures[ES_ACTIVE] = textureactive;
		_textures[ES_HOVER] = texturehover;
		updateSprite();
	}

	void Button::updateSprite()
	{
		if(_textures[_state] != 0)
			_image->setTexture(_textures[_state], true);
	}

	void Button::draw(sf::RenderTarget& target, sf::RenderStates states) const
    {
		target.draw(static_cast<sf::RectangleShape>(*this));
		target.draw(*_label);
		target.draw(static_cast<sf::RectangleShape>(*_image));
    }

	void Button::leftMousebuttonPressedSlot()
	{
		_state = ES_ACTIVE;
		this->setFillColor(sf::Color(50, 50, 50, 255));
		updateSprite();
	}

	void Button::mouseEnteredSlot()
	{
		_state = ES_HOVER;
		this->setFillColor(sf::Color(80, 80, 80, 255));
		updateSprite();
	}

	void Button::clickedSlot()
	{
		_state = ES_HOVER;
		this->setFillColor(sf::Color(60, 60, 60, 255));
		updateSprite();
	}

	void Button::mouseLeftSlot()
	{
		_state = ES_INACTIVE;
		this->setFillColor(sf::Color(60, 60, 60, 255));
		updateSprite();
	}

}
<|endoftext|>