<commit_before>/*
 * Copyright (C) 2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \file urbi/uvar.hh

#ifndef URBI_CUSTOMUVAR_HH
# define URBI_CUSTOMUVAR_HH

#include <urbi/uobject.hh>
#include <urbi/uvar.hh>

namespace urbi
{
  /** UVar wrapper with a custom data field.
   * Since the UVar reference passed as argument to the notifyChange callback
   * is the same as the one given to UNotifyChange, one can inherit from UVar
   * to transmit custom data to the callbacks. This class is designed to ease
   * this process.
   *
   * Example usage:
   *
   * \code
   * CustomUVar<int> v = new UVar(*this, "motor" + string_cast(mID));
   * v->data() = mID;
   * UNotifyChange(*v, &Motor::onChange);
   *
   * void Motor::onChange(UVar& var)
   * {
   *    int id = CustomUVar<int>::data(var);
   *    writeMotor(id, (double)var);
   * }
   *
   * \endcode
   */
  template<typename T> class CustomUVar: public UVar
  {
  public:
    CustomUVar();
    CustomUVar(const std::string&, impl::UContextImpl* = 0);
    CustomUVar(const std::string&, const std::string&, impl::UContextImpl* = 0);
    CustomUVar(UObject&, const std::string&, impl::UContextImpl* = 0);
    T& data();

    template<typename D> void operator=(D v);
    /** @return a reference to the data structure from an UVar.
     * The UVar must be a CustomUVar<T>, or the behavior will be undefined.
     */
    static T& data(UVar&);
    static void updateCache(UVar& v);
  private:
    T data_;
  };
}
/// Declare a CustomVar whose custom store is its value.
#define UBindCacheVar(cls, v, t) \
  UBindVar(cls, v); \
  ::urbi::createUCallback(*this, &v, "var", &CustomUVar<t>::updateCache, \
                          v.get_name(), ctx_);

# include <urbi/customuvar.hxx>

#endif
<commit_msg>CustomUVar: Add missing namespace in macro.<commit_after>/*
 * Copyright (C) 2010-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \file urbi/uvar.hh

#ifndef URBI_CUSTOMUVAR_HH
# define URBI_CUSTOMUVAR_HH

#include <urbi/uobject.hh>
#include <urbi/uvar.hh>

namespace urbi
{
  /** UVar wrapper with a custom data field.
   * Since the UVar reference passed as argument to the notifyChange callback
   * is the same as the one given to UNotifyChange, one can inherit from UVar
   * to transmit custom data to the callbacks. This class is designed to ease
   * this process.
   *
   * Example usage:
   *
   * \code
   * CustomUVar<int> v = new UVar(*this, "motor" + string_cast(mID));
   * v->data() = mID;
   * UNotifyChange(*v, &Motor::onChange);
   *
   * void Motor::onChange(UVar& var)
   * {
   *    int id = CustomUVar<int>::data(var);
   *    writeMotor(id, (double)var);
   * }
   *
   * \endcode
   */
  template<typename T> class CustomUVar: public UVar
  {
  public:
    CustomUVar();
    CustomUVar(const std::string&, impl::UContextImpl* = 0);
    CustomUVar(const std::string&, const std::string&, impl::UContextImpl* = 0);
    CustomUVar(UObject&, const std::string&, impl::UContextImpl* = 0);
    T& data();

    template<typename D> void operator=(D v);
    /** @return a reference to the data structure from an UVar.
     * The UVar must be a CustomUVar<T>, or the behavior will be undefined.
     */
    static T& data(UVar&);
    static void updateCache(UVar& v);
  private:
    T data_;
  };
}
/// Declare a CustomVar whose custom store is its value.
#define UBindCacheVar(cls, v, t) \
  UBindVar(cls, v); \
  ::urbi::createUCallback(*this, &v, "var", &urbi::CustomUVar<t>::updateCache, \
                          v.get_name(), ctx_);

# include <urbi/customuvar.hxx>

#endif
<|endoftext|>


<commit_before> /**
 * \file      main.cc
 * \brief     Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted
 * \author    Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman,Leo Jenneskens
 * \copyright Copyright (c) 2017, The R2D2 Team
 * \license   See LICENSE
 */

#include "mysql.hh"
#include "mfrc522.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "config-file-parser.hh"

#include <wiringPi.h>
#include <wiringPiSPI.h>

#include <iostream>

struct MFAuthentData {
    uint8_t command_code;
    uint8_t blockAddress;
    uint8_t sectorKey[5];
    uint8_t serialNumber[4];
};

int main(int argc, char **argv) {
#define USING_PIN           // Comment out this rule if not using a pincode on your application
    try {
        std::string ip;
        std::string username;
        std::string password;
        //int encryptionKey;

        ConfigFileParser factory("database-config.txt");
        factory.loadDatabaseSettings(ip, username, password);

        MySql connection;

        connection.connectTo(ip, username, password);
        connection.selectDatabase("R2D2");

        std::cout << "Made connection to the database\n";
        wiringPiSetup();
        wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz
        MFRC522 rfid;
        rfid.PCD_Init();

        //Keypad pinSetup
        const int keypadRow[] = {15, 16, 1, 4};
        const int keypadColumn[] = {8, 9, 7, 2};

        //Keypad objects
        MatrixKeypad keypad(keypadRow, keypadColumn, 4);
        char c;

        LedController led(0);

        while (true) {
            delay(1000);
            std::cout << "\n\nWaiting for rfid tag: \n";

            rfid.PICC_IsNewCardPresent();

            rfid.PICC_ReadCardSerial();

            // Hier moet het database gedeelte komen om te checken of je ID al in de database staat

#ifdef USING_PIN
            MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
            std::cout << "Input PIN and finish with #\n";
            std::string value = keypad.getString();
            long result;
            if(!rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid))
                continue;
	       	byte  writearray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
		    int index = 0;
            for(auto c :value){
		      if (c >47 && c < 58 ){
		          int number = c - 48;
		          writearray[index++] = (byte)number;
		        }
	        }
            rfid.MIFARE_Write((byte)0x05, writearray, (byte)16);
            for (int i = 0; i < 16; i++){
                std::cout <<(int)writearray[i] << '\n';
            }
            byte buffersize = (byte)18;
            byte readarray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
            rfid.MIFARE_Read((byte)0x05,readarray, &buffersize);
            std::cout << "Readarray contains: \n";
            for (int i = 0; i < 18; i++){
                std::cout <<(int)readarray[i] << '\n';
            }
#endif

            rfid.PCD_StopCrypto1();

            for(byte i = 0; i < rfid.uid.size; ++i){
                if(rfid.uid.uidByte[i] < 0x10){
                    printf(" 0");
                    printf("%X",rfid.uid.uidByte[i]);
                }
                else{
                    printf(" ");
                    printf("%X", rfid.uid.uidByte[i]);
                }
            }

            connection.executeQuery("SELECT * FROM RFID");

            std::cout << "Database information: "
                      << connection.getPreviousResponseColumn("CARD_ID")
                      << '\n';

            led.blinkLed(1000);
        }
    } catch (const std::string &error) {
        std::cerr << error << '\n';
        exit(EXIT_FAILURE);
    } catch (...) {
        std::cerr << "Something went wrong\n";
        exit(EXIT_FAILURE);
    }
    return 0;
}

<commit_msg>[RFID-03]: changed small indentation issue<commit_after> /**
 * \file      main.cc
 * \brief     Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted
 * \author    Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman,Leo Jenneskens
 * \copyright Copyright (c) 2017, The R2D2 Team
 * \license   See LICENSE
 */

#include "mysql.hh"
#include "mfrc522.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "config-file-parser.hh"

#include <wiringPi.h>
#include <wiringPiSPI.h>

#include <iostream>

struct MFAuthentData {
    uint8_t command_code;
    uint8_t blockAddress;
    uint8_t sectorKey[5];
    uint8_t serialNumber[4];
};

int main(int argc, char **argv) {
#define USING_PIN           // Comment out this rule if not using a pincode on your application
    try {
        std::string ip;
        std::string username;
        std::string password;
        //int encryptionKey;

        ConfigFileParser factory("database-config.txt");
        factory.loadDatabaseSettings(ip, username, password);

        MySql connection;

        connection.connectTo(ip, username, password);
        connection.selectDatabase("R2D2");

        std::cout << "Made connection to the database\n";
        wiringPiSetup();
        wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz
        MFRC522 rfid;
        rfid.PCD_Init();

        //Keypad pinSetup
        const int keypadRow[] = {15, 16, 1, 4};
        const int keypadColumn[] = {8, 9, 7, 2};

        //Keypad objects
        MatrixKeypad keypad(keypadRow, keypadColumn, 4);
        char c;

        LedController led(0);

        while (true) {
            delay(1000);
            std::cout << "\n\nWaiting for rfid tag: \n";

            rfid.PICC_IsNewCardPresent();

            rfid.PICC_ReadCardSerial();

            // Hier moet het database gedeelte komen om te checken of je ID al in de database staat

#ifdef USING_PIN
            MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
            std::cout << "Input PIN and finish with #\n";
            std::string value = keypad.getString();
            long result;
            if(!rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid))
                continue;
	       	byte  writearray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
		    int index = 0;
            for(auto c :value){
                if (c >47 && c < 58 ){
                    int number = c - 48;
                    writearray[index++] = (byte)number;
		        }
	        }
            rfid.MIFARE_Write((byte)0x05, writearray, (byte)16);
            for (int i = 0; i < 16; i++){
                std::cout <<(int)writearray[i] << '\n';
            }
            byte buffersize = (byte)18;
            byte readarray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
            rfid.MIFARE_Read((byte)0x05,readarray, &buffersize);
            std::cout << "Readarray contains: \n";
            for (int i = 0; i < 18; i++){
                std::cout <<(int)readarray[i] << '\n';
            }
#endif

            rfid.PCD_StopCrypto1();

            for(byte i = 0; i < rfid.uid.size; ++i){
                if(rfid.uid.uidByte[i] < 0x10){
                    printf(" 0");
                    printf("%X",rfid.uid.uidByte[i]);
                }
                else{
                    printf(" ");
                    printf("%X", rfid.uid.uidByte[i]);
                }
            }

            connection.executeQuery("SELECT * FROM RFID");

            std::cout << "Database information: "
                      << connection.getPreviousResponseColumn("CARD_ID")
                      << '\n';

            led.blinkLed(1000);
        }
    } catch (const std::string &error) {
        std::cerr << error << '\n';
        exit(EXIT_FAILURE);
    } catch (...) {
        std::cerr << "Something went wrong\n";
        exit(EXIT_FAILURE);
    }
    return 0;
}

