<commit_before>#include "lexer/lexer.h"

Lexer::Lexer(const char *file, bool f) {
    file_ = true;
    std::ifstream infile(file);
    file_name_ = file;
    int length = 0;
    if (infile.fail()) {
      ERROR(std::string, "cannot open file");
      f = false;
      err_msg_ = file + std::string(": file doesn't exist\n");
      return;
    }
    infile.seekg(0, infile.end);
    length = (size_t)infile.tellg();
    infile.seekg(0, infile.beg);
    code_.resize(length + 2, ' ');
    infile.read(&*(code_.begin()), length);
    infile.close();
    size_ = length;
    end_ = length;
    seek_ = 0;
    tok_ = nullptr;
    eos_ = false;
}

Token *Lexer::NextToken() {
    char ch, ch2, ch3;
    TokenType tok;
    Position pos;

    if (!buffer_.empty()) {
      Token *tok = buffer_.back();
      buffer_.pop_back();
      return tok;
    }

    ch = NextCharacter();
    // skip whitespaces
    while (ch != EOF && (ch == ' ' || ch == '\n' || ch == '\t'))
      ch = NextCharacter();

    // skip comments
    while (ch != EOF &&
           ((ch == '/' && LookAhead() == '/') || (ch == '/' && LookAhead() == '*')))
      StripComments(ch);

    // note the current position as we are about to parse
    // a valid(may be) token from this position
    pos = position_;

    if (ch != EOF) {

      // handle keywords, identifiers and numbers
      while (isalnum(ch) || ch == '_')
        return Characterize(ch, pos);

      if (LookAhead() == EOF || LookAhead() == '\0' || LookAhead() == ' ' ||
          LookAhead() == '\t' || LookAhead() == '\n')
        goto one;
      // else ch is a symbol
      ch2 = NextCharacter();

      if (LookAhead() == EOF || LookAhead() == '\0' || LookAhead() == ' ' ||
          LookAhead() == '\t' || LookAhead() == '\n')
        goto two;
      ch3 = NextCharacter();

      // check if there is a three character symbol
      tok = ThreeCharacterSymbol(ch, ch2, ch3);
      if (tok != INVALID) {
        return new Token(std::string({ch, ch2, ch3}), tok,
                         TOKENS[tok].precedance_, pos);
      }
      // as we have gone ahead one character so time to go back
      GoBack();
    two:
      // so now check whether we are at position of two character symbol
      tok = TwoCharacterSymbol(ch, ch2);
      if (tok != INVALID) {
        return new Token(std::string({ch, ch2}), tok, TOKENS[tok].precedance_,
                         pos);
      }

      // No! Let's go back one character
      GoBack();

    one:
      // Only possibility left
      tok = OneCharacterSymbol(ch);
      if (tok != INVALID) {
        return new Token(std::string({ch}), tok, TOKENS[tok].precedance_, pos);
      } else // oops! something went wrong, token is invalid!
        return new Token(std::string({ch}), INVALID, 0, pos);
    }

    // finally reached at the end of the given string
    return new Token(std::string({ch}), EOS, -1, pos);
}

void Lexer::StripComments(char &ch) { // skips all the comments from the string
  char last = '\0';
  // skip the comments - single line comment
  if (ch != EOF && (ch == '/' && LookAhead() == '/')) {
    ch = NextCharacter();
    while (ch != '\n' || ch == EOF)
      ch = NextCharacter();
    ch = NextCharacter();
  }

  // multiline comment, /* */ type
  if (ch != EOF && (ch == '/' && LookAhead() == '*')) {
    last = ch;
    ch = NextCharacter();
    while (ch != EOF && !(last == '*' && ch == '/')) {
      last = ch;
      ch = NextCharacter();
    }
    ch = NextCharacter();
  }

  while (ch != EOF && (ch == ' ' || ch == '\n' || ch == '\t'))
    ch = NextCharacter();
}

void Lexer::GoBack() { // go back one character back
  --seek_;
  if (position_.col_ - 1 < 0) { // we don't want our col_ to be negative
    position_.row_--;           // needed
    position_.col_ = lastColNumber_;
  } else { // okay, so simply decrement col_ member
    position_.col_--;
  }
}

char Lexer::NextCharacter() { // returns the next character from the string
  if (seek_ <= end_) { // if eos_ flag has not been set
    char ch = code_[seek_++];
    if (ch == '\0') { // if we are not processing EOF file character
      ch = EOF;
      eos_ = true;
    }
    if (ch == '\n') { // change the position
      position_.row_++;
      lastColNumber_ = position_.col_;
      position_.col_ = 0;
    } else {
      position_.col_++;
    }
    return ch;
  }
  return EOF;
}

Token *Lexer::Characterize(char ch,
             Position &pos)
{
  std::string buffer;
  if (isdigit(ch))
    return ParseNumber(ch, pos);

  if (isalpha(ch) || ch == '_' || ch == '$')
    return ParseIdentifierOrKeyWord(ch, pos);

  // if none of both then we have to return a invalid token
  return new Token(std::string(""), INVALID, -1, pos);
}

Token *
Lexer::ParseNumber(char ch,
            Position &pos) { // parses the number from the current position
  std::string buffer;        // buffer to store the parsed number
  while (isdigit(ch)) {
    buffer += ch;
    ch = NextCharacter();
  }
  // possible floating point number
  if (ch == '.' || ch == 'e' || ch == 'E') {
    buffer += ch;
    ch = NextCharacter();
    while (isdigit(ch)) {
      buffer += ch;
      ch = NextCharacter();
    }
  }
  // we've gone one character ahead, so go back
  GoBack();

  return new Token(buffer, DIGIT, -1, pos);
}

Token *Lexer::ParseIdentifierOrKeyWord(
    char ch,
    Position &
        pos) { // parses the identifier or a keyword from the current position
  std::string buffer;
  // possibly it is an identifier
  while (isalnum(ch) || ch == '_' || ch == '$') {
    buffer += ch;
    ch = NextCharacter();
  }
  // again went a character ahead
  GoBack();
  // check for KeyWord
  if (buffer[0] != '_' || buffer[0] != '$') {
    for (int i = LET; i <= RET; i++)
      if (buffer[0] == TOKENS[i].value_[0] && buffer == TOKENS[i].value_)
        return new Token(buffer, i, 0, pos);
  }
  return new Token(buffer, IDENT, -1, pos);
}

// although not required because of no use
Token *Lexer::ParseStringLiteral(
    char ch, Position &pos) { // parses the string literal from the string
  std::string str = "";
  if (ch == '"') { // string surrounded by "
    ch = NextCharacter();
    while (ch != '"') {
      str += ch;
      ch = NextCharacter();
    }
  } else if (ch == '\'') { // string surrounded by '
    ch = NextCharacter();
    while (ch != '\'') {
      str += ch;
      ch = NextCharacter();
    }
  }
  return new Token(str, STRING, -1, pos);
}

char parsehex(char ch) {
  if (ch >= '0' && ch <= '9')
    return ch - '0';
  else if ((ch >= 'a' && ch <= 'f')) {
    return 10 + ch - 'a';
  } else if (ch >= 'A' && ch <= 'F') {
    return 10 + ch - 'A';
  }
  throw std::runtime_error("wrong hexadecimal digits");
}

char parseoct(char ch) {
  if (ch >= '0' && ch <= '8')
    return ch - '0';
  throw std::runtime_error("wrong octal digits");
}

char escape_code(std::string str) {
  if (str[0] != '\\')
    return str[0];
  if (str[1] == 'x') {
    char ret = 0;
    ret |= parsehex(str[2]);
    ret <<= 4;
    ret |= parsehex(str[3]);
    return ret;
  } else if (str[1] == 'n')
    return '\n';
  else if (str[1] == 'b')
    return '\b';
  else if (str[1] == 'r')
    return '\r';
  else if (str[1] == 'a')
    return '\a';
  else if (str[1] == 't')
    return '\t';
  else if (str[1] == '"')
    return '"';
  else if (str[1] == '\'')
    return '\'';
  else throw std::runtime_error("unknown escape code");
}

// this function should be used instead of above function
// when we found a token of " or ' that means we are about
// to parse the string from the current position
std::string Lexer::GetStringLiteral() { // returns all the string until it finds "

  // create a buffer
  std::string str = "";
  char ch = NextCharacter();
  while (ch != EOF && (ch != '"' && ch != '\'')) {
    if (ch == '\\') {
        // a possible escape code
        std::string tmp = "";
        tmp += ch;
        ch = NextCharacter();
        tmp += ch;
        if (ch == 'x') {
          ch = NextCharacter();
          tmp += ch;
          ch = NextCharacter();
          tmp += ch;
        }
        ch = escape_code(tmp);
    }
    str += ch; // fill the buffer
    ch = NextCharacter();
  }
  return str;
}

TokenType Lexer::OneCharacterSymbol(
    char ch) { // returns the type of token from the given symbol
  switch (ch) {
  case '(':
    return LPAR;
  case ')':
    return RPAR;
  case '{':
    return LBRACE;
  case '}':
    return RBRACE;
  case '[':
    return LSQB;
  case ']':
    return RSQB;
  case ':':
    return COLON;
  case ';':
    return SCOLON;
  case '"':
  case '\'':
    return STRING;
  case '.':
    return DOT;
  case ',':
    return COMMA;
  case '?':
    return CONDITION;
  case '+':
    return PLUS;
  case '-':
    return MINUS;
  case '/':
    return DIV;
  case '*':
    return MUL;
  case '%':
    return MOD;
  case '>':
    return GT;
  case '<':
    return LT;
  case '=':
    return ASSIGN;
  case '^':
    return XOR;
  case '|':
    return BOR;
  case '&':
    return BAND;
  case '!':
    return NOT;
  case '~':
    return BNOT;
  default:
    return INVALID;
  }
}

