<commit_before>#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <chrono>

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>

using namespace ::std;

class I2CBus
{
  public:
    I2CBus(unsigned _busId)
     :m_busFd(-1),
      m_busPath()
    {
      ostringstream busDevName;
      busDevName << "/dev/i2c-" << _busId;
      m_busPath = busDevName.str();
      m_busFd = ::open(m_busPath.c_str(), O_RDWR | O_SYNC);
      if (m_busFd == -1)
      {
        ostringstream os;
        os << "cannot open i2c bus device " << m_busPath << ", error " << errno;
        throw runtime_error(os.str());
      }
    }

    ~I2CBus()
    {
      if (m_busFd != -1)
        ::close(m_busFd);
    }

    int           fd()   const { return m_busFd; }
    const string& path() const { return m_busPath; }

  private:
    int    m_busFd;
    string m_busPath;
};

class I2CDevice
{
  public:
    I2CDevice(unsigned _busId, unsigned _deviceId)
     :m_i2cBus(_busId)
    {
      if (ioctl(m_i2cBus.fd(), I2C_SLAVE, _deviceId) == -1)
      {
        ostringstream os;
        os << "cannot select i2c slave device " << _deviceId << ", bus " << m_i2cBus.path() << ", error " << errno;
        throw runtime_error(os.str());
      }
    }

    int smbusAccess(uint8_t _readWrite, uint8_t _cmd, i2c_smbus_data& _data, size_t _bytes)
    {
      struct i2c_smbus_ioctl_data args;
      args.read_write = _readWrite;
      args.command = _cmd;
      args.size = _bytes;
      args.data = &_data;
      return ioctl(m_i2cBus.fd(), I2C_SMBUS, &args);
    }

  private:
    I2CBus m_i2cBus;
};

class MSPControl
{
  public:
    MSPControl(unsigned _busId, unsigned _deviceId)
     :m_i2cDevice(_busId, _deviceId)
    {
    }

    unsigned readWord(unsigned _addr)
    {
      i2c_smbus_data i2cData;
      int res = m_i2cDevice.smbusAccess(I2C_SMBUS_READ, _addr, i2cData, I2C_SMBUS_WORD_DATA);
      if (res != 0)
      {
        ostringstream os;
        os << "failed ioctl(SMBUS_READ)";
        throw runtime_error(os.str());
      }

      return i2cData.word;
    }

  private:
    I2CDevice m_i2cDevice;
};

class GPIOControl
{
  public:
    GPIOControl(unsigned _gpio)
     :m_gpioFd(-1),
      m_gpioPath()
    {
      ostringstream gpioCtrlName;
      gpioCtrlName << "/sys/class/gpio/gpio" << _gpio << "/value";
      m_gpioPath = gpioCtrlName.str();
      m_gpioFd = ::open(m_gpioPath.c_str(), O_RDWR | O_SYNC);
      if (m_gpioFd == -1)
      {
        ostringstream os;
        os << "cannot open gpio control " << m_gpioPath;
        throw runtime_error(os.str());
      }
    }

    ~GPIOControl()
    {
      if (m_gpioFd != -1)
        ::close(m_gpioFd);
    }

    void setValue(unsigned _val)
    {
      ostringstream valueStream;
      valueStream << _val << endl;
      const string& value = valueStream.str();
      if (::write(m_gpioFd, value.c_str(), value.length()) != value.length())
      {
        ostringstream os;
        os << "cannot set gpio value " << m_gpioPath;
        throw runtime_error(os.str());
      }
    }

    const string& path() const { return m_gpioPath; }

  private:
    int m_gpioFd;
    string m_gpioPath;
};

class TrikCoilGun
{
  public:
    TrikCoilGun(unsigned _mspBusId, unsigned _mspDeviceId,
                unsigned _mspChargeLevelCmd, unsigned _mspDischargeCurrentCmd,
                unsigned _gpioChargeControl, unsigned _gpioDischargeControl)
     :m_mspControl(_mspBusId, _mspDeviceId),
      m_mspCmdChargeLevel(_mspChargeLevelCmd),
      m_mspCmdDischargeCurrent(_mspDischargeCurrentCmd),
      m_gpioChargeControl(_gpioChargeControl),
      m_gpioDischargeControl(_gpioDischargeControl)
    {
      m_gpioChargeControl.setValue(0);
      m_gpioDischargeControl.setValue(0);
    }

    ~TrikCoilGun()
    {
      m_gpioChargeControl.setValue(0);
      m_gpioDischargeControl.setValue(0);
    }

    void charge(unsigned _durationMs, unsigned _chargeLevel)
    {
      const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now();
      const bool waitCharge = _durationMs == 0;
      const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs);

      cerr << "Preparing for charge to level " << _chargeLevel << endl;
      bool charging = false;

      while (true)
      {
        if (!waitCharge && chrono::steady_clock::now() >= elapseAt)
          break;

        const unsigned currentChargeLevel = m_mspControl.readWord(m_mspCmdChargeLevel);
        if (currentChargeLevel >= _chargeLevel)
        {
          if (charging)
            cerr << "Stop charging at level " << currentChargeLevel << ", target level " << _chargeLevel << endl;
          charging = false;

          if (waitCharge)
            break;
          m_gpioChargeControl.setValue(0);
        }
        else
        {
          if (!charging)
            cerr << "Charging at level " << currentChargeLevel << ", target level " << _chargeLevel << endl;
          charging = true;
          m_gpioChargeControl.setValue(1);
        }
        usleep(1000);
      }

      cerr << "Charge done" << endl;
      m_gpioChargeControl.setValue(0);
    }

    void discharge(unsigned _durationMs, unsigned _zeroChargeLevel)
    {
      const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now();
      const bool waitDischarge = _durationMs == 0;
      const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs);

      cerr << "Preparing for discharge from level " << m_mspControl.readWord(m_mspCmdChargeLevel)
           << " to level " << _zeroChargeLevel << endl;
      while (true)
      {
        if (!waitDischarge && chrono::steady_clock::now() >= elapseAt)
          break;

        const unsigned currentChargeLevel = m_mspControl.readWord(m_mspCmdChargeLevel);
        if (currentChargeLevel <= _zeroChargeLevel)
        {
          cerr << "Discharged to level " << currentChargeLevel << ", target level " << _zeroChargeLevel << endl;
          break;
        }

        m_gpioDischargeControl.setValue(1);
        usleep(1000);
      }

      cerr << "Discharge done, current level " << m_mspControl.readWord(m_mspCmdChargeLevel)
           << ", target level " << _zeroChargeLevel << endl;
      m_gpioDischargeControl.setValue(0);
    }

    void fire(unsigned _preDelayMs, unsigned _durationUs, unsigned _postDelayMs)
    {
      m_gpioChargeControl.setValue(0);
      usleep(_preDelayMs * 1000);

      const chrono::steady_clock::time_point& stopFireAt = chrono::steady_clock::now() + chrono::duration<chrono::steady_clock::rep, chrono::microseconds::period>(_durationUs);
      cerr << "Fire!" << endl;
      m_gpioDischargeControl.setValue(1);
      while (chrono::steady_clock::now() >= stopFireAt)
        ;
      m_gpioDischargeControl.setValue(0);
      cerr << "Fire done" << endl;

      usleep(_postDelayMs * 1000);
    }

  private:
    MSPControl m_mspControl;
    unsigned m_mspCmdChargeLevel;
    unsigned m_mspCmdDischargeCurrent;
    GPIOControl m_gpioChargeControl;
    GPIOControl m_gpioDischargeControl;
};

int printUsageHelp()
{
#warning TODO
  return 1;
}

int main(int _argc, char* const _argv[])
{
  static const char* s_optstring = "h";
  static const struct option s_longopts[] = {
    { "help",				no_argument,		NULL,	0},
    { "msp-i2c-bus",			required_argument,	NULL,	0}, // 1
    { "msp-i2c-device",			required_argument,	NULL,	0},
    { "msp-i2c-charge-level",		required_argument,	NULL,	0},
    { "msp-i2c-discharge-current",	required_argument,	NULL,	0},
    { "gpio-charge",			required_argument,	NULL,	0}, // 5
    { "gpio-discharge",			required_argument,	NULL,	0},
    { "charge-duration",		required_argument,	NULL,	0}, // 7
    { "charge-level",			required_argument,	NULL,	0},
    { "fire-predelay",			required_argument,	NULL,	0}, // 9
    { "fire-duration",			required_argument,	NULL,	0},
    { "fire-duration-us",		required_argument,	NULL,	0},
    { "fire-postdelay",			required_argument,	NULL,	0},
    { "discharge-duration",		required_argument,	NULL,	0}, // 13
    { "discharge-level",		required_argument,	NULL,	0},
    { NULL,				0,			NULL,	0},
  };

  int longopt;
  int opt;

  unsigned mspI2cBusId = 0x2;
  unsigned mspI2cDeviceId = 0x48;
  unsigned mspChargeLevelCmd = 0x25;
  unsigned mspDischargeCurrentCmd = 0x24;
  unsigned gpioChargeCtrl = 0x17;
  unsigned gpioDischargeCtrl = 0x00;

  unsigned chargeDurationMs = 0;
  unsigned chargeLevel = 0x200;
  unsigned firePreDelayMs = 10;
  unsigned fireDurationUs = 1000;
  unsigned firePostDelayMs = 100;
  unsigned dischargeDurationMs = 0;
  unsigned dischargeLevel = 0x5;

  while ((opt = getopt_long(_argc, _argv, s_optstring, s_longopts, &longopt)) != -1)
  {
    switch (opt)
    {
      case 'h':		return printUsageHelp();

      case 0:
        switch (longopt)
        {
          case 0:	return printUsageHelp();

          case 1:	mspI2cBusId		= atoi(optarg);	break;
          case 2:	mspI2cDeviceId		= atoi(optarg);	break;
          case 3:	mspChargeLevelCmd	= atoi(optarg);	break;
          case 4:	mspDischargeCurrentCmd	= atoi(optarg);	break;
          case 5:	gpioChargeCtrl		= atoi(optarg);	break;
          case 6:	gpioDischargeCtrl	= atoi(optarg);	break;

          case 7:	chargeDurationMs	= atoi(optarg);	break;
          case 8:	chargeLevel		= atoi(optarg);	break;
          case 9:	firePreDelayMs		= atoi(optarg);	break;
          case 10:	fireDurationUs		= 1000*atoi(optarg);	break;
          case 11:	fireDurationUs		= atoi(optarg);	break;
          case 12:	firePostDelayMs		= atoi(optarg);	break;
          case 13:	dischargeDurationMs	= atoi(optarg);	break;
          case 14:	dischargeLevel		= atoi(optarg);	break;
          default:	return printUsageHelp();
        }
        break;
      default:		return printUsageHelp();
    }
  }

  cout << "Charge duration " << chargeDurationMs << "ms, level " << chargeLevel << endl;
  cout << "Fire pre-delay " << firePreDelayMs << "ms, duration " << fireDurationUs << "us, post-delay " << firePostDelayMs << "ms" << endl;
  cout << "Discharge duration " << dischargeDurationMs << "ms, level " << dischargeLevel << endl;

  TrikCoilGun coilGun(mspI2cBusId, mspI2cDeviceId, mspChargeLevelCmd, mspDischargeCurrentCmd, gpioChargeCtrl, gpioDischargeCtrl);

  coilGun.charge(chargeDurationMs, chargeLevel);
  coilGun.fire(firePreDelayMs, fireDurationUs, firePostDelayMs);
  coilGun.discharge(dischargeDurationMs, dischargeLevel);
}

<commit_msg>Fire duration measurement was invalid<commit_after>#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <chrono>

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>

using namespace ::std;