<|endoftext|>


<commit_before>#include "base/base.h"
#include "boost/multiprecision/cpp_int.hpp"
#include "boost/rational.hpp"

using namespace std;

using boost::rational;
using boost::rational_cast;

typedef boost::multiprecision::cpp_rational Q;

struct Vertex {
  Q x;
  Q y;
};

typedef vector<Vertex> Polygon;

std::istream& operator>>(istream& is, Vertex& v) {
  string r;
  while (isspace(is.peek())) {
    is.get();
  }
  std::getline(is, r, ',');
  v.x.assign(r);
  while (isspace(is.peek())) {
    is.get();
  }
  std::getline(is, r);
  v.y.assign(r);
  return is;
}

std::istream& operator>>(istream& is, Polygon& p) {
  int n_verts;
  is >> n_verts;
  p.resize(n_verts);
  for (int i = 0; i < n_verts; ++i) {
    is >> p[i];
  }
  return is;
}

int main() {
  int n_polys;
  cin >> n_polys;
  vector<Polygon> polys(n_polys);
  for (int i = 0; i < n_polys; ++i) {
    cin >> polys[i];
  }
  // TODO: Parse skelton

  Q min_x = 0, min_y = 0, max_x = 1, max_y = 1;
  for (int i = 0; i < n_polys; ++i) {
    for (const auto& v : polys[i]) {
      if (v.x < min_x) min_x = v.x;
      if (max_x < v.x) max_x = v.x;
      if (v.y < min_y) min_y = v.y;
      if (max_y < v.y) max_y = v.y;
    }
  }
  printf(
      R"(<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300px" height="300px" viewBox="%f %f %f %f"><rect x="0" y="0" width="1" height="1" fill="none" stroke="blue" stroke-width="0.01"/>)",
      min_x.convert_to<double>(), min_y.convert_to<double>(),
      Q(max_x - min_x).convert_to<double>(),
      Q(max_y - min_y).convert_to<double>());
  for (int i = 0; i < n_polys; ++i) {
    printf(R"(<path d=")");
    for (int j = 0; j < polys[i].size(); ++j) {
      printf("%c %.8f %.8f ", j == 0 ? 'M' : 'L',
             polys[i][j].x.convert_to<double>(),
             polys[i][j].y.convert_to<double>());
    }
    printf(R"(Z" fill="silver" stroke="gray" stroke-width="0.01" />)");
  }
  printf("</svg>");

  return 0;
}
<commit_msg>support hole polygons<commit_after>#include <complex>
#include <vector>

#include "base/base.h"
#include "boost/multiprecision/cpp_int.hpp"
#include "boost/rational.hpp"

DEFINE_BOOL(expand_viewbox, true,
            "Expand viewbox to covert the entire silhouette.");
DEFINE_BOOL(shrink_viewbox, false, "Shrink viewbox to fit silhouette.");

using boost::rational;
using boost::rational_cast;
using namespace std;

typedef boost::multiprecision::cpp_rational Q;
typedef std::complex<Q> C;

namespace std {
// Dummy functions for std::complex
bool isnan(const Q& q) { return false; }
bool isinf(const Q& q) { return false; }
Q copysign(const Q& x, const Q& y) { return x.sign() != y.sign() ? -x : x; }
}

struct Vertex {
  Q x;
  Q y;
};

typedef vector<Vertex> Polygon;

bool is_ccw(const Polygon& p) {
  vector<C> v(p.size());
  for (int i = 0; i < p.size(); ++i) {
    v[i] = C(p[i].x - p[0].x, p[i].y - p[0].y);
  }
  Q area;
  for (int i = 1; i < v.size() - 1; ++i) {
    area += (v[i] * std::conj(v[i + 1])).imag();
  }
  LOG_IF(ERROR, area == 0) << "Unexpected zero area";
  return area < 0;
}

std::istream& operator>>(istream& is, Vertex& v) {
  string r;
  while (isspace(is.peek())) {
    is.get();
  }
  std::getline(is, r, ',');
  v.x.assign(r);
  while (isspace(is.peek())) {
    is.get();
  }
  std::getline(is, r);
  v.y.assign(r);
  return is;
}

std::istream& operator>>(istream& is, Polygon& p) {
  int n_verts;
  is >> n_verts;
  p.resize(n_verts);
  for (int i = 0; i < n_verts; ++i) {
    is >> p[i];
  }
  return is;
}

int main() {
  int n_polys;
  cin >> n_polys;
  vector<Polygon> polys(n_polys);
  for (int i = 0; i < n_polys; ++i) {
    cin >> polys[i];
  }
  // TODO: Parse skelton

  // viewbox size
  Q min_x = 0, min_y = 0, max_x = 1, max_y = 1;
  if (FLAGS_shrink) {
    min_x = max_x = polys[0][0].x;
    min_y = max_y = polys[0][0].y;
  }
  if (FLAGS_expand_viewbox) {
    for (int i = 0; i < n_polys; ++i) {
      for (const auto& v : polys[i]) {
        if (v.x < min_x) min_x = v.x;
        if (max_x < v.x) max_x = v.x;
        if (v.y < min_y) min_y = v.y;
        if (max_y < v.y) max_y = v.y;
      }
    }
  }
  printf(
      R"(<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300px" height="300px" viewBox="%f %f %f %f"><rect x="0" y="0" width="1" height="1" fill="none" stroke="blue" stroke-width="0.01"/>)",
      min_x.convert_to<double>(), min_y.convert_to<double>(),
      Q(max_x - min_x).convert_to<double>(),
      Q(max_y - min_y).convert_to<double>());
  for (int i = 0; i < n_polys; ++i) {
    bool is_positive = is_ccw(polys[i]);
    printf(R"(<path d=")");
    for (int j = 0; j < polys[i].size(); ++j) {
      printf("%c %.3f %.3f ", j == 0 ? 'M' : 'L',
             polys[i][j].x.convert_to<double>(),
             polys[i][j].y.convert_to<double>());
    }
    printf(R"(Z" fill="silver" stroke="%s" stroke-width="0.01" />)",
           is_positive ? "gray" : "black");
  }
  printf("</svg>");

  return 0;
}
<|endoftext|>


<commit_before>#ifndef MJOLNIR_POTENTIAL_EXTERNAL_HARMONIC_RESTRAINT_POTENTIAL_HPP
#define MJOLNIR_POTENTIAL_EXTERNAL_HARMONIC_RESTRAINT_POTENTIAL_HPP
#include <mjolnir/core/System.hpp>
#include <utility>
#include <vector>
#include <limits>

namespace mjolnir
{

// apply a harmonic restraint (k(x-x0)^2.) per one particle.
template<typename realT>
class HarmonicRestraintPotential
{
  public:
    using real_type      = realT;
    using parameter_type = std::pair<real_type, real_type>; // {k, x0}

  public:

    HarmonicRestraintPotential(std::vector<parameter_type> params)
        : params_(std::move(params))
    {}
    ~HarmonicRestraintPotential() = default;

    real_type potential(const std::size_t i, const real_type r) const noexcept
    {
        const real_type k  = this->params_[i].first;
        const real_type r0 = this->params_[i].second;
        const real_type dr = r - r0;

        return k * dr * dr;
    }

    real_type derivative(const std::size_t i, const real_type r) const noexcept
    {
        const real_type k  = this->params_[i].first;
        const real_type r0 = this->params_[i].second;
        const real_type dr = r - r0;

        return 2 * k * dr;
    }

    // no cutoff length. it has a finite value wherever particle is.
    real_type max_cutoff_length() const noexcept
    {
        return std::numeric_limits<real_type>::infinity();
    }

    std::vector<std::size_t> participants() const
    {
        std::vector<std::size_t> retval;
        retval.reserve(this->params_.size());
        for(std::size_t i=0; i<this->params_.size(); ++i)
        {
            if(this->params_[i].second != real_type(0.0))
            {
                retval.push_back(i);
            }
        }
        return retval;
    }

    // nothing to do when system parameters change.
    template<typename T>
    void update(const System<T>&) const noexcept {return;}

    const char* name() const noexcept {return "HarmonicRestraint";}

    // access to the parameters...
    std::vector<parameter_type>&       parameters()       noexcept {return params_;}
    std::vector<parameter_type> const& parameters() const noexcept {return params_;}

  private:

    std::vector<parameter_type> params_;
};

} // mjolnir
#endif // MJOLNIR_EXTERNAL_LENNARD_JONES_WALL_POTENTIAL
<commit_msg>fix: count non-zero k as participant<commit_after>#ifndef MJOLNIR_POTENTIAL_EXTERNAL_HARMONIC_RESTRAINT_POTENTIAL_HPP
#define MJOLNIR_POTENTIAL_EXTERNAL_HARMONIC_RESTRAINT_POTENTIAL_HPP
#include <mjolnir/core/System.hpp>
#include <utility>
#include <vector>
#include <limits>

namespace mjolnir
{

// apply a harmonic restraint (k(x-x0)^2.) per one particle.
template<typename realT>
class HarmonicRestraintPotential
{
  public:
    using real_type      = realT;
    using parameter_type = std::pair<real_type, real_type>; // {k, x0}

  public:

    HarmonicRestraintPotential(std::vector<parameter_type> params)
        : params_(std::move(params))
    {}
    ~HarmonicRestraintPotential() = default;

    real_type potential(const std::size_t i, const real_type r) const noexcept
    {
        const real_type k  = this->params_[i].first;
        const real_type r0 = this->params_[i].second;
        const real_type dr = r - r0;

        return k * dr * dr;
    }

    real_type derivative(const std::size_t i, const real_type r) const noexcept
    {
        const real_type k  = this->params_[i].first;
        const real_type r0 = this->params_[i].second;
        const real_type dr = r - r0;

        return 2 * k * dr;
    }

    // no cutoff length. it has a finite value wherever particle is.
    real_type max_cutoff_length() const noexcept
    {
        return std::numeric_limits<real_type>::infinity();
    }

    std::vector<std::size_t> participants() const
    {
        std::vector<std::size_t> retval;
        retval.reserve(this->params_.size());
        for(std::size_t i=0; i<this->params_.size(); ++i)
        {
            if(this->params_[i].first != real_type(0.0))
            {
                retval.push_back(i);
            }
        }
        return retval;
    }