TokenType
Lexer::TwoCharacterSymbol(char ch1,
                   char ch2) { // returns the type of symbol of two characters
  switch (ch2) {
  case '=':
    switch (ch1) {
    case '+':
      return PLUSEQ;
    case '-':
      return MINUSEQ;
    case '*':
      return MULEQ;
    case '/':
      return DIVEQ;
    case '%':
      return MODEQ;
    case '^':
      return XOREQ;
    case '&':
      return BANDEQ;
    case '|':
      return BOREQ;
    case '>':
      return GTE;
    case '<':
      return LTE;
    case '=':
      return EQUAL;
    case '!':
      return NOTEQ;
    }
    return INVALID;
  case '|':
    if (ch1 == '|')
      return OR;
    return INVALID;
  case '&':
    if (ch1 == '&')
      return AND;
    return INVALID;
  case '+':
    if (ch1 == '+')
      return INC;
    return INVALID;
  case '-':
    if (ch1 == '-')
      return DEC;
    return INVALID;
  case '<':
    if (ch1 == '<')
      return SHL;
    return INVALID;
  case '>':
    if (ch1 == '>')
      return SHR;
  default:
    return INVALID;
  }
}

bool Lexer::IsFile() const { return file_; }
std::string Lexer::GetFileName() { return file_name_; }

TokenType Lexer::ThreeCharacterSymbol(
    char ch1, char ch2,
    char ch3) { // returns the type of symbol of three characters
  switch (ch3) {
  case '=':
    if (ch1 == '>' && ch2 == '>')
      return SHREQ;
    if (ch1 == '<' && ch2 == '<')
      return SHLEQ;
  default:
    return INVALID;
  }
}

void Lexer::PutBack(Token *tok) { // put in the buffer for one token lookahead
                           // required by parser
  buffer_.push_back(tok);
}

// move to next token
void Lexer::advance()
{
  tok_ = NextToken();
}

double Lexer::GetNumber()
{
  double result = 0.0;
  try {
    result = std::stod(tok_->GetValue());
  } catch (std::exception &e) {
    std::cerr << e.what() << std::endl;
  }

  return result;
}

<commit_msg>Fix: raspberry pi build issue<commit_after>#include "lexer/lexer.h"
#include <stdexcept>

Lexer::Lexer(const char *file, bool f) {
    file_ = true;
    std::ifstream infile(file);
    file_name_ = file;
    int length = 0;
    if (infile.fail()) {
      ERROR(std::string, "cannot open file");
      f = false;
      err_msg_ = file + std::string(": file doesn't exist\n");
      return;
    }
    infile.seekg(0, infile.end);
    length = (size_t)infile.tellg();
    infile.seekg(0, infile.beg);
    code_.resize(length + 2, ' ');
    infile.read(&*(code_.begin()), length);
    infile.close();
    size_ = length;
    end_ = length;
    seek_ = 0;
    tok_ = nullptr;
    eos_ = false;
}

Token *Lexer::NextToken() {
    char ch, ch2, ch3;
    TokenType tok;
    Position pos;

    if (!buffer_.empty()) {
      Token *tok = buffer_.back();
      buffer_.pop_back();
      return tok;
    }

    ch = NextCharacter();
    // skip whitespaces
    while (ch != EOF && (ch == ' ' || ch == '\n' || ch == '\t'))
      ch = NextCharacter();

    // skip comments
    while (ch != EOF &&
           ((ch == '/' && LookAhead() == '/') || (ch == '/' && LookAhead() == '*')))
      StripComments(ch);

    // note the current position as we are about to parse
    // a valid(may be) token from this position
    pos = position_;

    if (ch != EOF) {

      // handle keywords, identifiers and numbers
      while (isalnum(ch) || ch == '_')
        return Characterize(ch, pos);

      if (LookAhead() == EOF || LookAhead() == '\0' || LookAhead() == ' ' ||
          LookAhead() == '\t' || LookAhead() == '\n')
        goto one;
      // else ch is a symbol
      ch2 = NextCharacter();

      if (LookAhead() == EOF || LookAhead() == '\0' || LookAhead() == ' ' ||
          LookAhead() == '\t' || LookAhead() == '\n')
        goto two;
      ch3 = NextCharacter();

      // check if there is a three character symbol
      tok = ThreeCharacterSymbol(ch, ch2, ch3);
      if (tok != INVALID) {
        return new Token(std::string({ch, ch2, ch3}), tok,
                         TOKENS[tok].precedance_, pos);
      }
      // as we have gone ahead one character so time to go back
      GoBack();
    two:
      // so now check whether we are at position of two character symbol
      tok = TwoCharacterSymbol(ch, ch2);
      if (tok != INVALID) {
        return new Token(std::string({ch, ch2}), tok, TOKENS[tok].precedance_,
                         pos);
      }

      // No! Let's go back one character
      GoBack();

    one:
      // Only possibility left
      tok = OneCharacterSymbol(ch);
      if (tok != INVALID) {
        return new Token(std::string({ch}), tok, TOKENS[tok].precedance_, pos);
      } else // oops! something went wrong, token is invalid!
        return new Token(std::string({ch}), INVALID, 0, pos);
    }

    // finally reached at the end of the given string
    return new Token(std::string({ch}), EOS, -1, pos);
}

void Lexer::StripComments(char &ch) { // skips all the comments from the string
  char last = '\0';
  // skip the comments - single line comment
  if (ch != EOF && (ch == '/' && LookAhead() == '/')) {
    ch = NextCharacter();
    while (ch != '\n' || ch == EOF)
      ch = NextCharacter();
    ch = NextCharacter();
  }

  // multiline comment, /* */ type
  if (ch != EOF && (ch == '/' && LookAhead() == '*')) {
    last = ch;
    ch = NextCharacter();
    while (ch != EOF && !(last == '*' && ch == '/')) {
      last = ch;
      ch = NextCharacter();
    }
    ch = NextCharacter();
  }

  while (ch != EOF && (ch == ' ' || ch == '\n' || ch == '\t'))
    ch = NextCharacter();
}

void Lexer::GoBack() { // go back one character back
  --seek_;
  if (position_.col_ - 1 < 0) { // we don't want our col_ to be negative
    position_.row_--;           // needed
    position_.col_ = lastColNumber_;
  } else { // okay, so simply decrement col_ member
    position_.col_--;
  }
}

char Lexer::NextCharacter() { // returns the next character from the string
  if (seek_ <= end_) { // if eos_ flag has not been set
    char ch = code_[seek_++];
    if (ch == '\0') { // if we are not processing EOF file character
      ch = EOF;
      eos_ = true;
    }
    if (ch == '\n') { // change the position
      position_.row_++;
      lastColNumber_ = position_.col_;
      position_.col_ = 0;
    } else {
      position_.col_++;
    }
    return ch;
  }
  return EOF;
}

Token *Lexer::Characterize(char ch,
             Position &pos)
{
  std::string buffer;
  if (isdigit(ch))
    return ParseNumber(ch, pos);

  if (isalpha(ch) || ch == '_' || ch == '$')
    return ParseIdentifierOrKeyWord(ch, pos);

  // if none of both then we have to return a invalid token
  return new Token(std::string(""), INVALID, -1, pos);
}

Token *
Lexer::ParseNumber(char ch,
            Position &pos) { // parses the number from the current position
  std::string buffer;        // buffer to store the parsed number
  while (isdigit(ch)) {
    buffer += ch;
    ch = NextCharacter();
  }
  // possible floating point number
  if (ch == '.' || ch == 'e' || ch == 'E') {
    buffer += ch;
    ch = NextCharacter();
    while (isdigit(ch)) {
      buffer += ch;
      ch = NextCharacter();
    }
  }
  // we've gone one character ahead, so go back
  GoBack();

  return new Token(buffer, DIGIT, -1, pos);
}

Token *Lexer::ParseIdentifierOrKeyWord(
    char ch,
    Position &
        pos) { // parses the identifier or a keyword from the current position
  std::string buffer;
  // possibly it is an identifier
  while (isalnum(ch) || ch == '_' || ch == '$') {
    buffer += ch;
    ch = NextCharacter();
  }
  // again went a character ahead
  GoBack();
  // check for KeyWord
  if (buffer[0] != '_' || buffer[0] != '$') {
    for (int i = LET; i <= RET; i++)
      if (buffer[0] == TOKENS[i].value_[0] && buffer == TOKENS[i].value_)
        return new Token(buffer, i, 0, pos);
  }
  return new Token(buffer, IDENT, -1, pos);
}

// although not required because of no use
Token *Lexer::ParseStringLiteral(
    char ch, Position &pos) { // parses the string literal from the string
  std::string str = "";
  if (ch == '"') { // string surrounded by "
    ch = NextCharacter();
    while (ch != '"') {
      str += ch;
      ch = NextCharacter();
    }
  } else if (ch == '\'') { // string surrounded by '
    ch = NextCharacter();
    while (ch != '\'') {
      str += ch;
      ch = NextCharacter();
    }
  }
  return new Token(str, STRING, -1, pos);
}

char parsehex(char ch) {
  if (ch >= '0' && ch <= '9')
    return ch - '0';
  else if ((ch >= 'a' && ch <= 'f')) {
    return 10 + ch - 'a';
  } else if (ch >= 'A' && ch <= 'F') {
    return 10 + ch - 'A';
  }
  throw std::runtime_error("wrong hexadecimal digits");
}

char parseoct(char ch) {
  if (ch >= '0' && ch <= '8')
    return ch - '0';
  throw std::runtime_error("wrong octal digits");
}

char escape_code(std::string str) {
  if (str[0] != '\\')
    return str[0];
  if (str[1] == 'x') {
    char ret = 0;
    ret |= parsehex(str[2]);
    ret <<= 4;
    ret |= parsehex(str[3]);
    return ret;
  } else if (str[1] == 'n')
    return '\n';
  else if (str[1] == 'b')
    return '\b';
  else if (str[1] == 'r')
    return '\r';
  else if (str[1] == 'a')
    return '\a';
  else if (str[1] == 't')
    return '\t';
  else if (str[1] == '"')
    return '"';
  else if (str[1] == '\'')
    return '\'';
  else throw std::runtime_error("unknown escape code");
}