class I2CBus
{
  public:
    I2CBus(unsigned _busId)
     :m_busFd(-1),
      m_busPath()
    {
      ostringstream busDevName;
      busDevName << "/dev/i2c-" << _busId;
      m_busPath = busDevName.str();
      m_busFd = ::open(m_busPath.c_str(), O_RDWR | O_SYNC);
      if (m_busFd == -1)
      {
        ostringstream os;
        os << "cannot open i2c bus device " << m_busPath << ", error " << errno;
        throw runtime_error(os.str());
      }
    }

    ~I2CBus()
    {
      if (m_busFd != -1)
        ::close(m_busFd);
    }

    int           fd()   const { return m_busFd; }
    const string& path() const { return m_busPath; }

  private:
    int    m_busFd;
    string m_busPath;
};

class I2CDevice
{
  public:
    I2CDevice(unsigned _busId, unsigned _deviceId)
     :m_i2cBus(_busId)
    {
      if (ioctl(m_i2cBus.fd(), I2C_SLAVE, _deviceId) == -1)
      {
        ostringstream os;
        os << "cannot select i2c slave device " << _deviceId << ", bus " << m_i2cBus.path() << ", error " << errno;
        throw runtime_error(os.str());
      }
    }

    int smbusAccess(uint8_t _readWrite, uint8_t _cmd, i2c_smbus_data& _data, size_t _bytes)
    {
      struct i2c_smbus_ioctl_data args;
      args.read_write = _readWrite;
      args.command = _cmd;
      args.size = _bytes;
      args.data = &_data;
      return ioctl(m_i2cBus.fd(), I2C_SMBUS, &args);
    }

  private:
    I2CBus m_i2cBus;
};

class MSPControl
{
  public:
    MSPControl(unsigned _busId, unsigned _deviceId)
     :m_i2cDevice(_busId, _deviceId)
    {
    }

    unsigned readWord(unsigned _addr)
    {
      i2c_smbus_data i2cData;
      int res = m_i2cDevice.smbusAccess(I2C_SMBUS_READ, _addr, i2cData, I2C_SMBUS_WORD_DATA);
      if (res != 0)
      {
        ostringstream os;
        os << "failed ioctl(SMBUS_READ)";
        throw runtime_error(os.str());
      }

      return i2cData.word;
    }

  private:
    I2CDevice m_i2cDevice;
};

class GPIOControl
{
  public:
    GPIOControl(unsigned _gpio)
     :m_gpioFd(-1),
      m_gpioPath()
    {
      ostringstream gpioCtrlName;
      gpioCtrlName << "/sys/class/gpio/gpio" << _gpio << "/value";
      m_gpioPath = gpioCtrlName.str();
      m_gpioFd = ::open(m_gpioPath.c_str(), O_RDWR | O_SYNC);
      if (m_gpioFd == -1)
      {
        ostringstream os;
        os << "cannot open gpio control " << m_gpioPath;
        throw runtime_error(os.str());
      }
    }

    ~GPIOControl()
    {
      if (m_gpioFd != -1)
        ::close(m_gpioFd);
    }

    void setValue(unsigned _val)
    {
      ostringstream valueStream;
      valueStream << _val << endl;
      const string& value = valueStream.str();
      if (::write(m_gpioFd, value.c_str(), value.length()) != value.length())
      {
        ostringstream os;
        os << "cannot set gpio value " << m_gpioPath;
        throw runtime_error(os.str());
      }
    }

    const string& path() const { return m_gpioPath; }

  private:
    int m_gpioFd;
    string m_gpioPath;
};

class TrikCoilGun
{
  public:
    TrikCoilGun(unsigned _mspBusId, unsigned _mspDeviceId,
                unsigned _mspChargeLevelCmd, unsigned _mspDischargeCurrentCmd,
                unsigned _gpioChargeControl, unsigned _gpioDischargeControl)
     :m_mspControl(_mspBusId, _mspDeviceId),
      m_mspCmdChargeLevel(_mspChargeLevelCmd),
      m_mspCmdDischargeCurrent(_mspDischargeCurrentCmd),
      m_gpioChargeControl(_gpioChargeControl),
      m_gpioDischargeControl(_gpioDischargeControl)
    {
      m_gpioChargeControl.setValue(0);
      m_gpioDischargeControl.setValue(0);
    }

    ~TrikCoilGun()
    {
      m_gpioChargeControl.setValue(0);
      m_gpioDischargeControl.setValue(0);
    }

    void charge(unsigned _durationMs, unsigned _chargeLevel)
    {
      const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now();
      const bool waitCharge = _durationMs == 0;
      const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs);

      cerr << "Preparing for charge to level " << _chargeLevel << endl;
      bool charging = false;

      while (true)
      {
        if (!waitCharge && chrono::steady_clock::now() >= elapseAt)
          break;

        const unsigned currentChargeLevel = m_mspControl.readWord(m_mspCmdChargeLevel);
        if (currentChargeLevel >= _chargeLevel)
        {
          if (charging)
            cerr << "Stop charging at level " << currentChargeLevel << ", target level " << _chargeLevel << endl;
          charging = false;

          if (waitCharge)
            break;
          m_gpioChargeControl.setValue(0);
        }
        else
        {
          if (!charging)
            cerr << "Charging at level " << currentChargeLevel << ", target level " << _chargeLevel << endl;
          charging = true;
          m_gpioChargeControl.setValue(1);
        }
        usleep(1000);
      }

      cerr << "Charge done" << endl;
      m_gpioChargeControl.setValue(0);
    }

    void discharge(unsigned _durationMs, unsigned _zeroChargeLevel)
    {
      const chrono::steady_clock::time_point& startAt = chrono::steady_clock::now();
      const bool waitDischarge = _durationMs == 0;
      const chrono::steady_clock::time_point& elapseAt = startAt + chrono::duration<chrono::steady_clock::rep, chrono::milliseconds::period>(_durationMs);

      cerr << "Preparing for discharge from level " << m_mspControl.readWord(m_mspCmdChargeLevel)
           << " to level " << _zeroChargeLevel << endl;
      while (true)
      {
        if (!waitDischarge && chrono::steady_clock::now() >= elapseAt)
          break;

        const unsigned currentChargeLevel = m_mspControl.readWord(m_mspCmdChargeLevel);
        if (currentChargeLevel <= _zeroChargeLevel)
        {
          cerr << "Discharged to level " << currentChargeLevel << ", target level " << _zeroChargeLevel << endl;
          break;
        }

        m_gpioDischargeControl.setValue(1);
        usleep(1000);
      }

      cerr << "Discharge done, current level " << m_mspControl.readWord(m_mspCmdChargeLevel)
           << ", target level " << _zeroChargeLevel << endl;
      m_gpioDischargeControl.setValue(0);
    }

    void fire(unsigned _preDelayMs, unsigned _durationUs, unsigned _postDelayMs)
    {
      m_gpioChargeControl.setValue(0);
      usleep(_preDelayMs * 1000);

      cerr << "Fire!" << endl;
      const chrono::steady_clock::time_point stopFireAt = chrono::steady_clock::now() + chrono::duration<chrono::steady_clock::rep, chrono::microseconds::period>(_durationUs);
      m_gpioDischargeControl.setValue(1);
      while (chrono::steady_clock::now() <= stopFireAt)
        ;
      m_gpioDischargeControl.setValue(0);
      cerr << "Fire done" << endl;

      usleep(_postDelayMs * 1000);
    }

  private:
    MSPControl m_mspControl;
    unsigned m_mspCmdChargeLevel;
    unsigned m_mspCmdDischargeCurrent;
    GPIOControl m_gpioChargeControl;
    GPIOControl m_gpioDischargeControl;
};

int printUsageHelp()
{
#warning TODO
  return 1;
}

int main(int _argc, char* const _argv[])
{
  static const char* s_optstring = "h";
  static const struct option s_longopts[] = {
    { "help",				no_argument,		NULL,	0},
    { "msp-i2c-bus",			required_argument,	NULL,	0}, // 1
    { "msp-i2c-device",			required_argument,	NULL,	0},
    { "msp-i2c-charge-level",		required_argument,	NULL,	0},
    { "msp-i2c-discharge-current",	required_argument,	NULL,	0},
    { "gpio-charge",			required_argument,	NULL,	0}, // 5
    { "gpio-discharge",			required_argument,	NULL,	0},
    { "charge-duration",		required_argument,	NULL,	0}, // 7
    { "charge-level",			required_argument,	NULL,	0},
    { "fire-predelay",			required_argument,	NULL,	0}, // 9
    { "fire-duration",			required_argument,	NULL,	0},
    { "fire-duration-us",		required_argument,	NULL,	0},
    { "fire-postdelay",			required_argument,	NULL,	0},
    { "discharge-duration",		required_argument,	NULL,	0}, // 13
    { "discharge-level",		required_argument,	NULL,	0},
    { NULL,				0,			NULL,	0},
  };

  int longopt;
  int opt;

  unsigned mspI2cBusId = 0x2;
  unsigned mspI2cDeviceId = 0x48;
  unsigned mspChargeLevelCmd = 0x25;
  unsigned mspDischargeCurrentCmd = 0x24;
  unsigned gpioChargeCtrl = 0x17;
  unsigned gpioDischargeCtrl = 0x00;

  unsigned chargeDurationMs = 0;
  unsigned chargeLevel = 0x200;
  unsigned firePreDelayMs = 10;
  unsigned fireDurationUs = 1000;
  unsigned firePostDelayMs = 100;
  unsigned dischargeDurationMs = 0;
  unsigned dischargeLevel = 0x5;

  while ((opt = getopt_long(_argc, _argv, s_optstring, s_longopts, &longopt)) != -1)
  {
    switch (opt)
    {
      case 'h':		return printUsageHelp();

      case 0:
        switch (longopt)
        {
          case 0:	return printUsageHelp();

          case 1:	mspI2cBusId		= atoi(optarg);	break;
          case 2:	mspI2cDeviceId		= atoi(optarg);	break;
          case 3:	mspChargeLevelCmd	= atoi(optarg);	break;
          case 4:	mspDischargeCurrentCmd	= atoi(optarg);	break;
          case 5:	gpioChargeCtrl		= atoi(optarg);	break;
          case 6:	gpioDischargeCtrl	= atoi(optarg);	break;

          case 7:	chargeDurationMs	= atoi(optarg);	break;
          case 8:	chargeLevel		= atoi(optarg);	break;
          case 9:	firePreDelayMs		= atoi(optarg);	break;
          case 10:	fireDurationUs		= 1000*atoi(optarg);	break;
          case 11:	fireDurationUs		= atoi(optarg);	break;
          case 12:	firePostDelayMs		= atoi(optarg);	break;
          case 13:	dischargeDurationMs	= atoi(optarg);	break;
          case 14:	dischargeLevel		= atoi(optarg);	break;
          default:	return printUsageHelp();
        }
        break;
      default:		return printUsageHelp();
    }
  }

  cout << "Charge duration " << chargeDurationMs << "ms, level " << chargeLevel << endl;
  cout << "Fire pre-delay " << firePreDelayMs << "ms, duration " << fireDurationUs << "us, post-delay " << firePostDelayMs << "ms" << endl;
  cout << "Discharge duration " << dischargeDurationMs << "ms, level " << dischargeLevel << endl;

  TrikCoilGun coilGun(mspI2cBusId, mspI2cDeviceId, mspChargeLevelCmd, mspDischargeCurrentCmd, gpioChargeCtrl, gpioDischargeCtrl);

  coilGun.charge(chargeDurationMs, chargeLevel);
  coilGun.fire(firePreDelayMs, fireDurationUs, firePostDelayMs);
  coilGun.discharge(dischargeDurationMs, dischargeLevel);
}

<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>

#include "functions.h"