    // nothing to do when system parameters change.
    template<typename T>
    void update(const System<T>&) const noexcept {return;}

    const char* name() const noexcept {return "HarmonicRestraint";}

    // access to the parameters...
    std::vector<parameter_type>&       parameters()       noexcept {return params_;}
    std::vector<parameter_type> const& parameters() const noexcept {return params_;}

  private:

    std::vector<parameter_type> params_;
};

} // mjolnir
#endif // MJOLNIR_EXTERNAL_LENNARD_JONES_WALL_POTENTIAL
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/capturer_linux.h"

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/Xdamage.h>

#include <set>

#include "remoting/base/types.h"

namespace remoting {

static int IndexOfLowestBit(unsigned int mask) {
  int i = 0;

  // Extra-special do-while premature optimization, just to make dmaclach@
  // happy.
  do {
    if (mask & 1) {
      return i;
    }
    mask >>= 1;
    ++i;
  } while (mask);

  NOTREACHED() << "mask should never be 0.";
  return 0;
}

static bool IsRgb32(XImage* image) {
  return (IndexOfLowestBit(image->red_mask) == 16) &&
         (IndexOfLowestBit(image->green_mask) == 8) &&
         (IndexOfLowestBit(image->blue_mask) == 0);
}

static uint32_t* GetRowStart(uint8* buffer_start, int stride, int cur_row) {
  return reinterpret_cast<uint32_t*>(buffer_start + (cur_row * stride));
}

// Private Implementation pattern to avoid leaking the X11 types into the header
// file.
class CapturerLinuxPimpl {
 public:
  explicit CapturerLinuxPimpl(CapturerLinux* capturer);
  ~CapturerLinuxPimpl();

  bool Init();  // TODO(ajwong): Do we really want this to be synchronous?
  void CalculateInvalidRects();
  void CaptureRects(const InvalidRects& rects,
                    Capturer::CaptureCompletedCallback* callback);

 private:
  void DeinitXlib();
  // We expose two forms of blitting to handle variations in the pixel format.
  // In FastBlit, the operation is effectively a memcpy.
  void FastBlit(XImage* image, int dest_x, int dest_y,
                CaptureData* capture_data);
  void SlowBlit(XImage* image, int dest_x, int dest_y,
                CaptureData* capture_data);

  static const int kBytesPerPixel = 4;

  // Reference to containing class so we can access friend functions.
  // Not owned.
  CapturerLinux* capturer_;

  // X11 graphics context.
  Display* display_;
  GC gc_;
  Window root_window_;

  // XDamage information.
  Damage damage_handle_;
  int damage_event_base_;
  int damage_error_base_;

  // Capture state.
  uint8* buffers_[CapturerLinux::kNumBuffers];
  int stride_;
  bool capture_fullscreen_;
};

CapturerLinux::CapturerLinux(MessageLoop* message_loop)
    : Capturer(message_loop),
      pimpl_(new CapturerLinuxPimpl(this)) {
  // TODO(ajwong): This should be moved into an Init() method on Capturer
  // itself.  Then we can remove the CHECK.
  CHECK(pimpl_->Init());
}

CapturerLinux::~CapturerLinux() {
}

void CapturerLinux::ScreenConfigurationChanged() {
  // TODO(ajwong): Support resolution changes.
  NOTIMPLEMENTED();
}

void CapturerLinux::CalculateInvalidRects() {
  pimpl_->CalculateInvalidRects();
}

void CapturerLinux::CaptureRects(const InvalidRects& rects,
                                 CaptureCompletedCallback* callback) {
  pimpl_->CaptureRects(rects, callback);
}

CapturerLinuxPimpl::CapturerLinuxPimpl(CapturerLinux* capturer)
    : capturer_(capturer),
      display_(NULL),
      gc_(NULL),
      root_window_(BadValue),
      damage_handle_(BadValue),
      damage_event_base_(-1),
      damage_error_base_(-1),
      stride_(0),
      capture_fullscreen_(true) {
  for (int i = 0; i < CapturerLinux::kNumBuffers; i++) {
    buffers_[i] = NULL;
  }
}

CapturerLinuxPimpl::~CapturerLinuxPimpl() {
  DeinitXlib();

  for (int i = 0; i < CapturerLinux::kNumBuffers; i++) {
    delete [] buffers_[i];
    buffers_[i] = NULL;
  }
}

bool CapturerLinuxPimpl::Init() {
  // TODO(ajwong): We should specify the display string we are attaching to
  // in the constructor.
  display_ = XOpenDisplay(NULL);
  if (!display_) {
    LOG(ERROR) << "Unable to open display";
    return false;
  }

  root_window_ = RootWindow(display_, DefaultScreen(display_));
  if (root_window_ == BadValue) {
    LOG(ERROR) << "Unable to get the root window";
    DeinitXlib();
    return false;
  }

  gc_ = XCreateGC(display_, root_window_, 0, NULL);
  if (gc_ == NULL) {
    LOG(ERROR) << "Unable to get graphics context";
    DeinitXlib();
    return false;
  }

  // Setup XDamage to report changes in the damage window.  Mark the whole
  // window as invalid.
  if (!XDamageQueryExtension(display_, &damage_event_base_,
                             &damage_error_base_)) {
    LOG(ERROR) << "Server does not support XDamage.";
    DeinitXlib();
    return false;
  }
  damage_handle_ = XDamageCreate(display_, root_window_,
                                 XDamageReportDeltaRectangles);
  if (damage_handle_ == BadValue) {
    LOG(ERROR) << "Unable to create damage handle.";
    DeinitXlib();
    return false;
  }

  // TODO(ajwong): We should be able to replace this with a XDamageAdd().
  capture_fullscreen_ = true;

  // Set up the dimensions of the catpure framebuffer.
  XWindowAttributes root_attr;
  XGetWindowAttributes(display_, root_window_, &root_attr);
  capturer_->width_ = root_attr.width;
  capturer_->height_ = root_attr.height;
  stride_ = capturer_->width() * kBytesPerPixel;
  VLOG(1) << "Initialized with Geometry: " << capturer_->width()
          << "x" << capturer_->height();

  // Allocate the screen buffers.
  for (int i = 0; i < CapturerLinux::kNumBuffers; i++) {
    buffers_[i] =
        new uint8[capturer_->width() * capturer_->height() * kBytesPerPixel];
  }

  return true;
}

void CapturerLinuxPimpl::CalculateInvalidRects() {
  // TODO(ajwong): The capture_fullscreen_ logic here is very ugly. Refactor.

  // Find the number of events that are outstanding "now."  We don't just loop
  // on XPending because we want to guarantee this terminates.
  int events_to_process = XPending(display_);
  XEvent e;
  InvalidRects invalid_rects;
  for (int i = 0; i < events_to_process; i++) {
    XNextEvent(display_, &e);
    if (e.type == damage_event_base_ + XDamageNotify) {
      // If we're doing a full screen capture, we should just drain the events.
      if (!capture_fullscreen_) {
        XDamageNotifyEvent *event = reinterpret_cast<XDamageNotifyEvent*>(&e);
        gfx::Rect damage_rect(event->area.x, event->area.y, event->area.width,
                              event->area.height);
        invalid_rects.insert(damage_rect);
        VLOG(3) << "Damage receved for rect at ("
                << damage_rect.x() << "," << damage_rect.y() << ") size ("
                << damage_rect.width() << "," << damage_rect.height() << ")";
      }
    } else {
      LOG(WARNING) << "Got unknown event type: " << e.type;
    }
  }

  if (capture_fullscreen_) {
    capturer_->InvalidateFullScreen();
    capture_fullscreen_ = false;
  } else {
    capturer_->InvalidateRects(invalid_rects);
  }
}

void CapturerLinuxPimpl::CaptureRects(
    const InvalidRects& rects,
    Capturer::CaptureCompletedCallback* callback) {
  uint8* buffer = buffers_[capturer_->current_buffer_];
  DataPlanes planes;
  planes.data[0] = buffer;
  planes.strides[0] = stride_;

  scoped_refptr<CaptureData> capture_data(
      new CaptureData(planes, capturer_->width(), capturer_->height(),
                      media::VideoFrame::RGB32));

  for (InvalidRects::const_iterator it = rects.begin();
       it != rects.end();
       ++it) {
    XImage* image = XGetImage(display_, root_window_, it->x(), it->y(),
                              it->width(), it->height(), AllPlanes, ZPixmap);

    // Check if we can fastpath the blit.
    if ((image->depth == 24 || image->depth == 32) &&
        image->bits_per_pixel == 32 &&
        IsRgb32(image)) {
      VLOG(3) << "Fast blitting";
      FastBlit(image, it->x(), it->y(), capture_data);
    } else {
      VLOG(3) << "Slow blitting";
      SlowBlit(image, it->x(), it->y(), capture_data);
    }

    XDestroyImage(image);
  }

  // TODO(ajwong): We should only repair the rects that were copied!
  XDamageSubtract(display_, damage_handle_, None, None);

  capture_data->mutable_dirty_rects() = rects;
  // TODO(ajwong): These completion signals back to the upper class are very
  // strange.  Fix it.
  capturer_->FinishCapture(capture_data, callback);
}

void CapturerLinuxPimpl::DeinitXlib() {
  if (gc_) {
    XFreeGC(display_, gc_);
    gc_ = NULL;
  }

  if (display_) {
    XCloseDisplay(display_);
    display_ = NULL;
  }
}

void CapturerLinuxPimpl::FastBlit(XImage* image, int dest_x, int dest_y,
                                  CaptureData* capture_data) {
  uint8* src_pos = reinterpret_cast<uint8*>(image->data);

  DataPlanes planes = capture_data->data_planes();
  uint8* dst_buffer = planes.data[0];

  const int dst_stride = planes.strides[0];
  const int src_stride = image->bytes_per_line;

  // TODO(ajwong): I think this can never happen anyways due to the way we size
  // the buffer. Check to be certain and possibly remove check.
  CHECK((dst_stride - dest_x) >= src_stride);

  // Flip the coordinate system to match the client.
  for (int y = image->height - 1; y >= 0; y--) {
    uint32_t* dst_pos = GetRowStart(dst_buffer, dst_stride, y + dest_y);
    dst_pos += dest_x;

    memcpy(dst_pos, src_pos, src_stride);

    src_pos += src_stride;
  }
}

void CapturerLinuxPimpl::SlowBlit(XImage* image, int dest_x, int dest_y,
                                  CaptureData* capture_data) {
  DataPlanes planes = capture_data->data_planes();
  uint8* dst_buffer = planes.data[0];
  const int dst_stride = planes.strides[0];

  unsigned int red_shift = IndexOfLowestBit(image->red_mask);
  unsigned int blue_shift = IndexOfLowestBit(image->blue_mask);
  unsigned int green_shift = IndexOfLowestBit(image->green_mask);

  unsigned int max_red = image->red_mask >> red_shift;
  unsigned int max_blue = image->blue_mask >> blue_shift;
  unsigned int max_green = image->green_mask >> green_shift;

  for (int y = 0; y < image->height; y++) {
    // Flip the coordinate system to match the client.
    int dst_row = image->height - y - 1;
    uint32_t* dst_pos = GetRowStart(dst_buffer, dst_stride, dst_row + dest_y);
    dst_pos += dest_x;
    for (int x = 0; x < image->width; x++) {
      unsigned long pixel = XGetPixel(image, x, y);
      uint32_t r = (((pixel & image->red_mask) >> red_shift) * max_red) / 255;
      uint32_t g =
          (((pixel & image->green_mask) >> green_shift) * max_blue) / 255;
      uint32_t b =
          (((pixel & image->blue_mask) >> blue_shift) * max_green) / 255;

      // Write as 32-bit RGB.
      *dst_pos = r << 16 | g << 8 | b;
      dst_pos++;
    }
  }
}

// static
Capturer* Capturer::Create(MessageLoop* message_loop) {
  return new CapturerLinux(message_loop);
}

}  // namespace remoting
<commit_msg>Fix linux capturer for chromoting<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/capturer_linux.h"

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/Xdamage.h>