// this function should be used instead of above function
// when we found a token of " or ' that means we are about
// to parse the string from the current position
std::string Lexer::GetStringLiteral() { // returns all the string until it finds "

  // create a buffer
  std::string str = "";
  char ch = NextCharacter();
  while (ch != EOF && (ch != '"' && ch != '\'')) {
    if (ch == '\\') {
        // a possible escape code
        std::string tmp = "";
        tmp += ch;
        ch = NextCharacter();
        tmp += ch;
        if (ch == 'x') {
          ch = NextCharacter();
          tmp += ch;
          ch = NextCharacter();
          tmp += ch;
        }
        ch = escape_code(tmp);
    }
    str += ch; // fill the buffer
    ch = NextCharacter();
  }
  return str;
}

TokenType Lexer::OneCharacterSymbol(
    char ch) { // returns the type of token from the given symbol
  switch (ch) {
  case '(':
    return LPAR;
  case ')':
    return RPAR;
  case '{':
    return LBRACE;
  case '}':
    return RBRACE;
  case '[':
    return LSQB;
  case ']':
    return RSQB;
  case ':':
    return COLON;
  case ';':
    return SCOLON;
  case '"':
  case '\'':
    return STRING;
  case '.':
    return DOT;
  case ',':
    return COMMA;
  case '?':
    return CONDITION;
  case '+':
    return PLUS;
  case '-':
    return MINUS;
  case '/':
    return DIV;
  case '*':
    return MUL;
  case '%':
    return MOD;
  case '>':
    return GT;
  case '<':
    return LT;
  case '=':
    return ASSIGN;
  case '^':
    return XOR;
  case '|':
    return BOR;
  case '&':
    return BAND;
  case '!':
    return NOT;
  case '~':
    return BNOT;
  default:
    return INVALID;
  }
}

TokenType
Lexer::TwoCharacterSymbol(char ch1,
                   char ch2) { // returns the type of symbol of two characters
  switch (ch2) {
  case '=':
    switch (ch1) {
    case '+':
      return PLUSEQ;
    case '-':
      return MINUSEQ;
    case '*':
      return MULEQ;
    case '/':
      return DIVEQ;
    case '%':
      return MODEQ;
    case '^':
      return XOREQ;
    case '&':
      return BANDEQ;
    case '|':
      return BOREQ;
    case '>':
      return GTE;
    case '<':
      return LTE;
    case '=':
      return EQUAL;
    case '!':
      return NOTEQ;
    }
    return INVALID;
  case '|':
    if (ch1 == '|')
      return OR;
    return INVALID;
  case '&':
    if (ch1 == '&')
      return AND;
    return INVALID;
  case '+':
    if (ch1 == '+')
      return INC;
    return INVALID;
  case '-':
    if (ch1 == '-')
      return DEC;
    return INVALID;
  case '<':
    if (ch1 == '<')
      return SHL;
    return INVALID;
  case '>':
    if (ch1 == '>')
      return SHR;
  default:
    return INVALID;
  }
}

bool Lexer::IsFile() const { return file_; }
std::string Lexer::GetFileName() { return file_name_; }

TokenType Lexer::ThreeCharacterSymbol(
    char ch1, char ch2,
    char ch3) { // returns the type of symbol of three characters
  switch (ch3) {
  case '=':
    if (ch1 == '>' && ch2 == '>')
      return SHREQ;
    if (ch1 == '<' && ch2 == '<')
      return SHLEQ;
  default:
    return INVALID;
  }
}

void Lexer::PutBack(Token *tok) { // put in the buffer for one token lookahead
                           // required by parser
  buffer_.push_back(tok);
}

// move to next token
void Lexer::advance()
{
  tok_ = NextToken();
}

double Lexer::GetNumber()
{
  double result = 0.0;
  try {
    result = std::stod(tok_->GetValue());
  } catch (std::exception &e) {
    std::cerr << e.what() << std::endl;
  }

  return result;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: cdouthdl.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 08:23:19 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_PROPERTYHANDLER_CROSSEDOUTTYPES_HXX
#include <cdouthdl.hxx>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_AWT_FONTSTRIKEOUT_HPP
#include <com/sun/star/awt/FontStrikeout.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#ifndef _XMLOFF_XMLEMENT_HXX
#include "xmlelement.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::awt;
using namespace ::xmloff::token;

SvXMLEnumMapEntry pXML_CrossedoutType_Enum[] =
{
    { XML_NONE,                 FontStrikeout::NONE },
    { XML_SINGLE,   FontStrikeout::SINGLE },
    { XML_DOUBLE,               FontStrikeout::DOUBLE },
    { XML_SINGLE,    FontStrikeout::BOLD },
    { XML_SINGLE,    FontStrikeout::SLASH },
    { XML_SINGLE,    FontStrikeout::X },
    { XML_TOKEN_INVALID,                0 }
};

SvXMLEnumMapEntry pXML_CrossedoutStyle_Enum[] =
{
    { XML_NONE,                         FontStrikeout::NONE },
    { XML_SOLID,                        FontStrikeout::SINGLE },
    { XML_SOLID,                        FontStrikeout::DOUBLE },
    { XML_SOLID,                        FontStrikeout::BOLD },
    { XML_SOLID,                        FontStrikeout::SLASH },
    { XML_SOLID,                        FontStrikeout::X },
    { XML_DOTTED,               FontStrikeout::SINGLE },
    { XML_DASH,             FontStrikeout::SINGLE },
    { XML_LONG_DASH,            FontStrikeout::SINGLE },
    { XML_DOT_DASH,         FontStrikeout::SINGLE },
    { XML_DOT_DOT_DASH,     FontStrikeout::SINGLE },
    { XML_WAVE,             FontStrikeout::SINGLE },
    { XML_TOKEN_INVALID,                0 }
};

SvXMLEnumMapEntry pXML_CrossedoutWidth_Enum[] =
{
    { XML_AUTO,                 FontStrikeout::NONE },
    { XML_AUTO,                 FontStrikeout::SINGLE },
    { XML_AUTO,                 FontStrikeout::DOUBLE },
    { XML_BOLD,     FontStrikeout::BOLD },
    { XML_AUTO,                 FontStrikeout::SLASH },
    { XML_AUTO,                 FontStrikeout::X },
    { XML_THIN,                 FontStrikeout::NONE },
    { XML_MEDIUM,               FontStrikeout::NONE },
    { XML_THICK,                FontStrikeout::NONE },
    { XML_TOKEN_INVALID,                0 }
};

///////////////////////////////////////////////////////////////////////////////
//
// class XMLCrossedOutTypePropHdl
//

XMLCrossedOutTypePropHdl::~XMLCrossedOutTypePropHdl()
{
    // nothing to do
}

sal_Bool XMLCrossedOutTypePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_uInt16 eNewStrikeout;

    if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,
                                             pXML_CrossedoutType_Enum ) ) )
    {
        // multi property: style and width might be set already.
        // If the old value is NONE, the new is used unchanged.
        sal_Int16 eStrikeout;
        if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )
        {
            switch( eNewStrikeout )
            {
            case FontStrikeout::NONE:
            case FontStrikeout::SINGLE:
                // keep existing line style
                eNewStrikeout = eStrikeout;
                break;
            case FontStrikeout::DOUBLE:
                // A double line style has priority over a solid or a bold
                // line style,
                // but not about any other line style
                switch( eStrikeout )
                {
                case FontStrikeout::SINGLE:
                case FontStrikeout::BOLD:
                    break;
                default:
                    // If a double line style is not supported for the existing
                    // value, keep the new one
                    eNewStrikeout = eStrikeout;
                    break;
                }
                break;
            default:
                OSL_ENSURE( bRet, "unexpected line type value" );
                break;
            }
            if( eNewStrikeout != eStrikeout )
                rValue <<= (sal_Int16)eNewStrikeout;
        }
        else
        {
            rValue <<= (sal_Int16)eNewStrikeout;
        }
    }

    return bRet;
}

sal_Bool XMLCrossedOutTypePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_Int16 nValue;
    OUStringBuffer aOut;

    if( (rValue >>= nValue) && FontStrikeout::DOUBLE==nValue )
    {
        if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue, pXML_CrossedoutType_Enum ) ) )
            rStrExpValue = aOut.makeStringAndClear();
    }

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLCrossedOutStylePropHdl
//

XMLCrossedOutStylePropHdl::~XMLCrossedOutStylePropHdl()
{
    // nothing to do
}

sal_Bool XMLCrossedOutStylePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_uInt16 eNewStrikeout;

    if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,
                                             pXML_CrossedoutStyle_Enum ) ) )
    {
        // multi property: style and width might be set already.
        // If the old value is NONE, the new is used unchanged.
        sal_Int16 eStrikeout;
        if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )
        {
            // one NONE a SINGLE are possible new values. For both, the
            // existing value is kept.
        }
        else
        {
            rValue <<= (sal_Int16)eNewStrikeout;
        }
    }

    return bRet;
}

sal_Bool XMLCrossedOutStylePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_Int16 nValue;
    OUStringBuffer aOut;

    if( rValue >>= nValue )
    {
        if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue,
                                                 pXML_CrossedoutStyle_Enum ) ) )
            rStrExpValue = aOut.makeStringAndClear();
    }

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLCrossedOutWidthPropHdl
//

XMLCrossedOutWidthPropHdl::~XMLCrossedOutWidthPropHdl()
{
    // nothing to do
}

sal_Bool XMLCrossedOutWidthPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_uInt16 eNewStrikeout;

    if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,
                                             pXML_CrossedoutWidth_Enum ) ) )
    {
        // multi property: style and width might be set already.
        // If the old value is NONE, the new is used unchanged.
        sal_Int16 eStrikeout;
        if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )
        {
            switch( eNewStrikeout )
            {
            case FontStrikeout::NONE:
                // keep existing line style
                eNewStrikeout = eStrikeout;
                break;
            case FontStrikeout::BOLD:
                switch( eStrikeout )
                {
                case FontStrikeout::SINGLE:
                    break;
                default:
                    // If a double line style is not supported for the existing
                    // value, keep the new one
                    eNewStrikeout = eStrikeout;
                    break;
                }
            default:
                OSL_ENSURE( bRet, "unexpected line type value" );
                break;
            }
            if( eNewStrikeout != eStrikeout )
                rValue <<= (sal_Int16)eNewStrikeout;
        }
        else
        {
            rValue <<= (sal_Int16)eNewStrikeout;
        }
    }

    return bRet;
}

sal_Bool XMLCrossedOutWidthPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_Int16 nValue;
    OUStringBuffer aOut;

    if( (rValue >>= nValue) && (FontStrikeout::BOLD == nValue) )
    {
        if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue,
                                                 pXML_CrossedoutWidth_Enum ) ) )
            rStrExpValue = aOut.makeStringAndClear();
    }

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLCrossedOutTextPropHdl
//

XMLCrossedOutTextPropHdl::~XMLCrossedOutTextPropHdl()
{
    // nothing to do
}

sal_Bool XMLCrossedOutTextPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;

    if( rStrImpValue.getLength() )
    {
        sal_Int16 eStrikeout = ('/' == rStrImpValue[0]
                                        ? FontStrikeout::SLASH
                                        : FontStrikeout::X);
        rValue <<= (sal_Int16)eStrikeout;
        bRet = sal_True;
    }

    return bRet;
}

sal_Bool XMLCrossedOutTextPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_Int16 nValue;

    if( (rValue >>= nValue) &&
        (FontStrikeout::SLASH == nValue || FontStrikeout::X == nValue) )
    {
        rStrExpValue = OUString::valueOf(
            static_cast< sal_Unicode>( FontStrikeout::SLASH == nValue ? '/'
                                                                      : 'X' ) );
        bRet = sal_True;
    }

    return bRet;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.4.298); FILE MERGED 2005/09/05 14:39:22 rt 1.4.298.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cdouthdl.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:38:15 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLOFF_PROPERTYHANDLER_CROSSEDOUTTYPES_HXX
#include <cdouthdl.hxx>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_AWT_FONTSTRIKEOUT_HPP
#include <com/sun/star/awt/FontStrikeout.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#ifndef _XMLOFF_XMLEMENT_HXX
#include "xmlelement.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::awt;
using namespace ::xmloff::token;

SvXMLEnumMapEntry pXML_CrossedoutType_Enum[] =
{
    { XML_NONE,                 FontStrikeout::NONE },
    { XML_SINGLE,   FontStrikeout::SINGLE },
    { XML_DOUBLE,               FontStrikeout::DOUBLE },
    { XML_SINGLE,    FontStrikeout::BOLD },
    { XML_SINGLE,    FontStrikeout::SLASH },
    { XML_SINGLE,    FontStrikeout::X },
    { XML_TOKEN_INVALID,                0 }
};

SvXMLEnumMapEntry pXML_CrossedoutStyle_Enum[] =
{
    { XML_NONE,                         FontStrikeout::NONE },
    { XML_SOLID,                        FontStrikeout::SINGLE },
    { XML_SOLID,                        FontStrikeout::DOUBLE },
    { XML_SOLID,                        FontStrikeout::BOLD },
    { XML_SOLID,                        FontStrikeout::SLASH },
    { XML_SOLID,                        FontStrikeout::X },
    { XML_DOTTED,               FontStrikeout::SINGLE },
    { XML_DASH,             FontStrikeout::SINGLE },
    { XML_LONG_DASH,            FontStrikeout::SINGLE },
    { XML_DOT_DASH,         FontStrikeout::SINGLE },
    { XML_DOT_DOT_DASH,     FontStrikeout::SINGLE },
    { XML_WAVE,             FontStrikeout::SINGLE },
    { XML_TOKEN_INVALID,                0 }
};

SvXMLEnumMapEntry pXML_CrossedoutWidth_Enum[] =
{
    { XML_AUTO,                 FontStrikeout::NONE },
    { XML_AUTO,                 FontStrikeout::SINGLE },
    { XML_AUTO,                 FontStrikeout::DOUBLE },
    { XML_BOLD,     FontStrikeout::BOLD },
    { XML_AUTO,                 FontStrikeout::SLASH },
    { XML_AUTO,                 FontStrikeout::X },
    { XML_THIN,                 FontStrikeout::NONE },
    { XML_MEDIUM,               FontStrikeout::NONE },
    { XML_THICK,                FontStrikeout::NONE },
    { XML_TOKEN_INVALID,                0 }
};

///////////////////////////////////////////////////////////////////////////////
//
// class XMLCrossedOutTypePropHdl
//

XMLCrossedOutTypePropHdl::~XMLCrossedOutTypePropHdl()
{
    // nothing to do
}

sal_Bool XMLCrossedOutTypePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_uInt16 eNewStrikeout;

    if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,
                                             pXML_CrossedoutType_Enum ) ) )
    {
        // multi property: style and width might be set already.
        // If the old value is NONE, the new is used unchanged.
        sal_Int16 eStrikeout;
        if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )
        {
            switch( eNewStrikeout )
            {
            case FontStrikeout::NONE:
            case FontStrikeout::SINGLE:
                // keep existing line style
                eNewStrikeout = eStrikeout;
                break;
            case FontStrikeout::DOUBLE:
                // A double line style has priority over a solid or a bold
                // line style,
                // but not about any other line style
                switch( eStrikeout )
                {
                case FontStrikeout::SINGLE:
                case FontStrikeout::BOLD:
                    break;
                default:
                    // If a double line style is not supported for the existing
                    // value, keep the new one
                    eNewStrikeout = eStrikeout;
                    break;
                }
                break;
            default:
                OSL_ENSURE( bRet, "unexpected line type value" );
                break;
            }
            if( eNewStrikeout != eStrikeout )
                rValue <<= (sal_Int16)eNewStrikeout;
        }
        else
        {
            rValue <<= (sal_Int16)eNewStrikeout;
        }
    }

    return bRet;
}

sal_Bool XMLCrossedOutTypePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_Int16 nValue;
    OUStringBuffer aOut;

    if( (rValue >>= nValue) && FontStrikeout::DOUBLE==nValue )
    {
        if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue, pXML_CrossedoutType_Enum ) ) )
            rStrExpValue = aOut.makeStringAndClear();
    }

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLCrossedOutStylePropHdl
//

XMLCrossedOutStylePropHdl::~XMLCrossedOutStylePropHdl()
{
    // nothing to do
}

sal_Bool XMLCrossedOutStylePropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_uInt16 eNewStrikeout;

    if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,
                                             pXML_CrossedoutStyle_Enum ) ) )
    {
        // multi property: style and width might be set already.
        // If the old value is NONE, the new is used unchanged.
        sal_Int16 eStrikeout;
        if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )
        {
            // one NONE a SINGLE are possible new values. For both, the
            // existing value is kept.
        }
        else
        {
            rValue <<= (sal_Int16)eNewStrikeout;
        }
    }

    return bRet;
}

sal_Bool XMLCrossedOutStylePropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_Int16 nValue;
    OUStringBuffer aOut;

    if( rValue >>= nValue )
    {
        if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue,
                                                 pXML_CrossedoutStyle_Enum ) ) )
            rStrExpValue = aOut.makeStringAndClear();
    }

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLCrossedOutWidthPropHdl
//

XMLCrossedOutWidthPropHdl::~XMLCrossedOutWidthPropHdl()
{
    // nothing to do
}

sal_Bool XMLCrossedOutWidthPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_uInt16 eNewStrikeout;

    if( ( bRet = rUnitConverter.convertEnum( eNewStrikeout, rStrImpValue,
                                             pXML_CrossedoutWidth_Enum ) ) )
    {
        // multi property: style and width might be set already.
        // If the old value is NONE, the new is used unchanged.
        sal_Int16 eStrikeout;
        if( (rValue >>= eStrikeout) && FontStrikeout::NONE!=eStrikeout )
        {
            switch( eNewStrikeout )
            {
            case FontStrikeout::NONE:
                // keep existing line style
                eNewStrikeout = eStrikeout;
                break;
            case FontStrikeout::BOLD:
                switch( eStrikeout )
                {
                case FontStrikeout::SINGLE:
                    break;
                default:
                    // If a double line style is not supported for the existing
                    // value, keep the new one
                    eNewStrikeout = eStrikeout;
                    break;
                }
            default:
                OSL_ENSURE( bRet, "unexpected line type value" );
                break;
            }
            if( eNewStrikeout != eStrikeout )
                rValue <<= (sal_Int16)eNewStrikeout;
        }
        else
        {
            rValue <<= (sal_Int16)eNewStrikeout;
        }
    }

    return bRet;
}

sal_Bool XMLCrossedOutWidthPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_Int16 nValue;
    OUStringBuffer aOut;

    if( (rValue >>= nValue) && (FontStrikeout::BOLD == nValue) )
    {
        if( ( bRet = rUnitConverter.convertEnum( aOut, (sal_uInt16)nValue,
                                                 pXML_CrossedoutWidth_Enum ) ) )
            rStrExpValue = aOut.makeStringAndClear();
    }

    return bRet;
}

///////////////////////////////////////////////////////////////////////////////
//
// class XMLCrossedOutTextPropHdl
//

XMLCrossedOutTextPropHdl::~XMLCrossedOutTextPropHdl()
{
    // nothing to do
}