int main(int argc, char** argv)
{
  // hold a raw line of input
  std::string line;

  // print welcome message and prompt
  printf("Welcome to rshell!\n");

  while (true)
  {
    // holds a single command and its arguments
    Command cmd;
    // holds multiple commands
    std::vector<Command> cmds;

    // print prompt and get a line of text (done in condition)
    printf("$ ");
    getline(std::cin, line); // handles the EOF being passed in

    // look for comments
    if (line.find("#") != std::string::npos)
    {
      // remove them if necessary (they're useless)
      line = line.substr(0, line.find("#"));
    }

    // remove leading whitespace
    while (line.size() > 0 && (line[0] == ' ' || line[0] == ';'))
    {
      line = line.substr(1, line.size() - 1);
    }

    // add a space so that every space-separated entity has
    // at least one space directly to the right of it
    // (makes parsing easier)
    line += ' ';

    // if exit was entered properly
    if (line.substr(0,5) == "exit " || std::cin.fail())
    {
      if (std::cin.fail())
      {
        printf("\n");
      }
      // say goodbye, and quit
      printf("Goodbye!\n");
      exit(0);
    }

    int mode = GETWORD;
    unsigned begin = 0;

    // temporary: show pre-processed input to know what's being dealt with
    printf("You entered: \"%s\"\n", line.c_str());

    // prepare cmd
    cmd.connector = NONE;

    // syntax error flag
    bool se = false;

    // handle the input
    for(unsigned i = 0; i < line.size() && !se; ++i)
    {
      bool con   = isConn(line[i]);
      bool space = isspace(line[i]);

      // if we're getting a word and there's a whitespace or connector here
      if (mode == GETWORD && (space || con))
      {
        // chunk the last term and throw it into the vector
        char* c = stocstr(line.substr(begin, i - begin));
        if (strlen(c) > 0)
        {
          cmd.args.push_back(c);
        }
        else
        {
          break;
        }

        if (space)
        {
          mode = TRIMSPACE;
        }
        else // it's a connector
        {
          handleCon(cmds, cmd, line, mode, i, se);
        }
      }
      else if (mode == TRIMSPACE && (!space && con))
      {
        if (con && cmd.args.empty())
        {
          se = true;
        }
        else if (con) // it's a valid connector connector
        {
          handleCon(cmds, cmd, line, mode, i, se);
        }
        else
        {
          mode = GETWORD;
        }
      }
    }

    // if there was a syntax error
    if (se)
    {
      printf("Syntax error detected\n");
      continue;
    }

    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      printf("Command %u:\n", i);
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        printf("\t\"%s\"\n", cmds[i].args[j]);
      }
      switch(cmds[i].connector)
      {
        case AND:
          printf("\t&&\n");
          break;
        case OR:
          printf("\t||\n");
          break;
        case SEMI:
          printf("\t;\n");
          break;
        case NONE:
          printf("\tNo connector\n");
          break;
        default:
          printf("\tERROR: no valid connector specified\n");
      }
    }

    // deallocate allocated memory
    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        delete[] cmds[i].args[i];
      }
    }
  }
  return 0;
}

<commit_msg>Removed exit command checking<commit_after>#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>

#include "functions.h"

int main(int argc, char** argv)
{
  // hold a raw line of input
  std::string line;

  // print welcome message and prompt
  printf("Welcome to rshell!\n");

  while (true)
  {
    // holds a single command and its arguments
    Command cmd;
    // holds multiple commands
    std::vector<Command> cmds;

    // print prompt and get a line of text (done in condition)
    printf("$ ");
    getline(std::cin, line);

    // look for comments
    if (line.find("#") != std::string::npos)
    {
      // remove them if necessary (they're useless)
      line = line.substr(0, line.find("#"));
    }

    // remove leading whitespace
    while (line.size() > 0 && (line[0] == ' ' || line[0] == ';'))
    {
      line = line.substr(1, line.size() - 1);
    }

    if (std::cin.fail())
    {
      printf("\nGoodbye!\n");
      exit(0);
    }

    int mode = GETWORD;
    unsigned begin = 0;

    // temporary: show pre-processed input to know what's being dealt with
    printf("You entered: \"%s\"\n", line.c_str());

    // prepare cmd
    cmd.connector = NONE;

    // syntax error flag
    bool se = false;

    // handle the input
    for(unsigned i = 0; i < line.size() && !se; ++i)
    {
      bool con   = isConn(line[i]);
      bool space = isspace(line[i]);

      // if we're getting a word and there's a whitespace or connector here
      if (mode == GETWORD && (space || con))
      {
        // chunk the last term and throw it into the vector
        char* c = stocstr(line.substr(begin, i - begin));
        if (strlen(c) > 0)
        {
          cmd.args.push_back(c);
        }
        else
        {
          break;
        }

        if (space)
        {
          mode = TRIMSPACE;
        }
        else // it's a connector
        {
          handleCon(cmds, cmd, line, mode, i, se);
        }
      }
      else if (mode == TRIMSPACE && (!space && con))
      {
        if (con && cmd.args.empty())
        {
          se = true;
        }
        else if (con) // it's a valid connector connector
        {
          handleCon(cmds, cmd, line, mode, i, se);
        }
        else
        {
          mode = GETWORD;
        }
      }
    }

    // if there was a syntax error
    if (se)
    {
      printf("Syntax error detected\n");
      continue;
    }

    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      printf("Command %u:\n", i);
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        printf("\t\"%s\"\n", cmds[i].args[j]);
      }
      switch(cmds[i].connector)
      {
        case AND:
          printf("\t&&\n");
          break;
        case OR:
          printf("\t||\n");
          break;
        case SEMI:
          printf("\t;\n");
          break;
        case NONE:
          printf("\tNo connector\n");
          break;
        default:
          printf("\tERROR: no valid connector specified\n");
      }
    }

    // deallocate allocated memory
    for(unsigned i = 0; i < cmds.size(); ++i)
    {
      for(unsigned j = 0; j < cmds[i].args.size(); ++j)
      {
        delete[] cmds[i].args[i];
      }
    }
  }
  return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <random>
#include <vector>
#include <memory>
#include "geometry.h"
#include "immintrin.h"
#include "vec.h"
#include "mat3.h"
#include "color.h"
#include "render_target.h"
#include "camera.h"
#include "sphere.h"
#include "plane.h"
#include "diff_geom.h"
#include "material.h"
#include "light.h"
#include "occlusion_tester.h"
#include "block_queue.h"
#include "ld_sampler.h"
#include "scene.h"

int main(int, char**){
	const uint32_t width = 800;
	const uint32_t height = 600;
	const auto scene = Scene{
		{
			std::make_shared<Sphere>(Vec3f{0}, 0.5f, 0),
			std::make_shared<Plane>(Vec3f{0, -0.5f, 0.5f}, Vec3f{0, 1, 0}, 1)
		},
		{
			std::make_shared<LambertianMaterial>(Colorf{1, 0, 0}),
			std::make_shared<LambertianMaterial>(Colorf{0, 0, 1})
		},
		PointLight{Vec3f{1, 1, -2}, Colorf{50}}
	};

	const auto camera = PerspectiveCamera{Vec3f{0, 0, -3}, Vec3f{0, 0, 0}, Vec3f{0, 1, 0},
		60.f, static_cast<float>(width) / height};
	auto target = RenderTarget{width, height};
	const auto img_dim = Vec2f_8{static_cast<float>(width), static_cast<float>(height)};

	std::random_device rand_device;
	std::mt19937 rng(rand_device());
	const uint32_t block_dim = 8;
	auto block_queue = BlockQueue{block_dim, width, height};
	auto sampler = LDSampler{32, block_dim};
	for (auto block = block_queue.next(); block != block_queue.end(); block = block_queue.next()){
		sampler.select_block(block);
		while (sampler.has_samples()){
			auto samples = Vec2f_8{0, 0};
			Ray8 packet;
			packet.active = sampler.sample(rng, samples);
			camera.generate_rays(packet, samples / img_dim);

			DiffGeom8 dg;
			auto hits = scene.intersect(packet, dg);
			// If we hit something, shade it, otherwise use the background color (black)
			auto color = Colorf_8{0};
			if (_mm256_movemask_ps(hits) != 0){
				// How does ISPC find the unique values for its foreach_unique loop? Would like to do that
				// if it will be nicer than this
				std::array<int32_t, 8> mat_ids;
				_mm256_storeu_si256((__m256i*)mat_ids.data(), dg.material_id);
				// std::unique just removes consecutive repeated elements, so sort things first so we
				// don't get something like -1, 0, -1 or such
				std::sort(std::begin(mat_ids), std::end(mat_ids));
				auto id_end = std::unique(std::begin(mat_ids), std::end(mat_ids));
				for (auto it = std::begin(mat_ids); it != id_end; ++it){
					const auto i = *it;
					if (i == -1){
						continue;
					}
					const auto use_mat = _mm256_cmpeq_epi32(dg.material_id, _mm256_set1_epi32(i));
					auto shade_mask = _mm256_castsi256_ps(use_mat);
					if (_mm256_movemask_ps(shade_mask) != 0){
						const auto w_o = -packet.d;
						Vec3f_8 w_i{0};
						// Setup occlusion tester and set active ray mask to just be those with
						// corresponding to tests from hits with the material id being shaded
						OcclusionTester occlusion;
						const auto li = scene.light.sample(dg.point, w_i, occlusion);
						occlusion.rays.active = shade_mask;
						// We just need to flip the sign bit to change occluded mask to unoccluded mask since
						// only the sign bit is used by movemask and blendv
						auto unoccluded = _mm256_xor_ps(occlusion.occluded(scene), _mm256_set1_ps(-0.f));
						if (_mm256_movemask_ps(unoccluded) != 0){
							const auto c = scene.materials[i]->shade(w_o, w_i) * li
								* _mm256_max_ps(w_i.dot(dg.normal), _mm256_set1_ps(0.f));
							shade_mask = _mm256_and_ps(shade_mask, unoccluded);
							color.r = _mm256_blendv_ps(color.r, c.r, shade_mask);
							color.g = _mm256_blendv_ps(color.g, c.g, shade_mask);
							color.b = _mm256_blendv_ps(color.b, c.b, shade_mask);
						}
					}
				}
			}
			target.write_samples(samples, color, packet.active);
		}
	}
	target.save_image("out.bmp");
}

<commit_msg>Splitting render work into its own function for easier threading<commit_after>#include <iostream>
#include <algorithm>
#include <random>
#include <vector>
#include <memory>
#include "geometry.h"
#include "immintrin.h"
#include "vec.h"
#include "mat3.h"
#include "color.h"
#include "render_target.h"
#include "camera.h"
#include "sphere.h"
#include "plane.h"
#include "diff_geom.h"
#include "material.h"
#include "light.h"
#include "occlusion_tester.h"
#include "block_queue.h"
#include "ld_sampler.h"
#include "scene.h"