#include <set>

#include "remoting/base/types.h"

namespace remoting {

static int IndexOfLowestBit(unsigned int mask) {
  int i = 0;

  // Extra-special do-while premature optimization, just to make dmaclach@
  // happy.
  do {
    if (mask & 1) {
      return i;
    }
    mask >>= 1;
    ++i;
  } while (mask);

  NOTREACHED() << "mask should never be 0.";
  return 0;
}

static bool IsRgb32(XImage* image) {
  return (IndexOfLowestBit(image->red_mask) == 16) &&
         (IndexOfLowestBit(image->green_mask) == 8) &&
         (IndexOfLowestBit(image->blue_mask) == 0);
}

static uint32_t* GetRowStart(uint8* buffer_start, int stride, int cur_row) {
  return reinterpret_cast<uint32_t*>(buffer_start + (cur_row * stride));
}

// Private Implementation pattern to avoid leaking the X11 types into the header
// file.
class CapturerLinuxPimpl {
 public:
  explicit CapturerLinuxPimpl(CapturerLinux* capturer);
  ~CapturerLinuxPimpl();

  bool Init();  // TODO(ajwong): Do we really want this to be synchronous?
  void CalculateInvalidRects();
  void CaptureRects(const InvalidRects& rects,
                    Capturer::CaptureCompletedCallback* callback);

 private:
  void DeinitXlib();
  // We expose two forms of blitting to handle variations in the pixel format.
  // In FastBlit, the operation is effectively a memcpy.
  void FastBlit(XImage* image, int dest_x, int dest_y,
                CaptureData* capture_data);
  void SlowBlit(XImage* image, int dest_x, int dest_y,
                CaptureData* capture_data);

  static const int kBytesPerPixel = 4;

  // Reference to containing class so we can access friend functions.
  // Not owned.
  CapturerLinux* capturer_;

  // X11 graphics context.
  Display* display_;
  GC gc_;
  Window root_window_;

  // XDamage information.
  Damage damage_handle_;
  int damage_event_base_;
  int damage_error_base_;

  // Capture state.
  uint8* buffers_[CapturerLinux::kNumBuffers];
  int stride_;
  bool capture_fullscreen_;

  // Invalid rects in the last capture. This is used to synchronize current with
  // the previous buffer used.
  InvalidRects last_invalid_rects_;

  // Last capture buffer used.
  uint8* last_buffer_;
};

CapturerLinux::CapturerLinux(MessageLoop* message_loop)
    : Capturer(message_loop),
      pimpl_(new CapturerLinuxPimpl(this)) {
  // TODO(ajwong): This should be moved into an Init() method on Capturer
  // itself.  Then we can remove the CHECK.
  CHECK(pimpl_->Init());
}

CapturerLinux::~CapturerLinux() {
}

void CapturerLinux::ScreenConfigurationChanged() {
  // TODO(ajwong): Support resolution changes.
  NOTIMPLEMENTED();
}

void CapturerLinux::CalculateInvalidRects() {
  pimpl_->CalculateInvalidRects();
}

void CapturerLinux::CaptureRects(const InvalidRects& rects,
                                 CaptureCompletedCallback* callback) {
  pimpl_->CaptureRects(rects, callback);
}

CapturerLinuxPimpl::CapturerLinuxPimpl(CapturerLinux* capturer)
    : capturer_(capturer),
      display_(NULL),
      gc_(NULL),
      root_window_(BadValue),
      damage_handle_(BadValue),
      damage_event_base_(-1),
      damage_error_base_(-1),
      stride_(0),
      capture_fullscreen_(true),
      last_buffer_(NULL) {
  for (int i = 0; i < CapturerLinux::kNumBuffers; i++) {
    buffers_[i] = NULL;
  }
}

CapturerLinuxPimpl::~CapturerLinuxPimpl() {
  DeinitXlib();

  for (int i = 0; i < CapturerLinux::kNumBuffers; i++) {
    delete [] buffers_[i];
    buffers_[i] = NULL;
  }
}

bool CapturerLinuxPimpl::Init() {
  // TODO(ajwong): We should specify the display string we are attaching to
  // in the constructor.
  display_ = XOpenDisplay(NULL);
  if (!display_) {
    LOG(ERROR) << "Unable to open display";
    return false;
  }

  root_window_ = RootWindow(display_, DefaultScreen(display_));
  if (root_window_ == BadValue) {
    LOG(ERROR) << "Unable to get the root window";
    DeinitXlib();
    return false;
  }

  gc_ = XCreateGC(display_, root_window_, 0, NULL);
  if (gc_ == NULL) {
    LOG(ERROR) << "Unable to get graphics context";
    DeinitXlib();
    return false;
  }

  // Setup XDamage to report changes in the damage window.  Mark the whole
  // window as invalid.
  if (!XDamageQueryExtension(display_, &damage_event_base_,
                             &damage_error_base_)) {
    LOG(ERROR) << "Server does not support XDamage.";
    DeinitXlib();
    return false;
  }
  damage_handle_ = XDamageCreate(display_, root_window_,
                                 XDamageReportDeltaRectangles);
  if (damage_handle_ == BadValue) {
    LOG(ERROR) << "Unable to create damage handle.";
    DeinitXlib();
    return false;
  }

  // TODO(ajwong): We should be able to replace this with a XDamageAdd().
  capture_fullscreen_ = true;

  // Set up the dimensions of the catpure framebuffer.
  XWindowAttributes root_attr;
  XGetWindowAttributes(display_, root_window_, &root_attr);
  capturer_->width_ = root_attr.width;
  capturer_->height_ = root_attr.height;
  stride_ = capturer_->width() * kBytesPerPixel;
  VLOG(1) << "Initialized with Geometry: " << capturer_->width()
          << "x" << capturer_->height();

  // Allocate the screen buffers.
  for (int i = 0; i < CapturerLinux::kNumBuffers; i++) {
    buffers_[i] =
        new uint8[capturer_->width() * capturer_->height() * kBytesPerPixel];
  }

  return true;
}

void CapturerLinuxPimpl::CalculateInvalidRects() {
  // TODO(ajwong): The capture_fullscreen_ logic here is very ugly. Refactor.

  // Find the number of events that are outstanding "now."  We don't just loop
  // on XPending because we want to guarantee this terminates.
  int events_to_process = XPending(display_);
  XEvent e;
  InvalidRects invalid_rects;
  for (int i = 0; i < events_to_process; i++) {
    XNextEvent(display_, &e);
    if (e.type == damage_event_base_ + XDamageNotify) {
      // If we're doing a full screen capture, we should just drain the events.
      if (!capture_fullscreen_) {
        XDamageNotifyEvent *event = reinterpret_cast<XDamageNotifyEvent*>(&e);
        gfx::Rect damage_rect(event->area.x, event->area.y, event->area.width,
                              event->area.height);
        invalid_rects.insert(damage_rect);
        VLOG(3) << "Damage receved for rect at ("
                << damage_rect.x() << "," << damage_rect.y() << ") size ("
                << damage_rect.width() << "," << damage_rect.height() << ")";
      }
    } else {
      LOG(WARNING) << "Got unknown event type: " << e.type;
    }
  }

  if (capture_fullscreen_) {
    capturer_->InvalidateFullScreen();
    capture_fullscreen_ = false;
  } else {
    capturer_->InvalidateRects(invalid_rects);
  }
}

void CapturerLinuxPimpl::CaptureRects(
    const InvalidRects& rects,
    Capturer::CaptureCompletedCallback* callback) {
  uint8* buffer = buffers_[capturer_->current_buffer_];
  DataPlanes planes;
  planes.data[0] = buffer;
  planes.strides[0] = stride_;

  scoped_refptr<CaptureData> capture_data(
      new CaptureData(planes, capturer_->width(), capturer_->height(),
                      media::VideoFrame::RGB32));

  // Synchronize the current buffer with the last one since we do not capture
  // the entire desktop. Note that encoder may be reading from the previous
  // buffer at this time so thread access complaints are false positives.

  // TODO(hclam): We can reduce the amount of copying here by subtracting
  // |rects| from |last_invalid_rects_|.
  for (InvalidRects::const_iterator it = last_invalid_rects_.begin();
       last_buffer_ && it != last_invalid_rects_.end();
       ++it) {
    int offset = it->y() * stride_ + it->x() + kBytesPerPixel;
    for (int i = 0; i < it->height(); ++i) {
      memcpy(buffer + offset, last_buffer_ + offset,
             it->width() * kBytesPerPixel);
      offset += capturer_->width() * kBytesPerPixel;
    }
  }

  for (InvalidRects::const_iterator it = rects.begin();
       it != rects.end();
       ++it) {
    XImage* image = XGetImage(display_, root_window_, it->x(), it->y(),
                              it->width(), it->height(), AllPlanes, ZPixmap);

    // Check if we can fastpath the blit.
    if ((image->depth == 24 || image->depth == 32) &&
        image->bits_per_pixel == 32 &&
        IsRgb32(image)) {
      VLOG(3) << "Fast blitting";
      FastBlit(image, it->x(), it->y(), capture_data);
    } else {
      VLOG(3) << "Slow blitting";
      SlowBlit(image, it->x(), it->y(), capture_data);
    }

    XDestroyImage(image);
  }

  // TODO(ajwong): We should only repair the rects that were copied!
  XDamageSubtract(display_, damage_handle_, None, None);

  // Flip the rectangles based on y axis.
  InvalidRects inverted_rects;
  for (InvalidRects::const_iterator it = rects.begin();
       it != rects.end();
       ++it) {
    inverted_rects.insert(gfx::Rect(it->x(), capturer_->height() - it->bottom(),
                                    it->width(), it->height()));
  }

  capture_data->mutable_dirty_rects() = inverted_rects;
  last_invalid_rects_ = inverted_rects;
  last_buffer_ = buffer;

  // TODO(ajwong): These completion signals back to the upper class are very
  // strange.  Fix it.
  capturer_->FinishCapture(capture_data, callback);
}

void CapturerLinuxPimpl::DeinitXlib() {
  if (gc_) {
    XFreeGC(display_, gc_);
    gc_ = NULL;
  }

  if (display_) {
    XCloseDisplay(display_);
    display_ = NULL;
  }
}

void CapturerLinuxPimpl::FastBlit(XImage* image, int dest_x, int dest_y,
                                  CaptureData* capture_data) {
  uint8* src_pos = reinterpret_cast<uint8*>(image->data);

  DataPlanes planes = capture_data->data_planes();
  uint8* dst_buffer = planes.data[0];

  const int dst_stride = planes.strides[0];
  const int src_stride = image->bytes_per_line;

  // Produce an upside down image.
  uint8* dst_pos = dst_buffer + dst_stride * (capturer_->height() - dest_y - 1);
  dst_pos += dest_x * kBytesPerPixel;
  for (int y = 0; y < image->height; ++y) {
    memcpy(dst_pos, src_pos, image->width * kBytesPerPixel);

    src_pos += src_stride;
    dst_pos -= dst_stride;
  }
}

// TODO(hclam): SlowBlit() is incorrect.
void CapturerLinuxPimpl::SlowBlit(XImage* image, int dest_x, int dest_y,
                                  CaptureData* capture_data) {
  DataPlanes planes = capture_data->data_planes();
  uint8* dst_buffer = planes.data[0];
  const int dst_stride = planes.strides[0];

  unsigned int red_shift = IndexOfLowestBit(image->red_mask);
  unsigned int blue_shift = IndexOfLowestBit(image->blue_mask);
  unsigned int green_shift = IndexOfLowestBit(image->green_mask);

  unsigned int max_red = image->red_mask >> red_shift;
  unsigned int max_blue = image->blue_mask >> blue_shift;
  unsigned int max_green = image->green_mask >> green_shift;

  for (int y = 0; y < image->height; y++) {
    // Flip the coordinate system to match the client.
    int dst_row = image->height - y - 1;
    uint32_t* dst_pos = GetRowStart(dst_buffer, dst_stride, dst_row + dest_y);
    dst_pos += dest_x;
    for (int x = 0; x < image->width; x++) {
      unsigned long pixel = XGetPixel(image, x, y);
      uint32_t r = (((pixel & image->red_mask) >> red_shift) * max_red) / 255;
      uint32_t g =
          (((pixel & image->green_mask) >> green_shift) * max_blue) / 255;
      uint32_t b =
          (((pixel & image->blue_mask) >> blue_shift) * max_green) / 255;

      // Write as 32-bit RGB.
      *dst_pos = r << 16 | g << 8 | b;
      dst_pos++;
    }
  }
}

// static
Capturer* Capturer::Create(MessageLoop* message_loop) {
  return new CapturerLinux(message_loop);
}

}  // namespace remoting
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <initializer_list>