sal_Bool XMLCrossedOutTextPropHdl::importXML( const OUString& rStrImpValue, uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;

    if( rStrImpValue.getLength() )
    {
        sal_Int16 eStrikeout = ('/' == rStrImpValue[0]
                                        ? FontStrikeout::SLASH
                                        : FontStrikeout::X);
        rValue <<= (sal_Int16)eStrikeout;
        bRet = sal_True;
    }

    return bRet;
}

sal_Bool XMLCrossedOutTextPropHdl::exportXML( OUString& rStrExpValue, const uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool bRet = sal_False;
    sal_Int16 nValue;

    if( (rValue >>= nValue) &&
        (FontStrikeout::SLASH == nValue || FontStrikeout::X == nValue) )
    {
        rStrExpValue = OUString::valueOf(
            static_cast< sal_Unicode>( FontStrikeout::SLASH == nValue ? '/'
                                                                      : 'X' ) );
        bRet = sal_True;
    }

    return bRet;
}

<|endoftext|>


<commit_before>// Filename: collisionHandlerQueue.cxx
// Created by:  drose (16Mar02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////

#include "collisionHandlerQueue.h"
#include "config_collide.h"

TypeHandle CollisionHandlerQueue::_type_handle;

// This class is used in sort_entries(), below.
class CollisionEntrySorter {
public:
  CollisionEntrySorter(CollisionEntry *entry) {
    _entry = entry;
    LVector3f vec =
      entry->get_from_intersection_point() -
      entry->get_from()->get_collision_origin();
    _dist2 = vec.length_squared();
  }
  bool operator < (const CollisionEntrySorter &other) const {
    return _dist2 < other._dist2;
  }