void render(const Scene &scene, const PerspectiveCamera &camera, const Vec2f_8 img_dim, RenderTarget &target,
			BlockQueue &block_queue){
	std::random_device rand_device;
	std::mt19937 rng(rand_device());
	auto sampler = LDSampler{64, block_queue.get_block_dim()};
	for (auto block = block_queue.next(); block != block_queue.end(); block = block_queue.next()){
		sampler.select_block(block);
		while (sampler.has_samples()){
			auto samples = Vec2f_8{0, 0};
			Ray8 packet;
			packet.active = sampler.sample(rng, samples);
			camera.generate_rays(packet, samples / img_dim);

			DiffGeom8 dg;
			auto hits = scene.intersect(packet, dg);
			// If we hit something, shade it, otherwise use the background color (black)
			auto color = Colorf_8{0};
			if (_mm256_movemask_ps(hits) != 0){
				// How does ISPC find the unique values for its foreach_unique loop? Would like to do that
				// if it will be nicer than this
				std::array<int32_t, 8> mat_ids;
				_mm256_storeu_si256((__m256i*)mat_ids.data(), dg.material_id);
				// std::unique just removes consecutive repeated elements, so sort things first so we
				// don't get something like -1, 0, -1 or such
				std::sort(std::begin(mat_ids), std::end(mat_ids));
				auto id_end = std::unique(std::begin(mat_ids), std::end(mat_ids));
				for (auto it = std::begin(mat_ids); it != id_end; ++it){
					const auto i = *it;
					if (i == -1){
						continue;
					}
					const auto use_mat = _mm256_cmpeq_epi32(dg.material_id, _mm256_set1_epi32(i));
					auto shade_mask = _mm256_castsi256_ps(use_mat);
					if (_mm256_movemask_ps(shade_mask) != 0){
						const auto w_o = -packet.d;
						Vec3f_8 w_i{0};
						// Setup occlusion tester and set active ray mask to just be those with
						// corresponding to tests from hits with the material id being shaded
						OcclusionTester occlusion;
						const auto li = scene.light.sample(dg.point, w_i, occlusion);
						occlusion.rays.active = shade_mask;
						// We just need to flip the sign bit to change occluded mask to unoccluded mask since
						// only the sign bit is used by movemask and blendv
						auto unoccluded = _mm256_xor_ps(occlusion.occluded(scene), _mm256_set1_ps(-0.f));
						if (_mm256_movemask_ps(unoccluded) != 0){
							const auto c = scene.materials[i]->shade(w_o, w_i) * li
								* _mm256_max_ps(w_i.dot(dg.normal), _mm256_set1_ps(0.f));
							shade_mask = _mm256_and_ps(shade_mask, unoccluded);
							color.r = _mm256_blendv_ps(color.r, c.r, shade_mask);
							color.g = _mm256_blendv_ps(color.g, c.g, shade_mask);
							color.b = _mm256_blendv_ps(color.b, c.b, shade_mask);
						}
					}
				}
			}
			target.write_samples(samples, color, packet.active);
		}
	}
}

int main(int, char**){
	const uint32_t width = 800;
	const uint32_t height = 600;
	const auto scene = Scene{
		{
			std::make_shared<Sphere>(Vec3f{0}, 0.5f, 0),
			std::make_shared<Plane>(Vec3f{0, -0.5f, 0.5f}, Vec3f{0, 1, 0}, 1)
		},
		{
			std::make_shared<LambertianMaterial>(Colorf{1, 0, 0}),
			std::make_shared<LambertianMaterial>(Colorf{0, 0, 1})
		},
		PointLight{Vec3f{1, 1, -2}, Colorf{50}}
	};

	const auto camera = PerspectiveCamera{Vec3f{0, 0, -3}, Vec3f{0, 0, 0}, Vec3f{0, 1, 0},
		60.f, static_cast<float>(width) / height};
	auto target = RenderTarget{width, height};
	const auto img_dim = Vec2f_8{static_cast<float>(width), static_cast<float>(height)};
	const uint32_t block_dim = 8;
	auto block_queue = BlockQueue{block_dim, width, height};

	render(scene, camera, img_dim, target, block_queue);

	target.save_image("out.bmp");
}

<|endoftext|>


<commit_before>/*!
 * This file is part of CameraPlus.
 *
 * Copyright (C) 2012-2013 Mohammed Sameer <msameer@foolab.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#if defined(QT4)
#include <QApplication>
#include <QDeclarativeView>
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <QtDeclarative>
#include <QGLWidget>
#elif defined(QT5)
#include <QGuiApplication>
#include <QQuickView>
#include <QQmlError>
#endif

#include "settings.h"
#include "filenaming.h"
#ifdef HARMATTAN
#include "quillitem.h"
#endif
#include "geocode.h"
#include "deviceinfo.h"
#include "soundvolumecontrol.h"
#include "displaystate.h"
#include "fsmonitor.h"
#include "cameraresources.h"
#include "compass.h"
#include "orientation.h"
#include "mountprotector.h"
#include "trackerstore.h"
#include "focusrectangle.h"
#include "sharehelper.h"
#include "deletehelper.h"
#include "galleryhelper.h"
#include "postcapturemodel.h"
#include "batteryinfo.h"
#include "gridlines.h"
#include "devicekeys.h"
#include "platformsettings.h"
#include "dbusservice.h"
#include <MDeclarativeCache>

#ifdef QMLJSDEBUGGER
#include "qt_private/qdeclarativedebughelper_p.h"
#endif /* QMLJSDEBUGGER */

#if defined(QT4)
#include <QAbstractFileEngineHandler>
#include "qmlfileengine.h"

class QmlFileEngineHandler : public QAbstractFileEngineHandler {
  QAbstractFileEngine *create(const QString& fileName) const {
    QString fn = fileName.toLower();
    if (fn.startsWith(':') && fn.endsWith(".qml")) {
      return new QmlFileEngine(fileName);
    }

    return 0;
  }
};
#endif

Q_DECL_EXPORT int main(int argc, char *argv[]) {
#if defined(QT4)
  QApplication::setAttribute(Qt::AA_X11InitThreads, true);
  QApplication *app = new QApplication(argc, argv);

  QmlFileEngineHandler handler;
  Q_UNUSED(handler);

  QDeclarativeView *view = MDeclarativeCache::qDeclarativeView();
#elif defined(QT5)
  QGuiApplication *app = MDeclarativeCache::qApplication(argc, argv);
  QQuickView *view = MDeclarativeCache::qQuickView();
#endif

#ifdef QMLJSDEBUGGER
  QDeclarativeDebugHelper::enableDebugging();
#endif /* QMLJSDEBUGGER */

#if defined(QT4)
  view->setAttribute(Qt::WA_NoSystemBackground);
  view->setViewport(new QGLWidget);
  view->setResizeMode(QDeclarativeView::SizeRootObjectToView);
  view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
  view->viewport()->setAttribute(Qt::WA_NoSystemBackground);
#endif

#if defined(QT5)
  view->setResizeMode(QQuickView::SizeRootObjectToView);
  // TODO:
#endif

  qmlRegisterType<Settings>("CameraPlus", 1, 0, "Settings");
  qmlRegisterType<FileNaming>("CameraPlus", 1, 0, "FileNaming");
#ifdef HARMATTAN
  qmlRegisterType<QuillItem>("CameraPlus", 1, 0, "QuillItem");
#endif
  qmlRegisterType<Geocode>("CameraPlus", 1, 0, "ReverseGeocode");
  qmlRegisterType<DeviceInfo>("CameraPlus", 1, 0, "DeviceInfo");
  qmlRegisterType<SoundVolumeControl>("CameraPlus", 1, 0, "SoundVolumeControl");
  qmlRegisterType<DisplayState>("CameraPlus", 1, 0, "DisplayState");
  qmlRegisterType<FSMonitor>("CameraPlus", 1, 0, "FSMonitor");
  qmlRegisterType<CameraResources>("CameraPlus", 1, 0, "CameraResources");
  qmlRegisterType<Compass>("CameraPlus", 1, 0, "CameraCompass");
  qmlRegisterType<Orientation>("CameraPlus", 1, 0, "CameraOrientation");
  qmlRegisterType<MountProtector>("CameraPlus", 1, 0, "MountProtector");
  qmlRegisterType<TrackerStore>("CameraPlus", 1, 0, "TrackerStore");
  qmlRegisterType<FocusRectangle>("CameraPlus", 1, 0, "FocusRectangle");
  qmlRegisterType<ShareHelper>("CameraPlus", 1, 0, "ShareHelper");
  qmlRegisterType<DeleteHelper>("CameraPlus", 1, 0, "DeleteHelper");
  qmlRegisterType<GalleryHelper>("CameraPlus", 1, 0, "GalleryHelper");
  qmlRegisterType<PostCaptureModel>("CameraPlus", 1, 0, "PostCaptureModel");
  qmlRegisterType<BatteryInfo>("CameraPlus", 1, 0, "BatteryInfo");
  qmlRegisterType<GridLines>("CameraPlus", 1, 0, "GridLines");
  qmlRegisterType<DeviceKeys>("CameraPlus", 1, 0, "DeviceKeys");
  qmlRegisterType<PlatformSettings>("CameraPlus", 1, 0, "PlatformSettings");

  view->setSource(QUrl("qrc:/qml/main.qml"));

#if defined(QT5)
  if (view->status() == QQuickView::Error) {
    qCritical() << "Errors loading QML:";
    QList<QQmlError> errors = view->errors();

    foreach (const QQmlError& error, errors) {
      qCritical() << error.toString();
    }

    delete view;
    delete app;

    return 1;
  }
#endif

  view->showFullScreen();

  int ret = app->exec();

  delete view;
  delete app;

  return ret;
}
<commit_msg>Set applicationName to cameraplus.<commit_after>/*!
 * This file is part of CameraPlus.
 *
 * Copyright (C) 2012-2013 Mohammed Sameer <msameer@foolab.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#if defined(QT4)
#include <QApplication>
#include <QDeclarativeView>
#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <QtDeclarative>
#include <QGLWidget>
#elif defined(QT5)
#include <QGuiApplication>
#include <QQuickView>
#include <QQmlError>
#endif

#include "settings.h"
#include "filenaming.h"
#ifdef HARMATTAN
#include "quillitem.h"
#endif
#include "geocode.h"
#include "deviceinfo.h"
#include "soundvolumecontrol.h"
#include "displaystate.h"
#include "fsmonitor.h"
#include "cameraresources.h"
#include "compass.h"
#include "orientation.h"
#include "mountprotector.h"
#include "trackerstore.h"
#include "focusrectangle.h"
#include "sharehelper.h"
#include "deletehelper.h"
#include "galleryhelper.h"
#include "postcapturemodel.h"
#include "batteryinfo.h"
#include "gridlines.h"
#include "devicekeys.h"
#include "platformsettings.h"
#include "dbusservice.h"
#include <MDeclarativeCache>

#ifdef QMLJSDEBUGGER
#include "qt_private/qdeclarativedebughelper_p.h"
#endif /* QMLJSDEBUGGER */

#if defined(QT4)
#include <QAbstractFileEngineHandler>
#include "qmlfileengine.h"

class QmlFileEngineHandler : public QAbstractFileEngineHandler {
  QAbstractFileEngine *create(const QString& fileName) const {
    QString fn = fileName.toLower();
    if (fn.startsWith(':') && fn.endsWith(".qml")) {
      return new QmlFileEngine(fileName);
    }

    return 0;
  }
};
#endif