using namespace std;

template <class T>
struct TheList
{
	vector<T> listVector;
	TheList(intializer_list<T> myList) : listVector(myList)
	{
		for (auto i: listVector)
		{
			cout << i << endl;
		}
	}
};

int main()
{
	TheList<string> toDoList {"start cpp-tricks.com",
				    "make brl-cad website mockup",
                                    "work on FLAT, PEEMT, SLLP",
				    "Major Project",
				    "Mathematics"};

}
<commit_msg>added "does not compile error free" warning<commit_after>/* This code does not compile error free yet, correct it or ignore it */
#include <iostream>
#include <vector>
#include <initializer_list>

using namespace std;

template <class T>
struct TheList
{
	vector<T> listVector;
	TheList(intializer_list<T> myList) : listVector(myList)
	{
		for (auto i: listVector)
		{
			cout << i << endl;
		}
	}
};

int main()
{
	TheList<string> toDoList {"start cpp-tricks.com",
				    "make brl-cad website mockup",
                                    "work on FLAT, PEEMT, SLLP",
				    "Major Project",
				    "Mathematics"};

}
<|endoftext|>


<commit_before>#ifdef _WIN32
#include <string>
#include <vector>
#include <windows.h>
#include "winargs.h"
#include "winglob.h"

static bool is_unc(const std::wstring &argw) {
	if (argw.length() > 4) {
		return argw[0] == '\\' && argw[1] == '\\' && argw[2] == '?' && argw[3] == '\\';
	}
	return false;
}

// Translate a path into components, i.e. { "C:", "Users", "Me", "Doc*", "*.foo" }
static std::vector<std::wstring> split_components(const std::wstring &argw) {
	std::vector<std::wstring> components;
	if (is_unc(argw)) {
		// This tells us specifically not to perform wildcard expansion.
		components.push_back(argw);
		return components;
	}

	size_t pos = 0;
	while (pos != argw.npos) {
		size_t next = argw.find_first_of(L"/\\", pos);
		if (next == pos && pos != 0) {
			// Ignore doubled up slashes, i.e. C:\\Users\\\\Me.
			++pos;
			continue;
		}

		if (next == argw.npos) {
			components.push_back(argw.substr(pos));
		} else {
			components.push_back(argw.substr(pos, next - pos));
		}
		pos = next;
	}

	return components;
}

static std::wstring find_base_context(std::vector<std::wstring> &components) {
	if (components[0].length() == 2 && components[0][1] == ':') {
		// Is the first thing a drive letter?
		std::wstring context = components[0] + L"\\";
		components.erase(components.begin());
		return context;
	} else if (components[0].length() == 0) {
		components.erase(components.begin());
		return L"\\";
	} else if (components.size() == 1 && is_unc(components[0])) {
		// UNC path, use it as a context directly to avoid any wildcard parsing.
		std::wstring context = components[0];
		components.clear();
		return context;
	}

	return L"";
}

// Expand the wildcard component against each context folder in input, and return the full list.
static std::vector<std::wstring> next_contexts(const std::vector<std::wstring> &input, std::wstring component) {
	std::vector<std::wstring> output;

	// Special case for . or .. as the component.
	if (component == L"." || component == L"..") {
		for (const std::wstring &context : input) {
			std::wstring base = context.empty() ? L"" : (context + L"\\");
			output.push_back(base + component);
		}
		return output;
	}

	for (const std::wstring &context : input) {
		std::wstring base = context.empty() ? L"" : (context + L"\\");
		std::wstring search = base + component;

		WIN32_FIND_DATA data;
		HANDLE finder = FindFirstFile(search.c_str(), &data);
		do {
			std::wstring filename(data.cFileName, wcsnlen(data.cFileName, MAX_PATH));
			if (filename == L"." || filename == L"..") {
				continue;
			}

			output.push_back(base + filename);
		} while (FindNextFile(finder, &data) != 0);
		FindClose(finder);
	}

	return output;
}

void winargs_get_wildcard(const char *arg, std::vector<std::string> &files) {
	std::wstring argw;
	str_to_utf16z(arg, argw);
	if (argw.empty()) {
		return;
	}
	argw.resize(argw.size() - 1);

	// We need to process each component, one at a time.
	std::vector<std::wstring> components = split_components(argw);
	std::vector<std::wstring> contexts;
	contexts.push_back(find_base_context(components));

	for (const std::wstring &component : components) {
		contexts = next_contexts(contexts, component);
	}

	// Now we have all the expanded files, so convert to utf8.
	for (const std::wstring &wfilename : contexts) {
		std::string filename;
		str_to_utf8z(wfilename.c_str(), filename);
		// Now truncate off the null - we don't need it here.
		if (!filename.empty()) {
			filename.resize(filename.size() - 1);
		}
		files.push_back(filename);
	}
}
#endif
<commit_msg>Correctly handle Windows fileshare paths.<commit_after>#ifdef _WIN32
#include <string>
#include <vector>
#include <windows.h>
#include "winargs.h"
#include "winglob.h"

static bool is_unc(const std::wstring &argw) {
	if (argw.length() > 4) {
		return argw[0] == '\\' && argw[1] == '\\' && argw[2] == '?' && argw[3] == '\\';
	}
	return false;
}

// Translate a path into components, i.e. { "C:", "Users", "Me", "Doc*", "*.foo" }
static std::vector<std::wstring> split_components(const std::wstring &argw) {
	std::vector<std::wstring> components;
	if (is_unc(argw)) {
		// This tells us specifically not to perform wildcard expansion.
		components.push_back(argw);
		return components;
	}

	size_t pos = 0;
	while (pos != argw.npos) {
		size_t next = argw.find_first_of(L"/\\", pos);
		if (next == pos) {
			if (pos != 0) {
				// Ignore doubled up slashes, i.e. C:\\Users\\\\Me.
				++pos;
				continue;
			}
			next = argw.find_first_of(L"/\\", pos + 1);
		}

		if (next == argw.npos) {
			components.push_back(argw.substr(pos));
		} else {
			components.push_back(argw.substr(pos, next - pos));
		}
		pos = next;
	}

	return components;
}