  CollisionEntry *_entry;
  float _dist2;
};

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::Constructor
//       Access: Public
//  Description:
////////////////////////////////////////////////////////////////////
CollisionHandlerQueue::
CollisionHandlerQueue() {
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::begin_group
//       Access: Public, Virtual
//  Description: Will be called by the CollisionTraverser before a new
//               traversal is begun.  It instructs the handler to
//               reset itself in preparation for a number of
//               CollisionEntries to be sent.
////////////////////////////////////////////////////////////////////
void CollisionHandlerQueue::
begin_group() {
  _entries.clear();
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::add_entry
//       Access: Public, Virtual
//  Description: Called between a begin_group() .. end_group()
//               sequence for each collision that is detected.
////////////////////////////////////////////////////////////////////
void CollisionHandlerQueue::
add_entry(CollisionEntry *entry) {
  nassertv(entry != (CollisionEntry *)NULL);
  _entries.push_back(entry);
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::sort_entries
//       Access: Public
//  Description: Sorts all the detected collisions front-to-back by
//               from_intersection_point() so that those intersection
//               points closest to the collider's origin (e.g., the
//               center of the CollisionSphere, or the point_a of a
//               CollisionSegment) appear first.
////////////////////////////////////////////////////////////////////
void CollisionHandlerQueue::
sort_entries() {
  // Build up a temporary vector of entries so we can sort the
  // pointers.  This uses the class defined above.
  typedef pvector<CollisionEntrySorter> Sorter;
  Sorter sorter;
  sorter.reserve(_entries.size());

  Entries::const_iterator ei;
  for (ei = _entries.begin(); ei != _entries.end(); ++ei) {
    sorter.push_back(CollisionEntrySorter(*ei));
  }

  sort(sorter.begin(), sorter.end());
  nassertv(sorter.size() == _entries.size());

  // Now that they're sorted, get them back.  We do this in two steps,
  // building up a temporary vector first, so we don't accidentally
  // delete all the entries when the pointers go away.
  Entries sorted_entries;
  sorted_entries.reserve(sorter.size());
  Sorter::const_iterator si;
  for (si = sorter.begin(); si != sorter.end(); ++si) {
    sorted_entries.push_back((*si)._entry);
  }

  _entries.swap(sorted_entries);
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::clear_entries
//       Access: Public
//  Description: Removes all the entries from the queue.
////////////////////////////////////////////////////////////////////
void CollisionHandlerQueue::
clear_entries() {
  _entries.clear();
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::get_num_entries
//       Access: Public
//  Description: Returns the number of CollisionEntries detected last
//               pass.
////////////////////////////////////////////////////////////////////
int CollisionHandlerQueue::
get_num_entries() const {
  return _entries.size();
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::get_entry
//       Access: Public
//  Description: Returns the nth CollisionEntry detected last pass.
////////////////////////////////////////////////////////////////////
CollisionEntry *CollisionHandlerQueue::
get_entry(int n) const {
  nassertr(n >= 0 && n < (int)_entries.size(), NULL);
  return _entries[n];
}
<commit_msg>use new interface<commit_after>// Filename: collisionHandlerQueue.cxx
// Created by:  drose (16Mar02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////

#include "collisionHandlerQueue.h"
#include "config_collide.h"

TypeHandle CollisionHandlerQueue::_type_handle;

// This class is used in sort_entries(), below.
class CollisionEntrySorter {
public:
  CollisionEntrySorter(CollisionEntry *entry) {
    _entry = entry;
    LVector3f vec =
      entry->get_surface_point(entry->get_from_node_path()) -
      entry->get_from()->get_collision_origin();
    _dist2 = vec.length_squared();
  }
  bool operator < (const CollisionEntrySorter &other) const {
    return _dist2 < other._dist2;
  }

  CollisionEntry *_entry;
  float _dist2;
};

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::Constructor
//       Access: Public
//  Description:
////////////////////////////////////////////////////////////////////
CollisionHandlerQueue::
CollisionHandlerQueue() {
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::begin_group
//       Access: Public, Virtual
//  Description: Will be called by the CollisionTraverser before a new
//               traversal is begun.  It instructs the handler to
//               reset itself in preparation for a number of
//               CollisionEntries to be sent.
////////////////////////////////////////////////////////////////////
void CollisionHandlerQueue::
begin_group() {
  _entries.clear();
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::add_entry
//       Access: Public, Virtual
//  Description: Called between a begin_group() .. end_group()
//               sequence for each collision that is detected.
////////////////////////////////////////////////////////////////////
void CollisionHandlerQueue::
add_entry(CollisionEntry *entry) {
  nassertv(entry != (CollisionEntry *)NULL);
  _entries.push_back(entry);
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::sort_entries
//       Access: Public
//  Description: Sorts all the detected collisions front-to-back by
//               from_intersection_point() so that those intersection
//               points closest to the collider's origin (e.g., the
//               center of the CollisionSphere, or the point_a of a
//               CollisionSegment) appear first.
////////////////////////////////////////////////////////////////////
void CollisionHandlerQueue::
sort_entries() {
  // Build up a temporary vector of entries so we can sort the
  // pointers.  This uses the class defined above.
  typedef pvector<CollisionEntrySorter> Sorter;
  Sorter sorter;
  sorter.reserve(_entries.size());

  Entries::const_iterator ei;
  for (ei = _entries.begin(); ei != _entries.end(); ++ei) {
    sorter.push_back(CollisionEntrySorter(*ei));
  }

  sort(sorter.begin(), sorter.end());
  nassertv(sorter.size() == _entries.size());

  // Now that they're sorted, get them back.  We do this in two steps,
  // building up a temporary vector first, so we don't accidentally
  // delete all the entries when the pointers go away.
  Entries sorted_entries;
  sorted_entries.reserve(sorter.size());
  Sorter::const_iterator si;
  for (si = sorter.begin(); si != sorter.end(); ++si) {
    sorted_entries.push_back((*si)._entry);
  }

  _entries.swap(sorted_entries);
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::clear_entries
//       Access: Public
//  Description: Removes all the entries from the queue.
////////////////////////////////////////////////////////////////////
void CollisionHandlerQueue::
clear_entries() {
  _entries.clear();
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::get_num_entries
//       Access: Public
//  Description: Returns the number of CollisionEntries detected last
//               pass.
////////////////////////////////////////////////////////////////////
int CollisionHandlerQueue::
get_num_entries() const {
  return _entries.size();
}

////////////////////////////////////////////////////////////////////
//     Function: CollisionHandlerQueue::get_entry
//       Access: Public
//  Description: Returns the nth CollisionEntry detected last pass.
////////////////////////////////////////////////////////////////////
CollisionEntry *CollisionHandlerQueue::
get_entry(int n) const {
  nassertr(n >= 0 && n < (int)_entries.size(), NULL);
  return _entries[n];
}
<|endoftext|>


<commit_before><commit_msg>cppcheck: redundantAssignment<commit_after><|endoftext|>


<commit_before>#define DEFINE_GLOBALS
#include"all_defines.hpp"

#ifndef single_threaded
	bool single_threaded;
#endif

#include"symbols.hpp"

boost::scoped_ptr<SymbolsTable> symbols;
Symbol* symbol_sym;
Symbol* symbol_int;
Symbol* symbol_char;
Symbol* symbol_cons;
Symbol* symbol_pid;
Symbol* symbol_fn;
Symbol* symbol_string;
Symbol* symbol_unspecified;
Symbol* symbol_num;
Symbol* symbol_array;
Symbol* symbol_table;
Symbol* symbol_container;

void initialize_globals(void) {
	symbols.reset(new SymbolsTable());
	symbol_sym = symbols->lookup("<hl>sym");
	symbol_sym = symbols->lookup("<hl>int");
	symbol_sym = symbols->lookup("<hl>char");
	symbol_cons = symbols->lookup("<hl>cons");
	symbol_pid = symbols->lookup("<hl>pid");
	symbol_fn = symbols->lookup("<hl>fn");
	symbol_string = symbols->lookup("<hl>string");
	symbol_unspecified = symbols->lookup("<hl>unpsecified");
	symbol_num = symbols->lookup("<hl>num");
	symbol_array = symbols->lookup("<hl>array");
	symbol_table = symbols->lookup("<hl>table");
	symbol_container = symbols->lookup("<hl>container");
}

<commit_msg>src/globals.cpp: Some rearrangement of code<commit_after>#define DEFINE_GLOBALS
#include"all_defines.hpp"

#ifndef single_threaded
	bool single_threaded;
#endif

class Symbol;

Symbol* symbol_sym;
Symbol* symbol_int;
Symbol* symbol_char;
Symbol* symbol_cons;
Symbol* symbol_pid;
Symbol* symbol_fn;
Symbol* symbol_string;
Symbol* symbol_unspecified;
Symbol* symbol_num;
Symbol* symbol_array;
Symbol* symbol_table;
Symbol* symbol_container;

#include"symbols.hpp"

boost::scoped_ptr<SymbolsTable> symbols;

void initialize_globals(void) {
	symbols.reset(new SymbolsTable());
	symbol_sym = symbols->lookup("<hl>sym");
	symbol_sym = symbols->lookup("<hl>int");
	symbol_sym = symbols->lookup("<hl>char");
	symbol_cons = symbols->lookup("<hl>cons");
	symbol_pid = symbols->lookup("<hl>pid");
	symbol_fn = symbols->lookup("<hl>fn");
	symbol_string = symbols->lookup("<hl>string");
	symbol_unspecified = symbols->lookup("<hl>unpsecified");
	symbol_num = symbols->lookup("<hl>num");
	symbol_array = symbols->lookup("<hl>array");
	symbol_table = symbols->lookup("<hl>table");
	symbol_container = symbols->lookup("<hl>container");
}

<|endoftext|>


<commit_before>#include "adjacencyMatrix.h"
#include <vector>
using namespace std;

adjacencyMatrix::adjacencyMatrix()
{
/**
 * Constructor
 */
    max_id_=0;
}

bool adjacencyMatrix::Get(int id1, int id2){
/**
 * Gets the id of the edges connecting two nodes in the graph. Returns true if the edge exists, false otherwise.
 * \param[in]   id1 ID of the first node
 * \param[in]   id2 ID of the second node
 */
    int id1_s=max(id1,id2);
    int id2_s=min(id1,id2);
	int n=mat_.size();
	if( (id1_s>n-1) || (id2_s<0) ){
        return false;
	}else{
        int val=mat_.at(id1_s).at(id2_s);
        if (val==0){
            return false;
        } else {
            return true;
        }
	}
}

bool adjacencyMatrix::Get(int id1, int id2, int& ide){
/**
 * Gets the id of the edges connecting two nodes in the graph. Returns true if the edge exists, false otherwise.
 * \param[in]   id1 ID of the first node
 * \param[in]   id2 ID of the second node
 * \param[out]  ide edge ID, if it exists in the adjacency matrix
 */
    int id1_s=max(id1,id2);
    int id2_s=min(id1,id2);
	int n=mat_.size();
	if( (id1_s>n-1) || (id2_s<0) ){
        return false;
	}else{
        int val=mat_.at(id1_s).at(id2_s);
        if (val==0){
            return false;
        } else {
            if(id1>id2){
                ide=val;
            }else{
                ide=-val;
            }
            return true;
        }
	}
}

void resize(vector<vector<int> >& mat,int nNew){
/**
 * Enlarges the adjacency matrix.
 * \param[in,out] mat matrix to be enlarged
 * \param[in] New size of the matrix
 */
    int nOld=mat.size();
    int i;
    for(i=nOld;i<nNew;i++){
        vector<int> bottom(i,0);
        mat.push_back(bottom);
    }
}

int adjacencyMatrix::Set(int id1,int id2){
/**
 * Add new entry to the adjacency matrix and returns the edge ID. If the entry already exists, it returns the corresponding ID; otherwise, it increments the max ID and uses it.
 * If any of the imput argument is negative, it increments the max ID but returns 0.
 * \param[in] id1 ID of the first node
 * \param[in] id2 ID of the second node
 */
    int ide;
    if ( (id1<0) || (id2<0) ){ // Any negative input index
        max_id_++;
        ide=max_id_;
    } else {                    // Both positive
        if( !( Get(id1,id2,ide) ) ){    // If the entry already exists, it just gets the edge ID
            max_id_++;
            if(id1>id2){
                resize(mat_,id1+1);
                mat_.at(id1).at(id2)=max_id_;
            }else{
                resize(mat_,id2+1);
                mat_.at(id2).at(id1)=-max_id_;
            }
        ide=max_id_;
        }
    }
	return ide;
}

int adjacencyMatrix::size(){
/**
 * Gets the size of the adjacency matrix.
 */
    return mat_.size();
}

adjacencyMatrix::~adjacencyMatrix()
{
/**
 * Destructor
 */
}
<commit_msg>Allow self loops<commit_after>#include "adjacencyMatrix.h"
#include <vector>
using namespace std;

adjacencyMatrix::adjacencyMatrix()
{
/**
 * Constructor
 */
    max_id_=0;
}

bool adjacencyMatrix::Get(int id1, int id2){
/**
 * Gets the id of the edges connecting two nodes in the graph. Returns true if the edge exists, false otherwise.
 * \param[in]   id1 ID of the first node
 * \param[in]   id2 ID of the second node
 */
    	int id1_s=max(id1,id2);
	int id2_s=min(id1,id2);
	int n=mat_.size();
	if( (id1_s>n-1) || (id2_s<0) ){
        	return false;
	} else {
        	int val=mat_.at(id1_s).at(id2_s);
        	if (val==0){
            		return false;
        	} else {
            		return true;
        	}
	}
}

bool adjacencyMatrix::Get(int id1, int id2, int& ide){
/**
 * Gets the id of the edges connecting two nodes in the graph. Returns true if the edge exists, false otherwise.
 * \param[in]   id1 ID of the first node
 * \param[in]   id2 ID of the second node
 * \param[out]  ide edge ID, if it exists in the adjacency matrix
 */
	int id1_s=max(id1,id2);
	int id2_s=min(id1,id2);
	int n=mat_.size();
	if( (id1_s>n-1) || (id2_s<0) ){
        	return false;
	} else {
		int val=mat_.at(id1_s).at(id2_s);
		if (val==0){
			return false;
        	} else {
			if(id1>=id2){
				ide=val;
			}else{
				ide=-val;
			}
			return true;
		}
	}
}

void resize(vector<vector<int> >& mat,int nNew){
/**
 * Enlarges the adjacency matrix.
 * \param[in,out] mat matrix to be enlarged
 * \param[in] New size of the matrix
 */
    int nOld=mat.size();
    int i;
    for(i=nOld;i<nNew;i++){
        vector<int> bottom(i,0);
        mat.push_back(bottom);
    }
}

int adjacencyMatrix::Set(int id1,int id2){
/**
 * Add new entry to the adjacency matrix and returns the edge ID. If the entry already exists, it returns the corresponding ID; otherwise, it increments the max ID and uses it.
 * If any of the imput argument is negative, it increments the max ID but returns 0.
 * \param[in] id1 ID of the first node
 * \param[in] id2 ID of the second node
 */
	int ide;
	if ( (id1<0) || (id2<0) ){ // Any negative input index
		max_id_++;
		ide=max_id_;
	} else {                    // Both positive
		if( !( Get(id1,id2,ide) ) ){    // If the entry already exists, it just gets the edge ID
			max_id_++;
			if(id1>=id2){
				resize(mat_,id1+1);
				mat_.at(id1).at(id2)=max_id_;
			} else {
				resize(mat_,id2+1);
				mat_.at(id2).at(id1)=-max_id_;
			}
			ide=max_id_;
		}
	}
	return ide;
}

int adjacencyMatrix::size(){
/**
 * Gets the size of the adjacency matrix.
 */
    return mat_.size();
}

adjacencyMatrix::~adjacencyMatrix()
{
/**
 * Destructor
 */
}
<|endoftext|>


<commit_before>#include <iostream>

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc.hpp"

#include "cvui.h"

#define WINDOW_NAME		"CVUI Test"

int main(int argc, const char *argv[])
{
	cv::Mat aFrame = cv::Mat(800, 600, CV_8UC3);
	bool aChecked = false;
	int aCount = 0;

	cv::namedWindow(WINDOW_NAME);
	cvui::init(WINDOW_NAME);

	while (true) {
		// Fill the frame with a nice color
		aFrame = cv::Scalar(49, 52, 49);

		// Check if ESC key was pressed
		if (cv::waitKey(10) == 27) {
			break;
		}

		cvui::text(aFrame, 50, 30, "Hey there!", 0.4);

		if (cvui::button(aFrame, 50, 50, "Button")) {
			std::cout << "Button clicked!" << std::endl;
		}

		cvui::checkbox(aFrame, 50, 100, "Checkbox test", &aChecked);
		cvui::window(aFrame, 50, 150, 120, 100, "My Window");
		cvui::counter(aFrame, 50, 280, &aCount);

		cvui::update();

		// Show everything on the screen
		imshow(WINDOW_NAME, aFrame);
	}

	return 0;
}<commit_msg>Add a bit of comments<commit_after>/*
This is a demo application to showcase the UI components of cvui.

Copyright (c) 2016 Fernando Bevilacqua <dovyski@gmail.com>
Licensed under the MIT license.
*/

#include <iostream>

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc.hpp"

#include "cvui.h"

#define WINDOW_NAME		"CVUI Test"

int main(int argc, const char *argv[])
{
	cv::Mat frame = cv::Mat(250, 600, CV_8UC3);
	bool checked = false;
	bool checked2 = true;
	int count = 0;

	// Init a OpenCV window and tell cvui to use it.
	// If cv::namedWindow() is not used, mouse events will
	// not be captured by cvui.
	cv::namedWindow(WINDOW_NAME);
	cvui::init(WINDOW_NAME);

	while (true) {
		// Fill the frame with a nice color
		frame = cv::Scalar(49, 52, 49);

		// Check if ESC key was pressed
		if (cv::waitKey(10) == 27) {
			break;
		}

		// Show some pieces of text. You can also specify the size of the
		// text and its color (using hex 0xRRGGBB CSS-like style).
		cvui::text(frame, 50, 30, "Hey there!");
		cvui::text(frame, 200, 30, "Use hex 0xRRGGBB colors easily", 0.4, 0xff0000);

		// Buttons will return true if they were clicked, which makes
		// handling clicks a breeze.
		if (cvui::button(frame, 50, 50, "Button")) {
			std::cout << "Button clicked!" << std::endl;
		}

		// If you do not specify the button width/height, the size will be
		// automatically adjusted to properly house the label.
		cvui::button(frame, 200, 50, "Button with large label");
		// You can tell the width and height you want
		cvui::button(frame, 410, 50, 15, 15, "x");

		// Window components are useful to create HUDs and similars. At the
		// moment, there is no implementation to constraint content within a
		// a window.
		cvui::window(frame, 50, 100, 120, 100, "Window");

		// The counter component can be used to alter int variables. Use
		// the 4th parameter of the function to point it to the variable
		// to be changed.
		cvui::counter(frame, 200, 100, &count);

		// Checkboxes also accept a pointer to a variable that controls
		// the state of the checkbox (checked or not). cvui::checkbox() will
		// automatically update the value of the boolean after all
		// interactions, but you can also change it by yourself. Just
		// do "checked = true" somewhere and the checkbox will change
		// its appearance.
		cvui::checkbox(frame, 200, 150, "Checkbox", &checked);
		cvui::checkbox(frame, 200, 180, "A checked checkbox", &checked2);

		// This function must be called *AFTER* all UI components. It does
		// all the behind the scenes magic to handle mouse clicks, etc.
		cvui::update();

		// Show everything on the screen
		cv::imshow(WINDOW_NAME, frame);
	}

	return 0;
}<|endoftext|>


<commit_before>#include <string>

#include "AgentProtocol.h"
#include "NetworkManager.hh"
#include "IConnector.hh"
#include "TCPConnector.h"
#include "UDPConnector.hh"

const std::string AgentProtocol::TCP_KEY = "TCP";
const std::string AgentProtocol::UDP_KEY = "UDP";

AgentProtocol::AgentProtocol(Network::NetworkManager &networkAdapter)
    : AProtocol(networkAdapter)
{
    Network::IConnector *connector = new Network::TCPConnector();
    _networkAdapter.setConnector(AgentProtocol::TCP_KEY, connector);
    _networkAdapter.setConnector(AgentProtocol::UDP_KEY, new Network::UDPConnector());
}

AgentProtocol::~AgentProtocol()
{
}

void         AgentProtocol::setAgent(IAgent *agent, Slam &slam)
{
    this->registerCallback("SetGoalPosEvent", [agent](pcl::PointXYZ pos) {dynamic_cast<Agent *>(agent)->setGoalPos(pos);});
    this->registerCallback("SetPosEvent", [agent](pcl::PointXYZ pos) {agent->setPos(pos);});
    agent->registerCallback("SendPacketEvent", [this](IAgent * agent) {sendPacketEvent(agent);});
    agent->registerCallback("SendStatusEvent", [this](std::string const & status) {sendStatusEvent(status);});
    ///@todo: Register in the factory (process data)
    agent->registerCallback("SendCloudEvent", [this](pcl::PointCloud<pcl::PointXYZ> const & cloud) {sendCloudEvent(cloud);});
    slam.registerCallback("SendNewLandmarkEvent", [this](std::vector<Landmarks::Landmark *> &nl) {sendNewLandmarkEvent(nl);});
}

void        AgentProtocol::sendCloudEvent(pcl::PointCloud<pcl::PointXYZ> const &cloud)
{
    for (size_t i = 0; i < cloud.points.size (); ++i)
        std::cout << "    " << cloud.points[i].x
                  << " "    << cloud.points[i].y
                  << " "    << cloud.points[i].z << std::endl;

    _factory.processData(cloud);
    int i = 0;
    bool is_ready = true;
    std::string toSend = "";
    while (_factory.isFullChunkReady())
    {
        if (is_ready) {
            ++i;
            toSend  = _factory.getChunk();
        }
        is_ready = _networkAdapter.send(toSend, AgentProtocol::UDP_KEY);
        usleep(100);
    }
    std::cerr << "Send cloud event " << i << std::endl;

    Json::Value     reply;

    reply["data"]["exit"] = 0;
    reply["status"]["code"] = 0;
    reply["status"]["message"] = "ok";
    this->sendDataTcp(reply);
    exit(1);
}

void        AgentProtocol::sendNewLandmarkEvent(std::vector<Landmarks::Landmark *> &nl)
{
    _factory.processData(nl);
    while (_factory.isFullChunkReady())
    {
        std::string toSend = _factory.getChunk();
        _networkAdapter.send(toSend, AgentProtocol::UDP_KEY);
    }
}

void        AgentProtocol::sendDataTcp(Json::Value &root)
{
    _outPacket.clear();
    std::string buffer = root.toStyledString();
    // buffer.erase(std::remove_if(buffer.begin(),
    //                           buffer.end(),
    //                           [](char x){return std::isspace(x);}),
    //            buffer.end());
    _outPacket.append(buffer.c_str(), buffer.size());
    // std::cout << "data sent == " << buffer << std::endl;
    _networkAdapter.send(_outPacket, AgentProtocol::TCP_KEY);
    // std::cout << "in send data:: magic = " << (char)_outPacket.getPacketHeader().magic << " -- packetsize == " << _outPacket.getPacketHeader().packetSize << " -- version == " << _outPacket.getPacketHeader().version << " -- header size == " << _outPacket.getPacketHeader().headerSize << std::endl;
    _outPacket.clear();
}
/**
 * @brief Function called when a connector is connected to the server
 * @todo: Change the function to get in param the key of the connector (maybe)
 */
void        AgentProtocol::connectedEvent(IAgent *agent)
{
    // std::cout << "connected event " << std::endl;
    Json::Value     reply;

    reply["data"]["name"] = agent->name();
    reply["data"]["position"]["x"] = agent->getPos().x;
    reply["data"]["position"]["y"] = agent->getPos().y;
    reply["data"]["position"]["z"] = agent->getPos().z;
    reply["status"]["code"] = 0;
    reply["status"]["message"] = "ok";
    this->sendDataTcp(reply);
}

void        AgentProtocol::sendStatusEvent(std::string const &status)
{
    Json::Value     root;

    std::cout << "Send status event " << std::endl;
    root["status"]["code"] = 0;
    root["status"]["message"] = "ok";
    root["data"]["state"] = status;
    this->sendDataTcp(root);
}

void        AgentProtocol::sendPacketEvent(IAgent *agent)
{
    Json::Value     root;

    std::cout << "Send movement event " << std::endl;
    root["data"]["position"]["x"] = agent->getPos().x;
    root["data"]["position"]["y"] = agent->getPos().y;
    root["data"]["position"]["z"] = agent->getPos().z;
    root["data"]["battery"] = (agent->getBattery() * 100) / Agent::DEFAULTBATTERY;
    root["status"]["code"] = 0;
    root["status"]["message"] = "ok";
    this->sendDataTcp(root);
}

void PrintJSONValue( const Json::Value &val )
{
    if ( val.isString() ) {
        printf( "string(%s)", val.asString().c_str() );
    } else if ( val.isBool() ) {
        printf( "bool(%d)", val.asBool() );
    } else if ( val.isInt() ) {
        printf( "int(%d)", val.asInt() );
    } else if ( val.isUInt() ) {
        printf( "uint(%u)", val.asUInt() );
    } else if ( val.isDouble() ) {
        printf( "double(%f)", val.asDouble() );
    }
    else
    {
        printf( "unknown type=[%d]", val.type() );
    }
}

bool PrintJSONTree( const Json::Value &root, unsigned short depth /* = 0 */)
{
    depth += 1;
    printf( " {type=[%d], size=%d}", root.type(), root.size() );

    if ( root.size() > 0 ) {
        printf("\n");
        for ( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) {
            // Print depth.
            for ( int tab = 0 ; tab < depth; tab++) {
                printf("-");
            }
            printf(" subvalue(");
            PrintJSONValue(itr.key());
            printf(") -");
            PrintJSONTree( *itr, depth);
        }
        return true;
    } else {
        printf(" ");
        PrintJSONValue(root);
        printf( "\n" );
    }
    return true;
}

pcl::PointXYZ AgentProtocol::getPosFromJson(Json::Value const &root)
{
    return ((pcl::PointXYZ) {
        root.get("x", 0.0).asFloat(),
                 root.get("y", 0.0).asFloat(),
                 root.get("z", 0.0).asFloat()
    });
}

void        AgentProtocol::receivePacketEvent(Network::ComPacket *packet)      // only for test 4 now, will change
{
    Json::Reader        reader;
    Json::Value         root;
    std::string         serverReply((const char *)packet->data() + sizeof(Network::s_ComPacketHeader), packet->getPacketSize() - sizeof(Network::s_ComPacketHeader));

    std::cout << "received message from serveur " << serverReply << std::endl;
    if (reader.parse(serverReply, root, false) == true)
    {
        // std::cout << "received a data " << serverReply << std::endl;
        Json::Value data = root["data"];
        Json::Value status = root["status"];
        int status_code = status.get("code", 0).asInt();
        // std::cout << "Status code == " << status_code << std::endl;
        if (status_code == 0 && data.empty() == false)
        {
            // std::cout << "Data found == " << data << std::endl;
            for (Json::ValueIterator it = data.begin(); it != data.end(); ++it)
            {
                std::string command = it.memberName();
                pcl::PointXYZ pos;
                if (command == "order")
                {
                    pos = this->getPosFromJson(*it);
                    std::cout << "Order goal pos got == " << pos << std::endl;
                    this->dispatch("SetGoalPosEvent", pos);
                }
                else if (command == "position")
                {
                    pos = this->getPosFromJson(*it);
                    this->dispatch("SetPosEvent", pos);
                }
                else
                    std::cout << "Command not known: " << command << std::endl;
            }
        }
        else
        {
            if (status_code != 0)
                std::cerr << "Status error recieved: [" << status_code << "]: " << status.get("message", "").asString() << std::endl;
            // else
            //     std::cerr << "No data recieved but good status: " << status.get("message", "").asString() << std::endl;
        }
    }
    else
        std::cerr << "error while parsing order " << serverReply << ": " << reader.getFormatedErrorMessages() << std::endl;
}

void        AgentProtocol::disconnectEvent()
{

}
<commit_msg>Packaging: comment test lines in AgentProtocol<commit_after>#include <string>

#include "AgentProtocol.h"
#include "NetworkManager.hh"
#include "IConnector.hh"
#include "TCPConnector.h"
#include "UDPConnector.hh"

const std::string AgentProtocol::TCP_KEY = "TCP";
const std::string AgentProtocol::UDP_KEY = "UDP";

AgentProtocol::AgentProtocol(Network::NetworkManager &networkAdapter)
    : AProtocol(networkAdapter)
{
    Network::IConnector *connector = new Network::TCPConnector();
    _networkAdapter.setConnector(AgentProtocol::TCP_KEY, connector);
    _networkAdapter.setConnector(AgentProtocol::UDP_KEY, new Network::UDPConnector());
}

AgentProtocol::~AgentProtocol()
{
}

void         AgentProtocol::setAgent(IAgent *agent, Slam &slam)
{
    this->registerCallback("SetGoalPosEvent", [agent](pcl::PointXYZ pos) {dynamic_cast<Agent *>(agent)->setGoalPos(pos);});
    this->registerCallback("SetPosEvent", [agent](pcl::PointXYZ pos) {agent->setPos(pos);});
    agent->registerCallback("SendPacketEvent", [this](IAgent * agent) {sendPacketEvent(agent);});
    agent->registerCallback("SendStatusEvent", [this](std::string const & status) {sendStatusEvent(status);});
    ///@todo: Register in the factory (process data)
    agent->registerCallback("SendCloudEvent", [this](pcl::PointCloud<pcl::PointXYZ> const & cloud) {sendCloudEvent(cloud);});
    slam.registerCallback("SendNewLandmarkEvent", [this](std::vector<Landmarks::Landmark *> &nl) {sendNewLandmarkEvent(nl);});
}

void        AgentProtocol::sendCloudEvent(pcl::PointCloud<pcl::PointXYZ> const &cloud)
{
    // To decomment to see the cloud to be send
    // for (size_t i = 0; i < cloud.points.size (); ++i)
    //     std::cout << "    " << cloud.points[i].x
    //               << " "    << cloud.points[i].y
    //               << " "    << cloud.points[i].z << std::endl;

    _factory.processData(cloud);
    int i = 0;
    bool is_ready = true;
    std::string toSend = "";
    while (_factory.isFullChunkReady())
    {
        if (is_ready) {
            ++i;
            toSend  = _factory.getChunk();
        }
        is_ready = _networkAdapter.send(toSend, AgentProtocol::UDP_KEY);
        usleep(100);
    }
    std::cerr << "Send cloud event " << i << std::endl;

    //To uncomment if you want to send only one cloud
    // Json::Value     reply;

    // reply["data"]["exit"] = 0;
    // reply["status"]["code"] = 0;
    // reply["status"]["message"] = "ok";
    // this->sendDataTcp(reply);
    // exit(1);
}

void        AgentProtocol::sendNewLandmarkEvent(std::vector<Landmarks::Landmark *> &nl)
{
    _factory.processData(nl);
    while (_factory.isFullChunkReady())
    {
        std::string toSend = _factory.getChunk();
        _networkAdapter.send(toSend, AgentProtocol::UDP_KEY);
    }
}

void        AgentProtocol::sendDataTcp(Json::Value &root)
{
    _outPacket.clear();
    std::string buffer = root.toStyledString();
    // buffer.erase(std::remove_if(buffer.begin(),
    //                           buffer.end(),
    //                           [](char x){return std::isspace(x);}),
    //            buffer.end());
    _outPacket.append(buffer.c_str(), buffer.size());
    // std::cout << "data sent == " << buffer << std::endl;
    _networkAdapter.send(_outPacket, AgentProtocol::TCP_KEY);
    // std::cout << "in send data:: magic = " << (char)_outPacket.getPacketHeader().magic << " -- packetsize == " << _outPacket.getPacketHeader().packetSize << " -- version == " << _outPacket.getPacketHeader().version << " -- header size == " << _outPacket.getPacketHeader().headerSize << std::endl;
    _outPacket.clear();
}
/**
 * @brief Function called when a connector is connected to the server
 * @todo: Change the function to get in param the key of the connector (maybe)
 */
void        AgentProtocol::connectedEvent(IAgent *agent)
{
    // std::cout << "connected event " << std::endl;
    Json::Value     reply;

    reply["data"]["name"] = agent->name();
    reply["data"]["position"]["x"] = agent->getPos().x;
    reply["data"]["position"]["y"] = agent->getPos().y;
    reply["data"]["position"]["z"] = agent->getPos().z;
    reply["status"]["code"] = 0;
    reply["status"]["message"] = "ok";
    this->sendDataTcp(reply);
}

void        AgentProtocol::sendStatusEvent(std::string const &status)
{
    Json::Value     root;

    std::cout << "Send status event " << std::endl;
    root["status"]["code"] = 0;
    root["status"]["message"] = "ok";
    root["data"]["state"] = status;
    this->sendDataTcp(root);
}

void        AgentProtocol::sendPacketEvent(IAgent *agent)
{
    Json::Value     root;

    std::cout << "Send movement event " << std::endl;
    root["data"]["position"]["x"] = agent->getPos().x;
    root["data"]["position"]["y"] = agent->getPos().y;
    root["data"]["position"]["z"] = agent->getPos().z;
    root["data"]["battery"] = (agent->getBattery() * 100) / Agent::DEFAULTBATTERY;
    root["status"]["code"] = 0;
    root["status"]["message"] = "ok";
    this->sendDataTcp(root);
}

void PrintJSONValue( const Json::Value &val )
{
    if ( val.isString() ) {
        printf( "string(%s)", val.asString().c_str() );
    } else if ( val.isBool() ) {
        printf( "bool(%d)", val.asBool() );
    } else if ( val.isInt() ) {
        printf( "int(%d)", val.asInt() );
    } else if ( val.isUInt() ) {
        printf( "uint(%u)", val.asUInt() );
    } else if ( val.isDouble() ) {
        printf( "double(%f)", val.asDouble() );
    }
    else
    {
        printf( "unknown type=[%d]", val.type() );
    }
}

bool PrintJSONTree( const Json::Value &root, unsigned short depth /* = 0 */)
{
    depth += 1;
    printf( " {type=[%d], size=%d}", root.type(), root.size() );

    if ( root.size() > 0 ) {
        printf("\n");
        for ( Json::ValueIterator itr = root.begin() ; itr != root.end() ; itr++ ) {
            // Print depth.
            for ( int tab = 0 ; tab < depth; tab++) {
                printf("-");
            }
            printf(" subvalue(");
            PrintJSONValue(itr.key());
            printf(") -");
            PrintJSONTree( *itr, depth);
        }
        return true;
    } else {
        printf(" ");
        PrintJSONValue(root);
        printf( "\n" );
    }
    return true;
}

pcl::PointXYZ AgentProtocol::getPosFromJson(Json::Value const &root)
{
    return ((pcl::PointXYZ) {
        root.get("x", 0.0).asFloat(),
                 root.get("y", 0.0).asFloat(),
                 root.get("z", 0.0).asFloat()
    });
}

void        AgentProtocol::receivePacketEvent(Network::ComPacket *packet)      // only for test 4 now, will change
{
    Json::Reader        reader;
    Json::Value         root;
    std::string         serverReply((const char *)packet->data() + sizeof(Network::s_ComPacketHeader), packet->getPacketSize() - sizeof(Network::s_ComPacketHeader));

    std::cout << "received message from serveur " << serverReply << std::endl;
    if (reader.parse(serverReply, root, false) == true)
    {
        // std::cout << "received a data " << serverReply << std::endl;
        Json::Value data = root["data"];
        Json::Value status = root["status"];
        int status_code = status.get("code", 0).asInt();
        // std::cout << "Status code == " << status_code << std::endl;
        if (status_code == 0 && data.empty() == false)
        {
            // std::cout << "Data found == " << data << std::endl;
            for (Json::ValueIterator it = data.begin(); it != data.end(); ++it)
            {
                std::string command = it.memberName();
                pcl::PointXYZ pos;
                if (command == "order")
                {
                    pos = this->getPosFromJson(*it);
                    std::cout << "Order goal pos got == " << pos << std::endl;
                    this->dispatch("SetGoalPosEvent", pos);
                }
                else if (command == "position")
                {
                    pos = this->getPosFromJson(*it);
                    this->dispatch("SetPosEvent", pos);
                }
                else
                    std::cout << "Command not known: " << command << std::endl;
            }
        }
        else
        {
            if (status_code != 0)
                std::cerr << "Status error recieved: [" << status_code << "]: " << status.get("message", "").asString() << std::endl;
            // else
            //     std::cerr << "No data recieved but good status: " << status.get("message", "").asString() << std::endl;
        }
    }
    else
        std::cerr << "error while parsing order " << serverReply << ": " << reader.getFormatedErrorMessages() << std::endl;
}

void        AgentProtocol::disconnectEvent()
{

}
<|endoftext|>