Q_DECL_EXPORT int main(int argc, char *argv[]) {
#if defined(QT4)
  QApplication::setAttribute(Qt::AA_X11InitThreads, true);
  QApplication *app = new QApplication(argc, argv);
  app->setApplicationName("cameraplus");

  QmlFileEngineHandler handler;
  Q_UNUSED(handler);

  QDeclarativeView *view = MDeclarativeCache::qDeclarativeView();
#elif defined(QT5)
  QGuiApplication *app = MDeclarativeCache::qApplication(argc, argv);
  app->setApplicationName("cameraplus");

  QQuickView *view = MDeclarativeCache::qQuickView();
#endif

#ifdef QMLJSDEBUGGER
  QDeclarativeDebugHelper::enableDebugging();
#endif /* QMLJSDEBUGGER */

#if defined(QT4)
  view->setAttribute(Qt::WA_NoSystemBackground);
  view->setViewport(new QGLWidget);
  view->setResizeMode(QDeclarativeView::SizeRootObjectToView);
  view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
  view->viewport()->setAttribute(Qt::WA_NoSystemBackground);
#endif

#if defined(QT5)
  view->setResizeMode(QQuickView::SizeRootObjectToView);
  // TODO:
#endif

  qmlRegisterType<Settings>("CameraPlus", 1, 0, "Settings");
  qmlRegisterType<FileNaming>("CameraPlus", 1, 0, "FileNaming");
#ifdef HARMATTAN
  qmlRegisterType<QuillItem>("CameraPlus", 1, 0, "QuillItem");
#endif
  qmlRegisterType<Geocode>("CameraPlus", 1, 0, "ReverseGeocode");
  qmlRegisterType<DeviceInfo>("CameraPlus", 1, 0, "DeviceInfo");
  qmlRegisterType<SoundVolumeControl>("CameraPlus", 1, 0, "SoundVolumeControl");
  qmlRegisterType<DisplayState>("CameraPlus", 1, 0, "DisplayState");
  qmlRegisterType<FSMonitor>("CameraPlus", 1, 0, "FSMonitor");
  qmlRegisterType<CameraResources>("CameraPlus", 1, 0, "CameraResources");
  qmlRegisterType<Compass>("CameraPlus", 1, 0, "CameraCompass");
  qmlRegisterType<Orientation>("CameraPlus", 1, 0, "CameraOrientation");
  qmlRegisterType<MountProtector>("CameraPlus", 1, 0, "MountProtector");
  qmlRegisterType<TrackerStore>("CameraPlus", 1, 0, "TrackerStore");
  qmlRegisterType<FocusRectangle>("CameraPlus", 1, 0, "FocusRectangle");
  qmlRegisterType<ShareHelper>("CameraPlus", 1, 0, "ShareHelper");
  qmlRegisterType<DeleteHelper>("CameraPlus", 1, 0, "DeleteHelper");
  qmlRegisterType<GalleryHelper>("CameraPlus", 1, 0, "GalleryHelper");
  qmlRegisterType<PostCaptureModel>("CameraPlus", 1, 0, "PostCaptureModel");
  qmlRegisterType<BatteryInfo>("CameraPlus", 1, 0, "BatteryInfo");
  qmlRegisterType<GridLines>("CameraPlus", 1, 0, "GridLines");
  qmlRegisterType<DeviceKeys>("CameraPlus", 1, 0, "DeviceKeys");
  qmlRegisterType<PlatformSettings>("CameraPlus", 1, 0, "PlatformSettings");

  view->setSource(QUrl("qrc:/qml/main.qml"));

#if defined(QT5)
  if (view->status() == QQuickView::Error) {
    qCritical() << "Errors loading QML:";
    QList<QQmlError> errors = view->errors();

    foreach (const QQmlError& error, errors) {
      qCritical() << error.toString();
    }

    delete view;
    delete app;

    return 1;
  }
#endif

  view->showFullScreen();

  int ret = app->exec();

  delete view;
  delete app;

  return ret;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <SDL2/SDL.h>
#include "draw.hpp"

const char * game_name = "Game Of Life On Surface";
int screen_width = 640;
int screen_height = 640;
bool quit_flag = false;
SDL_Window * window = NULL;
SDL_Renderer * render = NULL;
SDL_Event event;

void game_send_error( int code ) {
    printf( "[error]: %s\n", SDL_GetError() );
    exit( code );
}

void game_event( SDL_Event * event ) {
    SDL_PollEvent( event );
    switch ( event->type ) {
        case SDL_QUIT:
            quit_flag = true;
            break;
        case SDL_KEYDOWN:
            switch ( event->key.keysym.sym ) {
                case SDLK_ESCAPE:
                    quit_flag = true;
                    break;
                default:
                    break;
            }
        default:
            break;
    }
}

void game_loop( void ) {
    // insert code
}

void draw_point( int x, int y, int size ) {
    SDL_Rect rect = { x, y, size, size };
    SDL_RenderFillRect( render, &rect );
}

void game_render( void ) {
    SDL_RenderClear( render );
    set_coloru( COLOR_WHITE );
    for ( int size = 0; size < 200; size += 10 ) {
        draw_ellipse( 100, 300 - size + 20, 200, size );
        draw_ellipse( 120, 300 - size, 200, size, M_PI / 2.0f );
    }
    draw_ellipse( 100, 120, 200, 200 );
    set_coloru( COLOR_BLACK );
    SDL_RenderPresent( render );
}

void game_destroy( void ) {
    SDL_DestroyRenderer( render );
    SDL_DestroyWindow( window );
    SDL_Quit();
}

void game_init( void ) {
    SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS );
    window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                               screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
    if ( window == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC |
                                 SDL_RENDERER_TARGETTEXTURE );
    if ( render == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND );
    draw_init( render );
}

int main( int argc, char * argv[] ) {
    Uint32 FPS_MAX = 1000 / 63; // ~ 60 fps

    game_init();
    while ( quit_flag == false ) {
        game_event( &event );
        game_loop();
        game_render();
        SDL_Delay( FPS_MAX );
    }
    game_destroy();
    return EXIT_SUCCESS;
}<commit_msg>size % 16 == 0<commit_after>#include <cstdio>
#include <SDL2/SDL.h>
#include "draw.hpp"

const char * game_name = "Game Of Life On Surface";
int screen_width = 640;
int screen_height = 640;
bool quit_flag = false;
SDL_Window * window = NULL;
SDL_Renderer * render = NULL;
SDL_Event event;

void game_send_error( int code ) {
    printf( "[error]: %s\n", SDL_GetError() );
    exit( code );
}

void game_event( SDL_Event * event ) {
    SDL_PollEvent( event );
    switch ( event->type ) {
        case SDL_QUIT:
            quit_flag = true;
            break;
        case SDL_KEYDOWN:
            switch ( event->key.keysym.sym ) {
                case SDLK_ESCAPE:
                    quit_flag = true;
                    break;
                default:
                    break;
            }
        default:
            break;
    }
}

void game_loop( void ) {
    // insert code
}

void draw_point( int x, int y, int size ) {
    SDL_Rect rect = { x, y, size, size };
    SDL_RenderFillRect( render, &rect );
}

void game_render( void ) {
    SDL_RenderClear( render );
    set_coloru( COLOR_WHITE );
    for ( int size = 0; size <= 192; size += 16 ) {
        draw_ellipse( 100, 300 - size + 20, 200, size );
        draw_ellipse( 120, 300 - size, 200, size, M_PI / 2.0f );
    }
    set_coloru( COLOR_BLACK );
    SDL_RenderPresent( render );
}

void game_destroy( void ) {
    SDL_DestroyRenderer( render );
    SDL_DestroyWindow( window );
    SDL_Quit();
}

void game_init( void ) {
    SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS );
    window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                               screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
    if ( window == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC |
                                 SDL_RENDERER_TARGETTEXTURE );
    if ( render == NULL ) {
        game_send_error( EXIT_FAILURE );
    }
    SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND );
    draw_init( render );
}

int main( int argc, char * argv[] ) {
    Uint32 FPS_MAX = 1000 / 63; // ~ 60 fps

    game_init();
    while ( quit_flag == false ) {
        game_event( &event );
        game_loop();
        game_render();
        SDL_Delay( FPS_MAX );
    }
    game_destroy();
    return EXIT_SUCCESS;
}<|endoftext|>


<commit_before>/*
 * main.cpp
 * Copyright (c) 2015 Markus Himmel. All rights reserved.
 * Distributed under the terms of the MIT license.
 */

#include <algorithm>
#include <iostream>

#include <Directory.h>
#include <FindDirectory.h>
#include <Path.h>
#include <String.h>

#include "BookmarksTree.h"
#include "BookmarksFormat.h"

int helpMessage(int code, BookmarksOutput* a, BookmarksInput* b)
{
	delete a;
	delete b;
	std::cout	<< "Converts browser bookmarks between a selection of formats."
				<< std::endl << std::endl
				<< "Usage: bookmarkconverter -f [format] [inputpath]"
				<< " [outputpath]" << std::endl
				<< "       bookmarkconverter --help" << std::endl
				<< std::endl
				<< "       format            "
				<< "The destination format (HTML, CHROME, WEBPOSITIVE, "
				<< "QUPZILLA)" << std::endl;

	BPath dir;
	if (find_directory(B_USER_SETTINGS_DIRECTORY, &dir) == B_OK) {
		BString path(dir.Path());
		std::cout << std::endl << "The default path for QupZilla bookmarks is:"
			<< std::endl << "\t" << path <<
			"/Qt/.config/qupzilla/profiles/default/bookmarks.json"
			<< std::endl << "The default path for WebPositive bookmarks is:"
			<< std::endl << "\t" << path << "/WebPositive/Bookmarks"
			<< std::endl << std::endl;
	}

	return code;
}

int main(int argc, char* argv[])
{
	BookmarksOutput* output = NULL;
	BookmarksInput* input = NULL;
	int curarg = 0, curpath = 0;;
	BString paths[2];

	while (curarg + 1 < argc) {
		curarg++;
		BString current(argv[curarg]);
		if (current == "-h" || current == "--help")
			return helpMessage(0, output, input);
		else if (current == "-f" || current == "--format") {
			if (curarg == argc - 1)
				return helpMessage(1, output, input);
			else {
				curarg++;
				BString format(argv[curarg]);
				if (format.ICompare("html") == 0)
					output = new HTMLOutput();
				else if (format.ICompare("chrome") == 0)
					output = new ChromeOutput();
				else if (format.ICompare("webpositive") == 0)
					output = new BeOutput();
				else if (format.ICompare("qupzilla") == 0)
					output = new QupZillaOutput();
				else
					return helpMessage(2, output, input);
			}
		} else if (current == "--webpositive-import") {
			input = new BeInput();
			paths[0] = "";
			curpath = std::max(curpath, 1);
		} else if (current == "--qupzilla-import") {
			input = new QupZillaInput();
			paths[0] = "";
			curpath = std::max(curpath, 1);
		} else if (curpath >= 2)
			return helpMessage(5, output, input);
		else
			paths[curpath++] = argv[curarg];

	}

	if (paths[0] == "")
		return helpMessage(3, output, input);

	if (input == NULL) {
		BDirectory test(paths[0].String());
		input = (test.InitCheck() == B_OK) ?
			new BeInput() : new QupZillaInput();
	}

	if (output == NULL)
		return helpMessage(4, output, input);

	BookmarksEntry* read = input->Input(paths[0].String());
	if (read != NULL)
		output->Output(read, paths[1].String());
	else
		std::cerr << "There was an error reading the input" << std::endl;

	delete input;
	delete output;
	return 0;
}