static std::wstring find_base_context(std::vector<std::wstring> &components) {
	if (components[0].length() == 2 && components[0][1] == ':') {
		// Is the first thing a drive letter?
		std::wstring context = components[0] + L"\\";
		components.erase(components.begin());
		return context;
	} else if (components[0].length() == 0) {
		components.erase(components.begin());
		return L"\\";
	} else if (components.size() == 1 && is_unc(components[0])) {
		// UNC path, use it as a context directly to avoid any wildcard parsing.
		std::wstring context = components[0];
		components.clear();
		return context;
	}

	return L"";
}

// Expand the wildcard component against each context folder in input, and return the full list.
static std::vector<std::wstring> next_contexts(const std::vector<std::wstring> &input, std::wstring component) {
	std::vector<std::wstring> output;

	// Special case for . or .. as the component.
	if (component == L"." || component == L"..") {
		for (const std::wstring &context : input) {
			std::wstring base = context.empty() ? L"" : (context + L"\\");
			output.push_back(base + component);
		}
		return output;
	}

	for (const std::wstring &context : input) {
		std::wstring base = context.empty() ? L"" : (context + L"\\");
		std::wstring search = base + component;

		WIN32_FIND_DATA data;
		HANDLE finder = FindFirstFile(search.c_str(), &data);
		if (finder == INVALID_HANDLE_VALUE) {
			output.push_back(search);
			continue;
		}
		do {
			std::wstring filename(data.cFileName, wcsnlen(data.cFileName, MAX_PATH));
			if (filename == L"." || filename == L"..") {
				continue;
			}

			output.push_back(base + filename);
		} while (FindNextFile(finder, &data) != 0);
		FindClose(finder);
	}

	return output;
}

void winargs_get_wildcard(const char *arg, std::vector<std::string> &files) {
	std::wstring argw;
	str_to_utf16z(arg, argw);
	if (argw.empty()) {
		return;
	}
	argw.resize(argw.size() - 1);

	// We need to process each component, one at a time.
	std::vector<std::wstring> components = split_components(argw);
	std::vector<std::wstring> contexts;
	contexts.push_back(find_base_context(components));

	for (const std::wstring &component : components) {
		contexts = next_contexts(contexts, component);
	}

	// Now we have all the expanded files, so convert to utf8.
	for (const std::wstring &wfilename : contexts) {
		std::string filename;
		str_to_utf8z(wfilename.c_str(), filename);
		// Now truncate off the null - we don't need it here.
		if (!filename.empty()) {
			filename.resize(filename.size() - 1);
		}
		files.push_back(filename);
	}
}
#endif
<|endoftext|>


<commit_before>/*
** qi.c
** Login : <ctaf42@cgestes-de2>
** Started on  Thu Nov 18 18:11:44 2010 Cedric GESTES
** $Id$
**
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2010 Cedric GESTES
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include <qi/qi.h>
#include <qi/messaging.hpp>
#include <qi/messaging/detail/client_impl.hpp>

struct client_private_t {
public:
  //Constructor
  client_private_t(const char *name, const char *address)
    : client(std::string(name), std::string(address))
  {}

public:
  qi::detail::ClientImpl client;
};

struct message_private_t {
  qi::serialization::BinarySerializer msg;
};

qi_client_t *qi_client_create(const char *name, const char *address) {
  client_private_t *pclient = new client_private_t(name, address);
  return (qi_client_t *)pclient;
}

void      qi_client_call(qi_client_t *client, const char *method, qi_message_t *msg, qi_message_t *ret)
{
  client_private_t  *pclient  = (client_private_t *)client;
  message_private_t *preturn  = (message_private_t *)ret;
  message_private_t *pmessage = (message_private_t *)msg;

  pclient->client.call(std::string(method), pmessage->msg, preturn->msg);
}

qi_message_t *qi_message_create()
{
  message_private_t *pmsg = new message_private_t();
  return (qi_message_t *)pmsg;
}

void qi_message_write_int(qi_message_t *msg, const int i)
{
  message_private_t *pmsg = (message_private_t *)msg;
  pmsg->msg.writeInt(i);
}

void qi_message_write_string(qi_message_t *msg, const char *s)
{
  message_private_t *pmsg = (message_private_t *)msg;
  pmsg->msg.writeString(std::string(s));
}

int qi_message_read_int(qi_message_t *msg)
{
  message_private_t *pmsg = (message_private_t *)msg;
  int i;
  pmsg->msg.readInt(i);
  return i;
}

char *qi_message_read_string(qi_message_t *msg)
{
 message_private_t *pmsg = (message_private_t *)msg;
 std::string s;
 pmsg->msg.readString(s);
 //TODO: buffer overflow
 return strdup(s.c_str());
}
<commit_msg>Protect cbindings from win strdup warning<commit_after>/*
** qi.c
** Login : <ctaf42@cgestes-de2>
** Started on  Thu Nov 18 18:11:44 2010 Cedric GESTES
** $Id$
**
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2010 Cedric GESTES
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include <qi/qi.h>
#include <qi/messaging.hpp>
#include <qi/messaging/detail/client_impl.hpp>

struct client_private_t {
public:
  //Constructor
  client_private_t(const char *name, const char *address)
    : client(std::string(name), std::string(address))
  {}

public:
  qi::detail::ClientImpl client;
};

struct message_private_t {
  qi::serialization::BinarySerializer msg;
};

qi_client_t *qi_client_create(const char *name, const char *address) {
  client_private_t *pclient = new client_private_t(name, address);
  return (qi_client_t *)pclient;
}

void      qi_client_call(qi_client_t *client, const char *method, qi_message_t *msg, qi_message_t *ret)
{
  client_private_t  *pclient  = (client_private_t *)client;
  message_private_t *preturn  = (message_private_t *)ret;
  message_private_t *pmessage = (message_private_t *)msg;

  pclient->client.call(std::string(method), pmessage->msg, preturn->msg);
}

qi_message_t *qi_message_create()
{
  message_private_t *pmsg = new message_private_t();
  return (qi_message_t *)pmsg;
}

void qi_message_write_int(qi_message_t *msg, const int i)
{
  message_private_t *pmsg = (message_private_t *)msg;
  pmsg->msg.writeInt(i);
}

void qi_message_write_string(qi_message_t *msg, const char *s)
{
  message_private_t *pmsg = (message_private_t *)msg;
  pmsg->msg.writeString(std::string(s));
}

int qi_message_read_int(qi_message_t *msg)
{
  message_private_t *pmsg = (message_private_t *)msg;
  int i;
  pmsg->msg.readInt(i);
  return i;
}

char *qi_message_read_string(qi_message_t *msg)
{
 message_private_t *pmsg = (message_private_t *)msg;
 std::string s;
 pmsg->msg.readString(s);
 //TODO: buffer overflow
#ifdef _WIN32
 return _strdup(s.c_str());
#else
 return strdup(s.c_str());
#endif
}
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#include "shapes.hxx"
#include "invader.hrc"
#include "expl.hxx"
#include <vcl/outdev.hxx>
#include <vcl/virdev.hxx>
#include <vcl/bitmap.hxx>

Image* ImplLoadImage( USHORT nId, ResMgr* pRes )
{
    return new Image( Bitmap( ResId( nId, pRes ) ), COL_WHITE );
}

// ------------------------------------------------------------------------

Fighter::Fighter(Size& rOut, ResMgr* pRes) :
            pFightr(NULL),
            pFightl(NULL),
            eMode(FIGHT_NORM),
            bNoKey(FALSE),
            nDelay(0),
            pFight1(NULL)
{
    pFight1 = ImplLoadImage( FIGHTER1, pRes );
    pFightr = ImplLoadImage( FIGHTERR, pRes );
    pFightl = ImplLoadImage( FIGHTERL, pRes );

    aSize = pFight1->GetSizePixel();

    aOut.X() = rOut.Width()/2-aSize.Width()/2;
    aOut.Y() = rOut.Height()-aSize.Height()-10;

    aStart = aOut;

    nMax = rOut.Width() - aSize.Width();
}

Fighter::~Fighter()
{

    delete pFight1;
    delete pFightr;
    delete pFightl;
}

void Fighter::Init()
{
    aOut  = aStart;
    eMode = FIGHT_NORM;
}

void Fighter::Paint(OutputDevice& rDev)
{
    if(eMode == FIGHT_DEST)
        return;

    switch(eMode)
    {
        case FIGHT_NORM:
            rDev.DrawImage(aOut,*pFight1);
            break;
        case FIGHT_RIGHT:
            rDev.DrawImage(aOut,*pFightr);
            break;
        case FIGHT_LEFT:
            rDev.DrawImage(aOut,*pFightl);
            break;
        case FIGHT_DEST:
            break;
    }

    if(nDelay <= 0)
        eMode = FIGHT_NORM;
    else
        nDelay--;

    bNoKey = FALSE;
}

void Fighter::Move(long nDirect)
{
    if(eMode == FIGHT_DEST)
        return;

    if(nDirect < 0)
    {
        aOut.X() -= KANONEX;
        eMode = FIGHT_LEFT;
    }
    else
    {
        aOut.X() += KANONEX;
        eMode = FIGHT_RIGHT;
    }

    nDelay = 5;

    if(aOut.X() <= 0)
        aOut.X() = 1;
    if(aOut.X() > nMax)
        aOut.X() = nMax;

    bNoKey = TRUE;
}

BOOL Fighter::Kollision(Rectangle aRect, Explosion* pExpl)
{
        if((aOut.X() <= aRect.Left() && aOut.X()+aSize.Width() >= aRect.Right()) &&
            (aOut.Y() <= aRect.Top() && aOut.Y()+aSize.Height() >= aRect.Bottom()))
        {
            pExpl->InsertExpl(aOut);
            eMode = FIGHT_DEST;
            return TRUE;
        }

    return FALSE;
}

Munition::Munition(ResMgr* pRes) :
            MunitionListe(0,1),
            pMunition2( NULL ),
            pMunition1( NULL )
{
    pMunition1 = ImplLoadImage( MUNITION1,pRes );
    pMunition2 = ImplLoadImage( MUNITION2,pRes );

    aSize = pMunition1->GetSizePixel();
}

Munition::~Munition()
{
    ClearAll();

    delete pMunition1;
    delete pMunition2;
}

void Munition::Start(Point& rPoint)
{
    if( Count() >= MUNMAX)
        return;

    Munition_Impl* pWork = new Munition_Impl();

    pWork->aPoint = rPoint;
    pWork->eMode = MUNI_MODE1;

    Insert(pWork);
}

void Munition::Paint(OutputDevice& rDev)
{
    unsigned long i;
    for(i=0; i<Count();i++)
    {
        switch(GetMode(i))
        {
            case MUNI_MODE1:
                rDev.DrawImage(GetPoint(i),*pMunition1);
                SetMode(i,MUNI_MODE2);
                break;
            case MUNI_MODE2:
                rDev.DrawImage(GetPoint(i),*pMunition2);
                SetMode(i,MUNI_MODE1);
                break;
            case MUNI_DEL:
                break;
        }

        SetKoll(i,Rectangle(Point(GetPoint(i).X()+aSize.Width()/2,GetPoint(i).Y()),
                    Point(GetPoint(i).X()+aSize.Width()/2,
                            GetPoint(i).Y())));

        SetPoint(i,Point(GetPoint(i).X(),GetPoint(i).Y() - MUNIY));
        if(GetPoint(i).Y() <= aSize.Height()*-1)
        {
            SetMode(i,MUNI_DEL);
        }
    }
}

long Munition::RemoveMunition()
{
    for(long i=Count()-1; i>=0; i--)
    {
        if(GetMode(i) == MUNI_DEL)
        {
            Munition_Impl* pWork = GetObject(i);
            Remove(pWork);
            delete pWork;
        }
    }

    return 5-Count();
}

void Munition::ClearAll()
{
    for(long i=Count()-1; i>=0; i--)
        delete  GetObject(i);

    Clear();
}

Bombe::Bombe(ResMgr* pRes) :
        BombenListe(0,1)
{
    pBombe = ImplLoadImage( BOMBE,pRes );

    aSize = pBombe->GetSizePixel();
    nSpeed = BOMBEY;
}

Bombe::~Bombe()
{
    ClearAll();

    delete pBombe;
}

void Bombe::Paint(OutputDevice& rDev)
{
    unsigned long i;
    for(i=0; i<Count();i++)
    {
        rDev.DrawImage(GetPoint(i),*pBombe);
        SetKoll(i,Rectangle(Point(GetPoint(i).X()+aSize.Width()/2,
                                GetPoint(i).Y()+aSize.Height()),
                        Point(GetPoint(i).X()+aSize.Width()/2,
                            GetPoint(i).Y()+aSize.Height())));

        SetPoint(i,Point(GetPoint(i).X(),GetPoint(i).Y() + MUNIY));
    }
}

void Bombe::InsertBombe(const Point& rPoint)
{
    Bombe_Impl* pWork = new Bombe_Impl;
    pWork->aXY = rPoint;
    pWork->bDelete = FALSE;
    Insert(pWork);
}

void Bombe::RemoveBomben()
{
    for(long i=Count()-1; i>=0; i--)
    {
        Bombe_Impl* pWork = GetObject(i);
        if(pWork->bDelete)
        {
            Remove(pWork);
            delete pWork;
        }
    }
}

void Bombe::ClearAll()
{
    unsigned long i;
    for(i=0;i<Count();i++)
        delete GetObject(i);
    Clear();
}

BOOL Bombe::Kollision(Rectangle aRect, Explosion* pExpl)
{
    unsigned long i;
    for(i=0;i<Count();i++)
    {
        if((GetPoint(i).X() <= aRect.Left() && GetPoint(i).X()+aSize.Width() >= aRect.Right()) &&
            (GetPoint(i).Y() <= aRect.Top() && GetPoint(i).Y()+aSize.Height() >= aRect.Bottom()))
        {
            pExpl->InsertExpl(GetPoint(i));
            SetDelete(i);
            return TRUE;
        }
    }

    return FALSE;
}

Wall::Wall(ResMgr* pRes) :
            WallListe(0,1),
            pWall1(0L),
            pWall2(0L),
            pWall3(0L),
            pWall4(0L),
            pWall5(0L),
            pWall6(0L),
            pWall7(0L),
            pWall8(0L),
            pWall9(0L),
            pWall10(0L)
{
    pWall1  = ImplLoadImage( WALL1,pRes );
    pWall2  = ImplLoadImage( WALL2,pRes );
    pWall3  = ImplLoadImage( WALL3,pRes );
    pWall4  = ImplLoadImage( WALL4,pRes );
    pWall5  = ImplLoadImage( WALL5,pRes );
    pWall6  = ImplLoadImage( WALL6,pRes );
    pWall7  = ImplLoadImage( WALL7,pRes );
    pWall8  = ImplLoadImage( WALL8,pRes );
    pWall9  = ImplLoadImage( WALL9,pRes );
    pWall10 = ImplLoadImage( WALL10,pRes );

    aSize = pWall1->GetSizePixel();
}

Wall::~Wall()
{
    ClearAll();

    delete pWall1;
    delete pWall2;
    delete pWall3;
    delete pWall4;
    delete pWall5;
    delete pWall6;
    delete pWall7;
    delete pWall8;
    delete pWall9;
    delete pWall10;
}

void Wall::Paint(OutputDevice& rDev)
{
    unsigned long i;
    for(i=0; i<Count(); i++)
    {
        switch(GetMode(i))
        {
            case WALL_MOD1:
                rDev.DrawImage(GetPoint(i),*pWall1);
                break;
            case WALL_MOD2:
                rDev.DrawImage(GetPoint(i),*pWall2);
                break;
            case WALL_MOD3:
                rDev.DrawImage(GetPoint(i),*pWall3);
                break;
            case WALL_MOD4:
                rDev.DrawImage(GetPoint(i),*pWall4);
                break;
            case WALL_MOD5:
                rDev.DrawImage(GetPoint(i),*pWall5);
                break;
            case WALL_MOD6:
                rDev.DrawImage(GetPoint(i),*pWall6);
                break;
            case WALL_MOD7:
                rDev.DrawImage(GetPoint(i),*pWall7);
                break;
            case WALL_MOD8:
                rDev.DrawImage(GetPoint(i),*pWall8);
                break;
            case WALL_MOD9:
                rDev.DrawImage(GetPoint(i),*pWall9);
                break;
            case WALL_MOD10:
                rDev.DrawImage(GetPoint(i),*pWall10);
                break;
            case WALL_DEL:
                break;
        }

    }
}

void Wall::InsertWall(const Point& rPoint)
{
    Wall_Impl* pWork = new Wall_Impl();

    pWork->aXY = rPoint;
    pWork->aXY.Y() = WALLY;
    pWork->eMode = WALL_MOD1;

    Insert(pWork);
}

void Wall::ClearAll()
{
    unsigned long i;
    for(i=0; i<Count(); i++)
        delete GetObject(i);

    Clear();
}

BOOL Wall::Kollision(Rectangle& rRect, BOOL bDel)
{
    BOOL nTreffer = FALSE;

    Rectangle aWork;

    unsigned long i;
    for(i=0; i<Count();i++)
    {

        Point aPoint = GetPoint(i);
        aWork = Rectangle(Point(aPoint.X(),aPoint.Y()-WALLKOLL),
                            Point(aPoint.X()+aSize.Width(),
                            aPoint.Y()+aSize.Height()-WALLKOLL));

        if((aWork.Left() <= rRect.Left() &&  aWork.Right() >= rRect.Right()) &&
            (aWork.Top() <= rRect.Top() && aWork.Bottom() >= rRect.Bottom()) &&
                GetMode(i) != WALL_DEL)
        {
            switch(GetMode(i))
            {
                case WALL_MOD1:
                    SetMode(i,WALL_MOD2);
                    break;
                case WALL_MOD2:
                    SetMode(i,WALL_MOD3);
                    break;
                case WALL_MOD3:
                    SetMode(i,WALL_MOD4);
                    break;
                case WALL_MOD4:
                    SetMode(i,WALL_MOD5);
                    break;
                case WALL_MOD5:
                    SetMode(i,WALL_MOD6);
                    break;
                case WALL_MOD6:
                    SetMode(i,WALL_MOD7);
                    break;
                case WALL_MOD7:
                    SetMode(i,WALL_MOD8);
                    break;
                case WALL_MOD8:
                    SetMode(i,WALL_MOD9);
                    break;
                case WALL_MOD9:
                    SetMode(i,WALL_MOD10);
                    break;
                case WALL_MOD10:
                    SetMode(i,WALL_DEL);
                    break;
                case WALL_DEL:
                    break;
            }

            if(bDel)
                SetMode(i,WALL_DEL);

            nTreffer = TRUE;
        }
    }

    return nTreffer;
}
<commit_msg>INTEGRATION: CWS residcleanup (1.5.72); FILE MERGED 2007/02/18 19:58:12 pl 1.5.72.1: #i74635# get rid of implicit global ResMgr<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: shapes.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 10:02:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#include "shapes.hxx"
#include "invader.hrc"
#include "expl.hxx"
#include <vcl/outdev.hxx>
#include <vcl/virdev.hxx>
#include <vcl/bitmap.hxx>

Image* ImplLoadImage( USHORT nId, ResMgr* pRes )
{
    return new Image( Bitmap( ResId( nId, *pRes ) ), COL_WHITE );
}

// ------------------------------------------------------------------------

Fighter::Fighter(Size& rOut, ResMgr* pRes) :
            pFightr(NULL),
            pFightl(NULL),
            eMode(FIGHT_NORM),
            bNoKey(FALSE),
            nDelay(0),
            pFight1(NULL)
{
    pFight1 = ImplLoadImage( FIGHTER1, pRes );
    pFightr = ImplLoadImage( FIGHTERR, pRes );
    pFightl = ImplLoadImage( FIGHTERL, pRes );

    aSize = pFight1->GetSizePixel();

    aOut.X() = rOut.Width()/2-aSize.Width()/2;
    aOut.Y() = rOut.Height()-aSize.Height()-10;

    aStart = aOut;

    nMax = rOut.Width() - aSize.Width();
}

Fighter::~Fighter()
{

    delete pFight1;
    delete pFightr;
    delete pFightl;
}

void Fighter::Init()
{
    aOut  = aStart;
    eMode = FIGHT_NORM;
}

void Fighter::Paint(OutputDevice& rDev)
{
    if(eMode == FIGHT_DEST)
        return;

    switch(eMode)
    {
        case FIGHT_NORM:
            rDev.DrawImage(aOut,*pFight1);
            break;
        case FIGHT_RIGHT:
            rDev.DrawImage(aOut,*pFightr);
            break;
        case FIGHT_LEFT:
            rDev.DrawImage(aOut,*pFightl);
            break;
        case FIGHT_DEST:
            break;
    }

    if(nDelay <= 0)
        eMode = FIGHT_NORM;
    else
        nDelay--;

    bNoKey = FALSE;
}

void Fighter::Move(long nDirect)
{
    if(eMode == FIGHT_DEST)
        return;

    if(nDirect < 0)
    {
        aOut.X() -= KANONEX;
        eMode = FIGHT_LEFT;
    }
    else
    {
        aOut.X() += KANONEX;
        eMode = FIGHT_RIGHT;
    }

    nDelay = 5;

    if(aOut.X() <= 0)
        aOut.X() = 1;
    if(aOut.X() > nMax)
        aOut.X() = nMax;

    bNoKey = TRUE;
}

BOOL Fighter::Kollision(Rectangle aRect, Explosion* pExpl)
{
        if((aOut.X() <= aRect.Left() && aOut.X()+aSize.Width() >= aRect.Right()) &&
            (aOut.Y() <= aRect.Top() && aOut.Y()+aSize.Height() >= aRect.Bottom()))
        {
            pExpl->InsertExpl(aOut);
            eMode = FIGHT_DEST;
            return TRUE;
        }

    return FALSE;
}

Munition::Munition(ResMgr* pRes) :
            MunitionListe(0,1),
            pMunition2( NULL ),
            pMunition1( NULL )
{
    pMunition1 = ImplLoadImage( MUNITION1,pRes );
    pMunition2 = ImplLoadImage( MUNITION2,pRes );

    aSize = pMunition1->GetSizePixel();
}

Munition::~Munition()
{
    ClearAll();

    delete pMunition1;
    delete pMunition2;
}

void Munition::Start(Point& rPoint)
{
    if( Count() >= MUNMAX)
        return;

    Munition_Impl* pWork = new Munition_Impl();

    pWork->aPoint = rPoint;
    pWork->eMode = MUNI_MODE1;

    Insert(pWork);
}

void Munition::Paint(OutputDevice& rDev)
{
    unsigned long i;
    for(i=0; i<Count();i++)
    {
        switch(GetMode(i))
        {
            case MUNI_MODE1:
                rDev.DrawImage(GetPoint(i),*pMunition1);
                SetMode(i,MUNI_MODE2);
                break;
            case MUNI_MODE2:
                rDev.DrawImage(GetPoint(i),*pMunition2);
                SetMode(i,MUNI_MODE1);
                break;
            case MUNI_DEL:
                break;
        }

        SetKoll(i,Rectangle(Point(GetPoint(i).X()+aSize.Width()/2,GetPoint(i).Y()),
                    Point(GetPoint(i).X()+aSize.Width()/2,
                            GetPoint(i).Y())));

        SetPoint(i,Point(GetPoint(i).X(),GetPoint(i).Y() - MUNIY));
        if(GetPoint(i).Y() <= aSize.Height()*-1)
        {
            SetMode(i,MUNI_DEL);
        }
    }
}

long Munition::RemoveMunition()
{
    for(long i=Count()-1; i>=0; i--)
    {
        if(GetMode(i) == MUNI_DEL)
        {
            Munition_Impl* pWork = GetObject(i);
            Remove(pWork);
            delete pWork;
        }
    }

    return 5-Count();
}

void Munition::ClearAll()
{
    for(long i=Count()-1; i>=0; i--)
        delete  GetObject(i);

    Clear();
}

Bombe::Bombe(ResMgr* pRes) :
        BombenListe(0,1)
{
    pBombe = ImplLoadImage( BOMBE,pRes );

    aSize = pBombe->GetSizePixel();
    nSpeed = BOMBEY;
}

Bombe::~Bombe()
{
    ClearAll();

    delete pBombe;
}

void Bombe::Paint(OutputDevice& rDev)
{
    unsigned long i;
    for(i=0; i<Count();i++)
    {
        rDev.DrawImage(GetPoint(i),*pBombe);
        SetKoll(i,Rectangle(Point(GetPoint(i).X()+aSize.Width()/2,
                                GetPoint(i).Y()+aSize.Height()),
                        Point(GetPoint(i).X()+aSize.Width()/2,
                            GetPoint(i).Y()+aSize.Height())));

        SetPoint(i,Point(GetPoint(i).X(),GetPoint(i).Y() + MUNIY));
    }
}

void Bombe::InsertBombe(const Point& rPoint)
{
    Bombe_Impl* pWork = new Bombe_Impl;
    pWork->aXY = rPoint;
    pWork->bDelete = FALSE;
    Insert(pWork);
}

void Bombe::RemoveBomben()
{
    for(long i=Count()-1; i>=0; i--)
    {
        Bombe_Impl* pWork = GetObject(i);
        if(pWork->bDelete)
        {
            Remove(pWork);
            delete pWork;
        }
    }
}

void Bombe::ClearAll()
{
    unsigned long i;
    for(i=0;i<Count();i++)
        delete GetObject(i);
    Clear();
}

BOOL Bombe::Kollision(Rectangle aRect, Explosion* pExpl)
{
    unsigned long i;
    for(i=0;i<Count();i++)
    {
        if((GetPoint(i).X() <= aRect.Left() && GetPoint(i).X()+aSize.Width() >= aRect.Right()) &&
            (GetPoint(i).Y() <= aRect.Top() && GetPoint(i).Y()+aSize.Height() >= aRect.Bottom()))
        {
            pExpl->InsertExpl(GetPoint(i));
            SetDelete(i);
            return TRUE;
        }
    }

    return FALSE;
}

Wall::Wall(ResMgr* pRes) :
            WallListe(0,1),
            pWall1(0L),
            pWall2(0L),
            pWall3(0L),
            pWall4(0L),
            pWall5(0L),
            pWall6(0L),
            pWall7(0L),
            pWall8(0L),
            pWall9(0L),
            pWall10(0L)
{
    pWall1  = ImplLoadImage( WALL1,pRes );
    pWall2  = ImplLoadImage( WALL2,pRes );
    pWall3  = ImplLoadImage( WALL3,pRes );
    pWall4  = ImplLoadImage( WALL4,pRes );
    pWall5  = ImplLoadImage( WALL5,pRes );
    pWall6  = ImplLoadImage( WALL6,pRes );
    pWall7  = ImplLoadImage( WALL7,pRes );
    pWall8  = ImplLoadImage( WALL8,pRes );
    pWall9  = ImplLoadImage( WALL9,pRes );
    pWall10 = ImplLoadImage( WALL10,pRes );

    aSize = pWall1->GetSizePixel();
}

Wall::~Wall()
{
    ClearAll();

    delete pWall1;
    delete pWall2;
    delete pWall3;
    delete pWall4;
    delete pWall5;
    delete pWall6;
    delete pWall7;
    delete pWall8;
    delete pWall9;
    delete pWall10;
}

void Wall::Paint(OutputDevice& rDev)
{
    unsigned long i;
    for(i=0; i<Count(); i++)
    {
        switch(GetMode(i))
        {
            case WALL_MOD1:
                rDev.DrawImage(GetPoint(i),*pWall1);
                break;
            case WALL_MOD2:
                rDev.DrawImage(GetPoint(i),*pWall2);
                break;
            case WALL_MOD3:
                rDev.DrawImage(GetPoint(i),*pWall3);
                break;
            case WALL_MOD4:
                rDev.DrawImage(GetPoint(i),*pWall4);
                break;
            case WALL_MOD5:
                rDev.DrawImage(GetPoint(i),*pWall5);
                break;
            case WALL_MOD6:
                rDev.DrawImage(GetPoint(i),*pWall6);
                break;
            case WALL_MOD7:
                rDev.DrawImage(GetPoint(i),*pWall7);
                break;
            case WALL_MOD8:
                rDev.DrawImage(GetPoint(i),*pWall8);
                break;
            case WALL_MOD9:
                rDev.DrawImage(GetPoint(i),*pWall9);
                break;
            case WALL_MOD10:
                rDev.DrawImage(GetPoint(i),*pWall10);
                break;
            case WALL_DEL:
                break;
        }

    }
}

void Wall::InsertWall(const Point& rPoint)
{
    Wall_Impl* pWork = new Wall_Impl();

    pWork->aXY = rPoint;
    pWork->aXY.Y() = WALLY;
    pWork->eMode = WALL_MOD1;

    Insert(pWork);
}

void Wall::ClearAll()
{
    unsigned long i;
    for(i=0; i<Count(); i++)
        delete GetObject(i);

    Clear();
}

BOOL Wall::Kollision(Rectangle& rRect, BOOL bDel)
{
    BOOL nTreffer = FALSE;

    Rectangle aWork;

    unsigned long i;
    for(i=0; i<Count();i++)
    {

        Point aPoint = GetPoint(i);
        aWork = Rectangle(Point(aPoint.X(),aPoint.Y()-WALLKOLL),
                            Point(aPoint.X()+aSize.Width(),
                            aPoint.Y()+aSize.Height()-WALLKOLL));

        if((aWork.Left() <= rRect.Left() &&  aWork.Right() >= rRect.Right()) &&
            (aWork.Top() <= rRect.Top() && aWork.Bottom() >= rRect.Bottom()) &&
                GetMode(i) != WALL_DEL)
        {
            switch(GetMode(i))
            {
                case WALL_MOD1:
                    SetMode(i,WALL_MOD2);
                    break;
                case WALL_MOD2:
                    SetMode(i,WALL_MOD3);
                    break;
                case WALL_MOD3:
                    SetMode(i,WALL_MOD4);
                    break;
                case WALL_MOD4:
                    SetMode(i,WALL_MOD5);
                    break;
                case WALL_MOD5:
                    SetMode(i,WALL_MOD6);
                    break;
                case WALL_MOD6:
                    SetMode(i,WALL_MOD7);
                    break;
                case WALL_MOD7:
                    SetMode(i,WALL_MOD8);
                    break;
                case WALL_MOD8:
                    SetMode(i,WALL_MOD9);
                    break;
                case WALL_MOD9:
                    SetMode(i,WALL_MOD10);
                    break;
                case WALL_MOD10:
                    SetMode(i,WALL_DEL);
                    break;
                case WALL_DEL:
                    break;
            }

            if(bDel)
                SetMode(i,WALL_DEL);

            nTreffer = TRUE;
        }
    }

    return nTreffer;
}
<|endoftext|>


<commit_before><commit_msg>gucefLOADER build fix<commit_after><|endoftext|>