<commit_msg>fix build on gcc5 (#1)<commit_after>/*
 * main.cpp
 * Copyright (c) 2015 Markus Himmel. All rights reserved.
 * Distributed under the terms of the MIT license.
 */

#include <algorithm>
#include <iostream>

#include <Directory.h>
#include <FindDirectory.h>
#include <Path.h>
#include <String.h>

#include "BookmarksTree.h"
#include "BookmarksFormat.h"

int helpMessage(int code, BookmarksOutput* a, BookmarksInput* b)
{
	delete a;
	delete b;
	std::cout	<< "Converts browser bookmarks between a selection of formats."
				<< std::endl << std::endl
				<< "Usage: bookmarkconverter -f [format] [inputpath]"
				<< " [outputpath]" << std::endl
				<< "       bookmarkconverter --help" << std::endl
				<< std::endl
				<< "       format            "
				<< "The destination format (HTML, CHROME, WEBPOSITIVE, "
				<< "QUPZILLA)" << std::endl;

	BPath dir;
	if (find_directory(B_USER_SETTINGS_DIRECTORY, &dir) == B_OK) {
		BString path(dir.Path());
		std::cout << std::endl << "The default path for QupZilla bookmarks is:"
			<< std::endl << "\t" << path <<
			"/Qt/.config/qupzilla/profiles/default/bookmarks.json"
			<< std::endl << "The default path for WebPositive bookmarks is:"
			<< std::endl << "\t" << path << "/WebPositive/Bookmarks"
			<< std::endl << std::endl;
	}

	return code;
}

int main(int argc, char* argv[])
{
	BookmarksOutput* output = NULL;
	BookmarksInput* input = NULL;
	int curarg = 0, curpath = 0;;
	BString paths[2];

	while (curarg + 1 < argc) {
		curarg++;
		BString current(argv[curarg]);
		if (current == "-h" || current == "--help")
			return helpMessage(0, output, input);
		else if (current == "-f" || current == "--format") {
			if (curarg == argc - 1)
				return helpMessage(1, output, input);
			else {
				curarg++;
				BString format(argv[curarg]);
				if (format.ICompare("html") == 0)
					output = new HTMLOutput();
				else if (format.ICompare("chrome") == 0)
					output = new ChromeOutput();
				else if (format.ICompare("webpositive") == 0)
					output = new BeOutput();
				else if (format.ICompare("qupzilla") == 0)
					output = new QupZillaOutput();
				else
					return helpMessage(2, output, input);
			}
		} else if (current == "--webpositive-import") {
			input = new BeInput();
			paths[0] = "";
			curpath = std::max(curpath, 1);
		} else if (current == "--qupzilla-import") {
			input = new QupZillaInput();
			paths[0] = "";
			curpath = std::max(curpath, 1);
		} else if (curpath >= 2)
			return helpMessage(5, output, input);
		else
			paths[curpath++] = argv[curarg];

	}

	if (paths[0] == "")
		return helpMessage(3, output, input);

	if (input == NULL) {
		BDirectory test(paths[0].String());
		if (test.InitCheck() == B_OK)
			input = new BeInput();
		else
			input = new QupZillaInput();
	}

	if (output == NULL)
		return helpMessage(4, output, input);

	BookmarksEntry* read = input->Input(paths[0].String());
	if (read != NULL)
		output->Output(read, paths[1].String());
	else
		std::cerr << "There was an error reading the input" << std::endl;

	delete input;
	delete output;
	return 0;
}

<|endoftext|>


<commit_before>#include "helpers.h"
#include "domain/Card.h"
#include "domain/IncomingRequest.h"
#include "domain/DataKey.h"
#include "domain/Config.h"
#include "domain/Card.h"
#include <iostream>

#include <util/util_config.h>
#if defined(YBUTIL_WINDOWS)
#include <rpc.h>
#else
#include <unistd.h>
#include <fcntl.h>
#endif
#if defined(YB_USE_WX)
#include <wx/app.h>
#elif defined(YB_USE_QT)
#include <QCoreApplication>
#endif
#include <iostream>
#include <util/string_utils.h>
#include <util/element_tree.h>

using namespace Domain;
using namespace std;
using namespace Yb;

ElementTree::ElementPtr mk_resp(const string &status,
        const string &status_code = "")
{
    ElementTree::ElementPtr res = ElementTree::new_element("response");
    res->sub_element("status", status);
    if (!status_code.empty())
        res->sub_element("status_code", status_code);
    char buf[40];
    MilliSec t = get_cur_time_millisec();
    sprintf(buf, "%u.%03u", (unsigned)(t/1000), (unsigned)(t%1000));
    res->sub_element("ts", buf);
    return res;
}

Yb::LongInt
get_random()
{
    Yb::LongInt buf;
#if defined(__WIN32__) || defined(_WIN32)
    UUID new_uuid;
    UuidCreate(&new_uuid);
    buf = new_uuid.Data1;
    buf <<= 32;
    Yb::LongInt buf2 = (new_uuid.Data2 << 16) | new_uuid.Data3;
    buf += buf2;
#else
    int fd = open("/dev/urandom", O_RDONLY);
    if (fd == -1)
        throw std::runtime_error("can't open /dev/urandom");
    if (read(fd, &buf, sizeof(buf)) != sizeof(buf)) {
        close(fd);
        throw std::runtime_error("can't read from /dev/urandom");
    }
    close(fd);
#endif
    return buf;
}

ElementTree::ElementPtr bind_card(Session &session, ILogger &logger,
        const StringDict &params)
{

    ElementTree::ElementPtr resp = mk_resp("success");
    Domain::Card card;
    Yb::LongInt token = get_random();
    card.card_token = token;
    card.dt = Yb::now();
    card.pan = params["pan"];/*convert data to string*/
    card.expire_dt = Yb::dt_make(params.get_as<int>("expire_year"), params.get_as<int>("expire_month"), 1);/*convert string to date*/
    card.card_holder = params["card_holder"];
    std::string pan_m1 =  params["pan"].substr(0,6);
    std::string pan_m2 =  params["pan"].substr(16,20);
    card.pan_masked = pan_m1 + "****" + pan_m2;
    card.save(session);
    session.commit();
    int card_id = card.id;

    resp->sub_element("card_id",Yb::to_string(card_id));
    resp->sub_element("card_holder",card.card_holder);
    resp->sub_element("pan_masked", card.pan_masked);
    std::string expire_dtYear =Yb::to_string(params.get_as<string>("expire_year"));/*convert data to string*/
    std::string expire_dtMonth =Yb::to_string(params.get_as<string>("expire_month"));/*convert data to string*/
    std::string expire_dtCD = expire_dtMonth +"/"+ expire_dtYear;
    resp->sub_element("expire.dt",expire_dtCD);

    return resp;
}

typedef ElementTree::ElementPtr (*HttpHandler)(
        Session &session, ILogger &logger,
        const StringDict &params);

class CardProxyHttpWrapper
{
    string name_, default_status_;
    HttpHandler f_;
    string dump_result(ILogger &logger, ElementTree::ElementPtr res)
    {
        string res_str = res->serialize();
        logger.info("result: " + res_str);
        return res_str;
    }
public:
    CardProxyHttpWrapper(): f_(NULL) {}
    CardProxyHttpWrapper(const string &name, HttpHandler f,
            const string &default_status = "not_available")
        : name_(name), default_status_(default_status), f_(f)
    {}
    const string &name() const { return name_; }
    string operator() (const StringDict &params)
    {
        ILogger::Ptr logger(theApp::instance().new_logger(name_));
        TimerGuard t(*logger);
        try {
            logger->info("started, params: " + dict2str(params));
            //int version = params.get_as<int>("version");
            //YB_ASSERT(version >= 2);
            auto_ptr<Session> session(
                    theApp::instance().new_session());
            ElementTree::ElementPtr res = f_(*session, *logger, params);
            session->commit();
            t.set_ok();
            return dump_result(*logger, res);
        }
        catch (const ApiResult &ex) {
            t.set_ok();
            return dump_result(*logger, ex.result());
        }
        catch (const exception &ex) {
            logger->error(string("exception: ") + ex.what());
            return dump_result(*logger, mk_resp(default_status_));
        }
    }
};

#define WRAP(func) CardProxyHttpWrapper(#func, func)

int main(int argc, char *argv[])
{
    string log_name = "card_proxy.log";
    string db_name = "card_proxy_db";
    string error_content_type = "text/xml";
    string error_body = mk_resp("internal_error")->serialize();
    string prefix = "/card_bind/";
    int port = 9119;
    CardProxyHttpWrapper handlers[] = {
        WRAP(bind_card),
    };
    int n_handlers = sizeof(handlers)/sizeof(handlers[0]);
    return run_server_app(log_name, db_name, port,
            handlers, n_handlers, error_content_type, error_body, prefix);
}

// vim:ts=4:sts=4:sw=4:et:
<commit_msg>find card<commit_after>#include "helpers.h"
#include "domain/Card.h"
#include "domain/IncomingRequest.h"
#include "domain/DataKey.h"
#include "domain/Config.h"
#include "domain/Card.h"
#include <iostream>

#include <util/util_config.h>
#if defined(YBUTIL_WINDOWS)
#include <rpc.h>
#else
#include <unistd.h>
#include <fcntl.h>
#endif
#if defined(YB_USE_WX)
#include <wx/app.h>
#elif defined(YB_USE_QT)
#include <QCoreApplication>
#endif
#include <iostream>
#include <util/string_utils.h>
#include <util/element_tree.h>

using namespace Domain;
using namespace std;
using namespace Yb;

ElementTree::ElementPtr mk_resp(const string &status,
        const string &status_code = "")
{
    ElementTree::ElementPtr res = ElementTree::new_element("response");
    res->sub_element("status", status);
    if (!status_code.empty())
        res->sub_element("status_code", status_code);
    char buf[40];
    MilliSec t = get_cur_time_millisec();
    sprintf(buf, "%u.%03u", (unsigned)(t/1000), (unsigned)(t%1000));
    res->sub_element("ts", buf);
    return res;
}

Yb::LongInt
get_random()
{
    Yb::LongInt buf;
#if defined(__WIN32__) || defined(_WIN32)
    UUID new_uuid;
    UuidCreate(&new_uuid);
    buf = new_uuid.Data1;
    buf <<= 32;
    Yb::LongInt buf2 = (new_uuid.Data2 << 16) | new_uuid.Data3;
    buf += buf2;
#else
    int fd = open("/dev/urandom", O_RDONLY);
    if (fd == -1)
        throw std::runtime_error("can't open /dev/urandom");
    if (read(fd, &buf, sizeof(buf)) != sizeof(buf)) {
        close(fd);
        throw std::runtime_error("can't read from /dev/urandom");
    }
    close(fd);
#endif
    return buf;
}

ElementTree::ElementPtr bind_card(Session &session, ILogger &logger,
        const StringDict &params)
{

    ElementTree::ElementPtr resp = mk_resp("success");
    Domain::Card card;

    Yb::LongInt token = get_random();
    card.card_token = token;
    card.dt = Yb::now();
    card.pan = params["pan"];

    Card rs = Yb::query<Card>(session)
      .filter_by(Card::c.pan == params["pan"]).one();

    card.expire_dt = Yb::dt_make(params.get_as<int>("expire_year"), params.get_as<int>("expire_month"), 1);/*convert string to date*/
    card.card_holder = params["card_holder"];
    std::string pan_m1 =  params["pan"].substr(0,6);
    std::string pan_m2 =  params["pan"].substr(16,20);
    card.pan_masked = pan_m1 + "****" + pan_m2;
    card.save(session);
    session.commit();
    int card_id = card.id;

    resp->sub_element("card_id",Yb::to_string(card_id));
    resp->sub_element("card_holder",card.card_holder);
    resp->sub_element("pan_masked", card.pan_masked);
    std::string expire_dtYear = Yb::to_string(params.get_as<string>("expire_year"));/*convert data to string*/
    std::string expire_dtMonth =Yb::to_string(params.get_as<string>("expire_month"));/*convert data to string*/
    std::string expire_dtCD = expire_dtMonth +"/"+ expire_dtYear;
    resp->sub_element("expire.dt",expire_dtCD);

    return resp;
}

typedef ElementTree::ElementPtr (*HttpHandler)(
        Session &session, ILogger &logger,
        const StringDict &params);

class CardProxyHttpWrapper
{
    string name_, default_status_;
    HttpHandler f_;
    string dump_result(ILogger &logger, ElementTree::ElementPtr res)
    {
        string res_str = res->serialize();
        logger.info("result: " + res_str);
        return res_str;
    }
public:
    CardProxyHttpWrapper(): f_(NULL) {}
    CardProxyHttpWrapper(const string &name, HttpHandler f,
            const string &default_status = "not_available")
        : name_(name), default_status_(default_status), f_(f)
    {}
    const string &name() const { return name_; }
    string operator() (const StringDict &params)
    {
        ILogger::Ptr logger(theApp::instance().new_logger(name_));
        TimerGuard t(*logger);
        try {
            logger->info("started, params: " + dict2str(params));
            //int version = params.get_as<int>("version");
            //YB_ASSERT(version >= 2);
            auto_ptr<Session> session(
                    theApp::instance().new_session());
            ElementTree::ElementPtr res = f_(*session, *logger, params);
            session->commit();
            t.set_ok();
            return dump_result(*logger, res);
        }
        catch (const ApiResult &ex) {
            t.set_ok();
            return dump_result(*logger, ex.result());
        }
        catch (const exception &ex) {
            logger->error(string("exception: ") + ex.what());
            return dump_result(*logger, mk_resp(default_status_));
        }
    }
};

#define WRAP(func) CardProxyHttpWrapper(#func, func)

int main(int argc, char *argv[])
{
    string log_name = "card_proxy.log";
    string db_name = "card_proxy_db";
    string error_content_type = "text/xml";
    string error_body = mk_resp("internal_error")->serialize();
    string prefix = "/card_bind/";
    int port = 9119;
    CardProxyHttpWrapper handlers[] = {
        WRAP(bind_card),
    };
    int n_handlers = sizeof(handlers)/sizeof(handlers[0]);
    return run_server_app(log_name, db_name, port,
            handlers, n_handlers, error_content_type, error_body, prefix);
}

// vim:ts=4:sts=4:sw=4:et:
<|endoftext|>


<commit_before>// Onut includes
#include <onut/ActionManager.h>
#include <onut/AudioEngine.h>
//#include <onut/Cloud.h>
#include <onut/ComponentFactory.h>
#include <onut/ContentManager.h>
#include <onut/Dispatcher.h>
#include <onut/SceneManager.h>
#include <onut/Font.h>
#include <onut/GamePad.h>
#include <onut/Input.h>
#include <onut/Http.h>
#include <onut/Log.h>
#include <onut/Multiplayer.h>
#include <onut/onut.h>
#include <onut/ParticleSystemManager.h>
#include <onut/PrimitiveBatch.h>
#include <onut/Random.h>
#include <onut/Renderer.h>
#include <onut/Settings.h>
#include <onut/SpriteBatch.h>
#include <onut/Texture.h>
#include <onut/ThreadPool.h>
#include <onut/Timing.h>
#include <onut/UIContext.h>
#include <onut/UIControl.h>
#include <onut/UIPanel.h>
#include <onut/UITextBox.h>
#include <onut/Updater.h>
#include <onut/Window.h>

// Private
#include "JSBindings.h"

// STL
#include <cassert>
#include <mutex>
#include <sstream>

OTextureRef g_pMainRenderTarget;

std::atomic<bool> g_bIsRunning;

namespace onut
{
    void createUI()
    {
        oUIContext = UIContext::create(Vector2(OScreenWf, OScreenHf));
        oUI = UIControl::create();
        oUI->widthType = UIControl::DimType::Relative;
        oUI->heightType = UIControl::DimType::Relative;

        oUIContext->addTextCaretSolver<onut::UITextBox>("", [=](const OUITextBoxRef& pTextBox, const Vector2& localPos) -> decltype(std::string().size())
        {
            auto pFont = OGetFont(pTextBox->textComponent.font.typeFace.c_str());
            if (!pFont) return 0;
            auto& text = pTextBox->textComponent.text;
            return pFont->caretPos(text, localPos.x - 4);
        });

        oWindow->onWrite = [](char c)
        {
            oUIContext->write(c);
        };
        oWindow->onKey = [](uintptr_t key)
        {
            oUIContext->keyDown(key);
        };

        oUIContext->addStyle<onut::UIPanel>("blur", [](const OUIPanelRef& pPanel, const Rect& rect)
        {
            oSpriteBatch->end();
            if (oRenderer->renderStates.renderTarget.get())
            {
                oRenderer->renderStates.renderTarget.get()->blur();
            }
            oSpriteBatch->begin();
            oSpriteBatch->drawRect(nullptr, (rect), pPanel->color);
        });
    }

    void createServices()
    {
        // Random
        randomizeSeed();

        // Thread pool
        if (!oThreadPool) oThreadPool = OThreadPool::create();

        // Dispatcher
        if (!oDispatcher) oDispatcher = ODispatcher::create();

        // Timing class
        if (!oTiming) oTiming = OTiming::create();

        // Updater
        if (!oUpdater) oUpdater = OUpdater::create();

        // Window
        if (!oWindow) oWindow = OWindow::create();

        // Renderer
        if (!oRenderer)
        {
            oRenderer = ORenderer::create(oWindow);
            oRenderer->init(oWindow);
        }

        // SpriteBatch
        if (!oSpriteBatch) oSpriteBatch = SpriteBatch::create();
        if (!oPrimitiveBatch) oPrimitiveBatch = PrimitiveBatch::create();

        // Content
        if (!oContentManager) oContentManager = ContentManager::create();

        // Cloud
        //oCloud = Cloud::create(oSettings->getAppId(), oSettings->getAppSecret());

        // Mouse/Keyboard
        if (!oInput) oInput = OInput::create(oWindow);

        // Audio
        if (!oAudioEngine) oAudioEngine = AudioEngine::create();

        // Particles
        if (!oParticleSystemManager) oParticleSystemManager = ParticleSystemManager::create();

        // Http
        if (!oHttp) oHttp = Http::create();

        // Multiplayer
        if (!oMultiplayer) oMultiplayer = Multiplayer::create();

        // UI Context
        createUI();

        // Component factory
        if (!oComponentFactory)
        {
            oComponentFactory = ComponentFactory::create();
            oComponentFactory->registerDefaultComponents();
        }

        // Entity Manager
        if (!oSceneManager) oSceneManager = SceneManager::create();

        // Undo/Redo for editors
        if (!oActionManager) oActionManager = ActionManager::create();

        g_pMainRenderTarget = OTexture::createScreenRenderTarget();

        // Initialize Javascript
        onut::js::init();
    }

    void cleanup()
    {
        onut::js::shutdown();

        g_pMainRenderTarget = nullptr;
        oActionManager = nullptr;
        oSceneManager = nullptr;
        oComponentFactory = nullptr;
        oDispatcher = nullptr;
        oUpdater = nullptr;
        oUI = nullptr;
        oUIContext = nullptr;
        oMultiplayer = nullptr;
        oHttp = nullptr;
        oParticleSystemManager = nullptr;
        oAudioEngine = nullptr;
        oInput = nullptr;
        //oCloud = nullptr;
        oContentManager = nullptr;
        oPrimitiveBatch = nullptr;
        oSpriteBatch = nullptr;
        oRenderer = nullptr;
        oWindow = nullptr;
        oSettings = nullptr;
        oThreadPool = nullptr;
        oTiming = nullptr;
    }

    // Start the engine
    void run(std::function<void()> initCallback,
             std::function<void()> updateCallback,
             std::function<void()> renderCallback,
             std::function<void()> postRenderCallback)
    {
        // Make sure we run just once
        static bool alreadyRan = false;
        assert(!alreadyRan);
        alreadyRan = true;

        createServices();

        // Call the user defined init
        if (initCallback)
        {
            initCallback();
        }

        // Main loop
        g_bIsRunning = true;
        while (true)
        {
            if (!oWindow->pollEvents()) break;
            if (!g_bIsRunning) break;

            // Sync to main callbacks
            oDispatcher->processQueue();

            // Update
            oAudioEngine->update();
            auto framesToUpdate = oTiming->update(oSettings->getIsFixedStep());
            while (framesToUpdate--)
            {
                oInput->update();
#if defined(__rpi__)
                if (OInputPressed(OKeyLeftAlt) && OInputPressed(OKeyF4))
                {
                    g_bIsRunning = false;
                    break;
                }
#endif
#if defined(WIN32)
                POINT cur;
                GetCursorPos(&cur);
                ScreenToClient(oWindow->getHandle(), &cur);
                oInput->mousePos.x = cur.x;
                oInput->mousePos.y = cur.y;
                oInput->mousePosf.x = static_cast<float>(cur.x);
                oInput->mousePosf.y = static_cast<float>(cur.y);
#endif // WIN32
                oUpdater->update();
                auto mousePosf = OGetMousePos();
                if (oUIContext->useNavigation)
                {
                    oUI->update(oUIContext, Vector2(mousePosf.x, mousePosf.y),
                                OGamePadPressed(OGamePadA) || OInputJustPressed(OKeyEnter) || OInputJustPressed(OXArcadeLButton1),
                                false, false,
                                OGamePadJustPressed(OGamePadDPadLeft) || OGamePadJustPressed(OGamePadLeftThumbLeft) || OInputJustPressed(OKeyLeft) || OInputJustPressed(OXArcadeLJoyLeft),
                                OGamePadJustPressed(OGamePadDPadRight) || OGamePadJustPressed(OGamePadLeftThumbRight) || OInputJustPressed(OKeyRight) || OInputJustPressed(OXArcadeLJoyRight),
                                OGamePadJustPressed(OGamePadDPadUp) || OGamePadJustPressed(OGamePadLeftThumbUp) || OInputJustPressed(OKeyUp) || OInputJustPressed(OXArcadeLJoyUp),
                                OGamePadJustPressed(OGamePadDPadDown) || OGamePadJustPressed(OGamePadLeftThumbDown) || OInputJustPressed(OKeyDown) || OInputJustPressed(OXArcadeLJoyDown),
                                0.f);
                }
                else
                {
                    oUI->update(oUIContext, Vector2(mousePosf.x, mousePosf.y),
                                OInputPressed(OMouse1), OInputPressed(OMouse2), OInputPressed(OMouse3),
                                false, false, false, false,
                                OInputPressed(OKeyLeftControl), oInput->getStateValue(OMouseZ));
                }
                oParticleSystemManager->update();
                oSceneManager->update();
                onut::js::update(oTiming->getDeltaTime());
                if (updateCallback)
                {
                    updateCallback();
                }
            }

            // Render
            oTiming->render();
            if (oSettings->getShowOnScreenLog() && oSettings->getIsRetroMode())
            {
                oRenderer->clear(Color::Black);
            }
          //  oRenderer->renderStates.renderTarget = g_pMainRenderTarget;
            oRenderer->beginFrame();
            onut::js::render();
            if (renderCallback)
            {
                renderCallback();
            }
            oSceneManager->render();
            oParticleSystemManager->render();
            oSpriteBatch->begin();
            oUI->render(oUIContext);
            oSpriteBatch->end();

            // Draw final render target
          /*  oRenderer->renderStates.renderTarget = nullptr;
            const auto& res = oRenderer->getResolution();
            oRenderer->renderStates.viewport = iRect{0, 0, res.x, res.y};
            oRenderer->renderStates.scissorEnabled = false;
            oRenderer->renderStates.scissor = oRenderer->renderStates.viewport.get();
            oSpriteBatch->begin();
            oSpriteBatch->changeBlendMode(OBlendOpaque);
            oSpriteBatch->changeFiltering(OFilterNearest);
            oSpriteBatch->drawRect(g_pMainRenderTarget, ORectSmartFit(Rect{0, 0, OScreenf}, g_pMainRenderTarget->getSizef()));
*/
            // Show the log
            if (oSettings->getShowOnScreenLog())
            {
                onut::drawLog();
            }
            oSpriteBatch->end();
            oSpriteBatch->changeBlendMode(OBlendAlpha);
            oSpriteBatch->changeFiltering(OFilterLinear);

            if (postRenderCallback)
            {
                postRenderCallback();
            }

            if (oSettings->getShowFPS())
            {
                auto pFont = OGetFont("font.fnt");
                if (pFont)
                {
                    pFont->draw("FPS: " + std::to_string(oTiming->getFPS()), { 0, 0 });
                }
            }

            oRenderer->endFrame();
        }

        cleanup();
    }

    void quit()
    {
#if defined(WIN32)
        PostQuitMessage(0);
#else
		g_bIsRunning = false;
#endif
    }
}

// Main
void initSettings();
void init();
void update();
void render();
void postRender();

std::vector<std::string> OArguments;

#if defined(WIN32)
#include <Windows.h>

int CALLBACK WinMain(HINSTANCE appInstance, HINSTANCE prevInstance, LPSTR cmdLine, int cmdCount)
{
    int argc;
    auto cmdLineW = onut::utf8ToUtf16(cmdLine);
    if (!cmdLineW.empty())
    {
        auto argvW = CommandLineToArgvW(cmdLineW.c_str(), &argc);
        for (int i = 0; i < argc; ++i)
        {
            OArguments.push_back(onut::utf16ToUtf8(argvW[i]));
        }
    }
    initSettings();
    onut::initLog();
    onut::run(init, update, render, postRender);
    return 0;
}
#else
int main(int argc, char** argv)
{
    for (int i = 0; i < argc; ++i)
    {
        OArguments.push_back(argv[i]);
    }

    initSettings();
    onut::run(init, update, render, postRender);
    return 0;
}
#endif
<commit_msg>added back RT<commit_after>// Onut includes
#include <onut/ActionManager.h>
#include <onut/AudioEngine.h>
//#include <onut/Cloud.h>
#include <onut/ComponentFactory.h>
#include <onut/ContentManager.h>
#include <onut/Dispatcher.h>
#include <onut/SceneManager.h>
#include <onut/Font.h>
#include <onut/GamePad.h>
#include <onut/Input.h>
#include <onut/Http.h>
#include <onut/Log.h>
#include <onut/Multiplayer.h>
#include <onut/onut.h>
#include <onut/ParticleSystemManager.h>
#include <onut/PrimitiveBatch.h>
#include <onut/Random.h>
#include <onut/Renderer.h>
#include <onut/Settings.h>
#include <onut/SpriteBatch.h>
#include <onut/Texture.h>
#include <onut/ThreadPool.h>
#include <onut/Timing.h>
#include <onut/UIContext.h>
#include <onut/UIControl.h>
#include <onut/UIPanel.h>
#include <onut/UITextBox.h>
#include <onut/Updater.h>
#include <onut/Window.h>

// Private
#include "JSBindings.h"

// STL
#include <cassert>
#include <mutex>
#include <sstream>

OTextureRef g_pMainRenderTarget;

std::atomic<bool> g_bIsRunning;

namespace onut
{
    void createUI()
    {
        oUIContext = UIContext::create(Vector2(OScreenWf, OScreenHf));
        oUI = UIControl::create();
        oUI->widthType = UIControl::DimType::Relative;
        oUI->heightType = UIControl::DimType::Relative;

        oUIContext->addTextCaretSolver<onut::UITextBox>("", [=](const OUITextBoxRef& pTextBox, const Vector2& localPos) -> decltype(std::string().size())
        {
            auto pFont = OGetFont(pTextBox->textComponent.font.typeFace.c_str());
            if (!pFont) return 0;
            auto& text = pTextBox->textComponent.text;
            return pFont->caretPos(text, localPos.x - 4);
        });

        oWindow->onWrite = [](char c)
        {
            oUIContext->write(c);
        };
        oWindow->onKey = [](uintptr_t key)
        {
            oUIContext->keyDown(key);
        };

        oUIContext->addStyle<onut::UIPanel>("blur", [](const OUIPanelRef& pPanel, const Rect& rect)
        {
            oSpriteBatch->end();
            if (oRenderer->renderStates.renderTarget.get())
            {
                oRenderer->renderStates.renderTarget.get()->blur();
            }
            oSpriteBatch->begin();
            oSpriteBatch->drawRect(nullptr, (rect), pPanel->color);
        });
    }

    void createServices()
    {
        // Random
        randomizeSeed();

        // Thread pool
        if (!oThreadPool) oThreadPool = OThreadPool::create();

        // Dispatcher
        if (!oDispatcher) oDispatcher = ODispatcher::create();

        // Timing class
        if (!oTiming) oTiming = OTiming::create();

        // Updater
        if (!oUpdater) oUpdater = OUpdater::create();

        // Window
        if (!oWindow) oWindow = OWindow::create();

        // Renderer
        if (!oRenderer)
        {
            oRenderer = ORenderer::create(oWindow);
            oRenderer->init(oWindow);
        }

        // SpriteBatch
        if (!oSpriteBatch) oSpriteBatch = SpriteBatch::create();
        if (!oPrimitiveBatch) oPrimitiveBatch = PrimitiveBatch::create();

        // Content
        if (!oContentManager) oContentManager = ContentManager::create();

        // Cloud
        //oCloud = Cloud::create(oSettings->getAppId(), oSettings->getAppSecret());

        // Mouse/Keyboard
        if (!oInput) oInput = OInput::create(oWindow);

        // Audio
        if (!oAudioEngine) oAudioEngine = AudioEngine::create();

        // Particles
        if (!oParticleSystemManager) oParticleSystemManager = ParticleSystemManager::create();

        // Http
        if (!oHttp) oHttp = Http::create();

        // Multiplayer
        if (!oMultiplayer) oMultiplayer = Multiplayer::create();

        // UI Context
        createUI();

        // Component factory
        if (!oComponentFactory)
        {
            oComponentFactory = ComponentFactory::create();
            oComponentFactory->registerDefaultComponents();
        }

        // Entity Manager
        if (!oSceneManager) oSceneManager = SceneManager::create();

        // Undo/Redo for editors
        if (!oActionManager) oActionManager = ActionManager::create();

        g_pMainRenderTarget = OTexture::createScreenRenderTarget();

        // Initialize Javascript
        onut::js::init();
    }

    void cleanup()
    {
        onut::js::shutdown();

        g_pMainRenderTarget = nullptr;
        oActionManager = nullptr;
        oSceneManager = nullptr;
        oComponentFactory = nullptr;
        oDispatcher = nullptr;
        oUpdater = nullptr;
        oUI = nullptr;
        oUIContext = nullptr;
        oMultiplayer = nullptr;
        oHttp = nullptr;
        oParticleSystemManager = nullptr;
        oAudioEngine = nullptr;
        oInput = nullptr;
        //oCloud = nullptr;
        oContentManager = nullptr;
        oPrimitiveBatch = nullptr;
        oSpriteBatch = nullptr;
        oRenderer = nullptr;
        oWindow = nullptr;
        oSettings = nullptr;
        oThreadPool = nullptr;
        oTiming = nullptr;
    }

    // Start the engine
    void run(std::function<void()> initCallback,
             std::function<void()> updateCallback,
             std::function<void()> renderCallback,
             std::function<void()> postRenderCallback)
    {
        // Make sure we run just once
        static bool alreadyRan = false;
        assert(!alreadyRan);
        alreadyRan = true;

        createServices();

        // Call the user defined init
        if (initCallback)
        {
            initCallback();
        }

        // Main loop
        g_bIsRunning = true;
        while (true)
        {
            if (!oWindow->pollEvents()) break;
            if (!g_bIsRunning) break;

            // Sync to main callbacks
            oDispatcher->processQueue();

            // Update
            oAudioEngine->update();
            auto framesToUpdate = oTiming->update(oSettings->getIsFixedStep());
            while (framesToUpdate--)
            {
                oInput->update();
#if defined(__rpi__)
                if (OInputPressed(OKeyLeftAlt) && OInputPressed(OKeyF4))
                {
                    g_bIsRunning = false;
                    break;
                }
#endif
#if defined(WIN32)
                POINT cur;
                GetCursorPos(&cur);
                ScreenToClient(oWindow->getHandle(), &cur);
                oInput->mousePos.x = cur.x;
                oInput->mousePos.y = cur.y;
                oInput->mousePosf.x = static_cast<float>(cur.x);
                oInput->mousePosf.y = static_cast<float>(cur.y);
#endif // WIN32
                oUpdater->update();
                auto mousePosf = OGetMousePos();
                if (oUIContext->useNavigation)
                {
                    oUI->update(oUIContext, Vector2(mousePosf.x, mousePosf.y),
                                OGamePadPressed(OGamePadA) || OInputJustPressed(OKeyEnter) || OInputJustPressed(OXArcadeLButton1),
                                false, false,
                                OGamePadJustPressed(OGamePadDPadLeft) || OGamePadJustPressed(OGamePadLeftThumbLeft) || OInputJustPressed(OKeyLeft) || OInputJustPressed(OXArcadeLJoyLeft),
                                OGamePadJustPressed(OGamePadDPadRight) || OGamePadJustPressed(OGamePadLeftThumbRight) || OInputJustPressed(OKeyRight) || OInputJustPressed(OXArcadeLJoyRight),
                                OGamePadJustPressed(OGamePadDPadUp) || OGamePadJustPressed(OGamePadLeftThumbUp) || OInputJustPressed(OKeyUp) || OInputJustPressed(OXArcadeLJoyUp),
                                OGamePadJustPressed(OGamePadDPadDown) || OGamePadJustPressed(OGamePadLeftThumbDown) || OInputJustPressed(OKeyDown) || OInputJustPressed(OXArcadeLJoyDown),
                                0.f);
                }
                else
                {
                    oUI->update(oUIContext, Vector2(mousePosf.x, mousePosf.y),
                                OInputPressed(OMouse1), OInputPressed(OMouse2), OInputPressed(OMouse3),
                                false, false, false, false,
                                OInputPressed(OKeyLeftControl), oInput->getStateValue(OMouseZ));
                }
                oParticleSystemManager->update();
                oSceneManager->update();
                onut::js::update(oTiming->getDeltaTime());
                if (updateCallback)
                {
                    updateCallback();
                }
            }

            // Render
            oTiming->render();
            if (oSettings->getShowOnScreenLog() && oSettings->getIsRetroMode())
            {
                oRenderer->clear(Color::Black);
            }
            oRenderer->renderStates.renderTarget = g_pMainRenderTarget;
            oRenderer->beginFrame();
            onut::js::render();
            if (renderCallback)
            {
                renderCallback();
            }
            oSceneManager->render();
            oParticleSystemManager->render();
            oSpriteBatch->begin();
            oUI->render(oUIContext);
            oSpriteBatch->end();

            // Draw final render target
            oRenderer->renderStates.renderTarget = nullptr;
            const auto& res = oRenderer->getResolution();
            oRenderer->renderStates.viewport = iRect{0, 0, res.x, res.y};
            oRenderer->renderStates.scissorEnabled = false;
            oRenderer->renderStates.scissor = oRenderer->renderStates.viewport.get();
            oSpriteBatch->begin();
            oSpriteBatch->changeBlendMode(OBlendOpaque);
            oSpriteBatch->changeFiltering(OFilterNearest);
            oSpriteBatch->drawRect(g_pMainRenderTarget, ORectSmartFit(Rect{0, 0, OScreenf}, g_pMainRenderTarget->getSizef()));

            // Show the log
            if (oSettings->getShowOnScreenLog())
            {
                onut::drawLog();
            }
            oSpriteBatch->end();
            oSpriteBatch->changeBlendMode(OBlendAlpha);
            oSpriteBatch->changeFiltering(OFilterLinear);

            if (postRenderCallback)
            {
                postRenderCallback();
            }

            if (oSettings->getShowFPS())
            {
                auto pFont = OGetFont("font.fnt");
                if (pFont)
                {
                    pFont->draw("FPS: " + std::to_string(oTiming->getFPS()), { 0, 0 });
                }
            }

            oRenderer->endFrame();
        }

        cleanup();
    }

    void quit()
    {
#if defined(WIN32)
        PostQuitMessage(0);
#else
		g_bIsRunning = false;
#endif
    }
}

// Main
void initSettings();
void init();
void update();
void render();
void postRender();

std::vector<std::string> OArguments;

#if defined(WIN32)
#include <Windows.h>

int CALLBACK WinMain(HINSTANCE appInstance, HINSTANCE prevInstance, LPSTR cmdLine, int cmdCount)
{
    int argc;
    auto cmdLineW = onut::utf8ToUtf16(cmdLine);
    if (!cmdLineW.empty())
    {
        auto argvW = CommandLineToArgvW(cmdLineW.c_str(), &argc);
        for (int i = 0; i < argc; ++i)
        {
            OArguments.push_back(onut::utf16ToUtf8(argvW[i]));
        }
    }
    initSettings();
    onut::initLog();
    onut::run(init, update, render, postRender);
    return 0;
}
#else
int main(int argc, char** argv)
{
    for (int i = 0; i < argc; ++i)
    {
        OArguments.push_back(argv[i]);
    }

    initSettings();
    onut::run(init, update, render, postRender);
    return 0;
}
#endif
<|endoftext|>