<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// Provide BZFS with a list server connection

/* class header */
#include "ListServerConnection.h"

/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>

/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"

extern Address serverAddress;
extern PingPacket getTeamCounts();

ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
  // parse url
  std::string protocol, hostname, pathname;
  int port = 80;
  bool useDefault = false;

  // use default if it can't be parsed
  if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
    useDefault = true;

  // use default if wrong protocol or invalid port
  if ((protocol != "http") || (port < 1) || (port > 65535))
    useDefault = true;

  // use default if bad address
  Address address = Address::getHostAddress(hostname);
  if (address.isAny())
    useDefault = true;

  // parse default list server URL if we need to; assume default works
  if (useDefault) {
    BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
    DEBUG1("Provided list server URL (%s) is invalid.  Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
  }

  // add to list
  this->address	   = address;
  this->port	   = port;
  this->pathname   = pathname;
  this->hostname   = hostname;
  this->linkSocket = NotConnected;

  this->publicizeAddress     = publicizedAddress;
  this->publicizeDescription = publicizedTitle;
  this->publicizeServer	     = true;  //if this c'tor is called, it's safe to publicize

  // schedule initial ADD message
  queueMessage(ListServerLink::ADD);
}

ListServerLink::ListServerLink()
{
  // does not create a usable link, so checks should be placed
  // in  all public member functions to ensure that nothing tries
  // to happen if publicizeServer is false
  this->linkSocket = NotConnected;
  this->publicizeServer = false;
}

ListServerLink::~ListServerLink()
{
  // now tell the list server that we're going away.  this can
  // take some time but we don't want to wait too long.  we do
  // our own multiplexing loop and wait for a maximum of 3 seconds
  // total.

  // if we aren't supposed to be publicizing, skip the whole thing
  // and don't waste 3 seconds.
  if (!publicizeServer)
    return;

  queueMessage(ListServerLink::REMOVE);
  TimeKeeper start = TimeKeeper::getCurrent();
  do {
    // compute timeout
    float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
    if (waitTime <= 0.0f)
      break;
    if (!isConnected()) //queueMessage should have connected us
      break;
    // check for list server socket connection
    int fdMax = -1;
    fd_set write_set;
    fd_set read_set;
    FD_ZERO(&write_set);
    FD_ZERO(&read_set);
    if (phase == ListServerLink::CONNECTING)
      _FD_SET(linkSocket, &write_set);
    else
      _FD_SET(linkSocket, &read_set);
    fdMax = linkSocket;

    // wait for socket to connect or timeout
    struct timeval timeout;
    timeout.tv_sec = long(floorf(waitTime));
    timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
    int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
			0, &timeout);
    if (nfound == 0)
      // Time has gone, close and go
      break;
    // check for connection to list server
    if (FD_ISSET(linkSocket, &write_set))
      sendQueuedMessages();
    else if (FD_ISSET(linkSocket, &read_set))
      read();
  } while (true);

  // stop list server communication
  closeLink();
}

void ListServerLink::closeLink()
{
  if (isConnected()) {
    close(linkSocket);
    DEBUG4("Closing List Server\n");
    linkSocket = NotConnected;
  }
}

void ListServerLink::read()
{
  if (isConnected()) {
    char    buf[256];
    recv(linkSocket, buf, sizeof(buf), 0);
    closeLink();
    if (nextMessageType != ListServerLink::NONE)
      // There was a pending request arrived after we write:
      // we should redo all the stuff
      openLink();
  }
}

void ListServerLink::openLink()
{
  // start opening connection if not already doing so
  if (!isConnected()) {
    linkSocket = socket(AF_INET, SOCK_STREAM, 0);
    DEBUG4("Opening List Server\n");
    if (!isConnected()) {
      return;
    }

    // set to non-blocking for connect
    if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
      closeLink();
      return;
    }

    // Make our connection come from our serverAddress in case we have
    // multiple/masked IPs so the list server can verify us.
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr = serverAddress;

    // assign the address to the socket
    if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
      closeLink();
      return;
    }

    // connect.  this should fail with EINPROGRESS but check for
    // success just in case.
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port   = htons(port);
    addr.sin_addr   = address;
    if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
      if (getErrno() != EINPROGRESS) {
	nerror("connecting to list server");
	// try to lookup dns name again in case it moved
	this->address = Address::getHostAddress(this->hostname);
	closeLink();
      } else {
	phase = CONNECTING;
      }
    } else {
      // shouldn't arrive here. Just in case, clean
      closeLink();
    }
  }
}

void ListServerLink::queueMessage(MessageType type)
{
  // ignore if the server is not public
  if (!publicizeServer) return;

  // Open network connection only if closed
  if (!isConnected()) openLink();

  // record next message to send.
  nextMessageType = type;
}

void ListServerLink::sendQueuedMessages()
{
  if (!isConnected())
    return;

  if (nextMessageType == ListServerLink::ADD) {
    DEBUG3("Queuing ADD message to list server\n");
    addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));
    lastAddTime = TimeKeeper::getCurrent();
  } else if (nextMessageType == ListServerLink::REMOVE) {
    DEBUG3("Queuing REMOVE message to list server\n");
    removeMe(publicizeAddress);
  }
}

void ListServerLink::addMe(PingPacket pingInfo,
			   std::string publicizedAddress,
			   std::string publicizedTitle)
{
  std::string msg;

  // encode ping reply as ascii hex digits plus NULL
  char gameInfo[PingPacketHexPackedSize + 1];
  pingInfo.packHex(gameInfo);

  // send ADD message (must send blank line)
  msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n"
    "Host: %s\r\nCache-Control: no-cache\r\n\r\n",
    pathname.c_str(), publicizedAddress.c_str(),
    getServerVersion(), gameInfo,
    getAppVersion(),
    publicizedTitle.c_str(),
    hostname.c_str());
  sendMessage(msg);
}

void ListServerLink::removeMe(std::string publicizedAddress)
{
  std::string msg;
  // send REMOVE (must send blank line)
  msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
    "Host: %s\r\nCache-Control: no-cache\r\n\r\n",
    pathname.c_str(),
    publicizedAddress.c_str(),
    hostname.c_str());
  sendMessage(msg);
}

void ListServerLink::sendMessage(std::string message)
{
  const int bufsize = 4096;
  char msg[bufsize];
  strncpy(msg, message.c_str(), bufsize);
  msg[bufsize - 1] = 0;
  if (strlen(msg) > 0) {
    DEBUG3("%s\n", msg);
    if (send(linkSocket, msg, strlen(msg), 0) == -1) {
      perror("List server send failed");
      DEBUG3("Unable to send to the list server!\n");
      closeLink();
    } else {
      nextMessageType = ListServerLink::NONE;
      phase	   = ListServerLink::WRITTEN;
    }
  } else {
    closeLink();
  }
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>comments on next steps for authentication<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// Provide BZFS with a list server connection

/* class header */
#include "ListServerConnection.h"

/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>

/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"

extern Address serverAddress;
extern PingPacket getTeamCounts();

ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
  // parse url
  std::string protocol, hostname, pathname;
  int port = 80;
  bool useDefault = false;

  // use default if it can't be parsed
  if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
    useDefault = true;

  // use default if wrong protocol or invalid port
  if ((protocol != "http") || (port < 1) || (port > 65535))
    useDefault = true;

  // use default if bad address
  Address address = Address::getHostAddress(hostname);
  if (address.isAny())
    useDefault = true;

  // parse default list server URL if we need to; assume default works
  if (useDefault) {
    BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
    DEBUG1("Provided list server URL (%s) is invalid.  Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
  }

  // add to list
  this->address	   = address;
  this->port	   = port;
  this->pathname   = pathname;
  this->hostname   = hostname;
  this->linkSocket = NotConnected;

  this->publicizeAddress     = publicizedAddress;
  this->publicizeDescription = publicizedTitle;
  this->publicizeServer	     = true;  //if this c'tor is called, it's safe to publicize

  // schedule initial ADD message
  queueMessage(ListServerLink::ADD);
}

ListServerLink::ListServerLink()
{
  // does not create a usable link, so checks should be placed
  // in  all public member functions to ensure that nothing tries
  // to happen if publicizeServer is false
  this->linkSocket = NotConnected;
  this->publicizeServer = false;
}

ListServerLink::~ListServerLink()
{
  // now tell the list server that we're going away.  this can
  // take some time but we don't want to wait too long.  we do
  // our own multiplexing loop and wait for a maximum of 3 seconds
  // total.

  // if we aren't supposed to be publicizing, skip the whole thing
  // and don't waste 3 seconds.
  if (!publicizeServer)
    return;

  queueMessage(ListServerLink::REMOVE);
  TimeKeeper start = TimeKeeper::getCurrent();
  do {
    // compute timeout
    float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
    if (waitTime <= 0.0f)
      break;
    if (!isConnected()) //queueMessage should have connected us
      break;
    // check for list server socket connection
    int fdMax = -1;
    fd_set write_set;
    fd_set read_set;
    FD_ZERO(&write_set);
    FD_ZERO(&read_set);
    if (phase == ListServerLink::CONNECTING)
      _FD_SET(linkSocket, &write_set);
    else
      _FD_SET(linkSocket, &read_set);
    fdMax = linkSocket;

    // wait for socket to connect or timeout
    struct timeval timeout;
    timeout.tv_sec = long(floorf(waitTime));
    timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
    int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
			0, &timeout);
    if (nfound == 0)
      // Time has gone, close and go
      break;
    // check for connection to list server
    if (FD_ISSET(linkSocket, &write_set))
      sendQueuedMessages();
    else if (FD_ISSET(linkSocket, &read_set))
      read();
  } while (true);

  // stop list server communication
  closeLink();
}

void ListServerLink::closeLink()
{
  if (isConnected()) {
    close(linkSocket);
    DEBUG4("Closing List Server\n");
    linkSocket = NotConnected;
  }
}

void ListServerLink::read()
{
  if (isConnected()) {
    char    buf[256];
    recv(linkSocket, buf, sizeof(buf), 0);
    closeLink();
    if (nextMessageType != ListServerLink::NONE)
      // There was a pending request arrived after we write:
      // we should redo all the stuff
      openLink();
  }
}

void ListServerLink::openLink()
{
  // start opening connection if not already doing so
  if (!isConnected()) {
    linkSocket = socket(AF_INET, SOCK_STREAM, 0);
    DEBUG4("Opening List Server\n");
    if (!isConnected()) {
      return;
    }

    // set to non-blocking for connect
    if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
      closeLink();
      return;
    }

    // Make our connection come from our serverAddress in case we have
    // multiple/masked IPs so the list server can verify us.
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr = serverAddress;

    // assign the address to the socket
    if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
      closeLink();
      return;
    }

    // connect.  this should fail with EINPROGRESS but check for
    // success just in case.
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port   = htons(port);
    addr.sin_addr   = address;
    if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
      if (getErrno() != EINPROGRESS) {
	nerror("connecting to list server");
	// try to lookup dns name again in case it moved
	this->address = Address::getHostAddress(this->hostname);
	closeLink();
      } else {
	phase = CONNECTING;
      }
    } else {
      // shouldn't arrive here. Just in case, clean
      closeLink();
    }
  }
}

void ListServerLink::queueMessage(MessageType type)
{
  // ignore if the server is not public
  if (!publicizeServer) return;

  // Open network connection only if closed
  if (!isConnected()) openLink();

  // record next message to send.
  nextMessageType = type;
}

void ListServerLink::sendQueuedMessages()
{
  if (!isConnected())
    return;

  if (nextMessageType == ListServerLink::ADD) {
    DEBUG3("Queuing ADD message to list server\n");
    addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));
    lastAddTime = TimeKeeper::getCurrent();
  } else if (nextMessageType == ListServerLink::REMOVE) {
    DEBUG3("Queuing REMOVE message to list server\n");
    removeMe(publicizeAddress);
  }
}

void ListServerLink::addMe(PingPacket pingInfo,
			   std::string publicizedAddress,
			   std::string publicizedTitle)
{
  std::string msg;

  // encode ping reply as ascii hex digits plus NULL
  char gameInfo[PingPacketHexPackedSize + 1];
  pingInfo.packHex(gameInfo);

  // TODO loop through and send any player tokens that need approval
  // TODO loop through groups we are interested and request those too
  // TODO we probably should convert to a POST instead. List server now allows either
  // send ADD message (must send blank line)
  msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n"
    "Host: %s\r\nCache-Control: no-cache\r\n\r\n",
    pathname.c_str(), publicizedAddress.c_str(),
    getServerVersion(), gameInfo,
    getAppVersion(),
    publicizedTitle.c_str(),
    hostname.c_str());
  // TODO need to listen for user info replies and setup callsign for isAllowedToEnter()
  sendMessage(msg);
}

void ListServerLink::removeMe(std::string publicizedAddress)
{
  std::string msg;
  // send REMOVE (must send blank line)
  msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
    "Host: %s\r\nCache-Control: no-cache\r\n\r\n",
    pathname.c_str(),
    publicizedAddress.c_str(),
    hostname.c_str());
  sendMessage(msg);
}

void ListServerLink::sendMessage(std::string message)
{
  const int bufsize = 4096;
  char msg[bufsize];
  strncpy(msg, message.c_str(), bufsize);
  msg[bufsize - 1] = 0;
  if (strlen(msg) > 0) {
    DEBUG3("%s\n", msg);
    if (send(linkSocket, msg, strlen(msg), 0) == -1) {
      perror("List server send failed");
      DEBUG3("Unable to send to the list server!\n");
      closeLink();
    } else {
      nextMessageType = ListServerLink::NONE;
      phase	   = ListServerLink::WRITTEN;
    }
  } else {
    closeLink();
  }
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2003-2006 Funambol
 *
 * 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 2 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 "base/fscapi.h"
#include "base/Log.h"
#include "base/util/XMLProcessor.h"
#include "syncml/formatter/Formatter.h"
#include "spds/EmailData.h"

#define EMAIL_READ  T("read")
#define EMAIL_FORW  T("forwarded")
#define EMAIL_REPL  T("replied")
#define EMAIL_TREC  T("received")
#define EMAIL_TCRE  T("created")
#define EMAIL_TMOD  T("modified")
#define EMAIL_DELE  T("deleted")
#define EMAIL_FLAG  T("flagged")
#define EMAIL_ITEM  T("emailitem")

static inline bool checkFlag(const char *xml, const char *field)
{
    size_t start = 0, end = 0;
    bool ret = false;

    if( XMLProcessor::getEscapedElementContent(xml, field, NULL, &start, &end) ) {
        ret = ( bstrncmp(xml+start, T("true"), end-start) == 0 ) ;
    }
    return ret;
}

EmailData::EmailData()
{
    read = false;
    forwarded = false;
    replied = false;
    deleted = false;
    flagged = false;
}

int EmailData::parse(const BCHAR *msg, size_t len)
{
    int ret = 0;
    size_t start, end;

    // Get attributes
    read      = checkFlag(msg, EMAIL_READ);
    forwarded = checkFlag(msg, EMAIL_FORW);
    replied   = checkFlag(msg, EMAIL_REPL);
    deleted   = checkFlag(msg, EMAIL_DELE);
    flagged   = checkFlag(msg, EMAIL_FLAG);

    if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TREC, NULL, &start, &end) ) {
        received = StringBuffer(msg+start, end-start);
    }
    else received = T("");

    if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TCRE, NULL, &start, &end) ) {
        created = StringBuffer(msg+start, end-start);
    }
    else created = T("");

    if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TMOD, NULL, &start, &end) ) {
        modified = StringBuffer(msg+start, end-start);
    }
    else modified = T("");

    // Get content
    if( XMLProcessor::getEscapedElementContent (msg, EMAIL_ITEM, NULL, &start, &end) ) {
		StringBuffer item(msg+start, end-start);

        if(XMLProcessor::getEscapedElementContent(item, T("CDATA"), NULL, &start, &end) == 0) {
            LOG.error(T("EMailData: can't find inner CDATA section."));
            return -1;
        }
        ret=emailItem.parse( item.c_str()+start, end-start );
    }
    else {
        LOG.info(T("EMailData: no <emailitem> tag."));
        // It is not an error, just log it for info.
    }
    return ret;
}

BCHAR *EmailData::format() {
    StringBuffer out;

    out.reserve(150);

    out = T("<![CDATA[\n<Email>\n");
    out += XMLProcessor::makeElement(EMAIL_READ, read);
    out += XMLProcessor::makeElement(EMAIL_FORW, forwarded);
    out += XMLProcessor::makeElement(EMAIL_REPL, replied);
    out += XMLProcessor::makeElement(EMAIL_TREC, received);
    out += XMLProcessor::makeElement(EMAIL_TCRE, created);
    out += XMLProcessor::makeElement(EMAIL_TMOD, modified);
    out += XMLProcessor::makeElement(EMAIL_DELE, deleted);
    out += XMLProcessor::makeElement(EMAIL_FLAG, flagged);
    out += T("<emailitem>\n<![CDATA[");
    BCHAR *item = emailItem.format();
    if ( item ) {
        out += item;
        delete [] item;
    }
    out += T("]]>\n</emailitem>\n</Email>\n]]>\n");
    return stringdup(out.c_str());
}

<commit_msg>Parsing of qp encoded emailitem<commit_after>/**
 * Copyright (C) 2003-2006 Funambol
 *
 * 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 2 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 "base/fscapi.h"
#include "base/Log.h"
#include "base/util/XMLProcessor.h"
#include "base/quoted-printable.h"
#include "syncml/formatter/Formatter.h"
#include "spds/EmailData.h"

#define EMAIL_READ  T("read")
#define EMAIL_FORW  T("forwarded")
#define EMAIL_REPL  T("replied")
#define EMAIL_TREC  T("received")
#define EMAIL_TCRE  T("created")
#define EMAIL_TMOD  T("modified")
#define EMAIL_DELE  T("deleted")
#define EMAIL_FLAG  T("flagged")
#define EMAIL_ITEM  T("emailitem")

static inline bool checkFlag(const char *xml, const char *field)
{
    size_t start = 0, end = 0;
    bool ret = false;

    if( XMLProcessor::getEscapedElementContent(xml, field, NULL, &start, &end) ) {
        ret = ( bstrncmp(xml+start, T("true"), end-start) == 0 ) ;
    }
    return ret;
}

EmailData::EmailData()
{
    read = false;
    forwarded = false;
    replied = false;
    deleted = false;
    flagged = false;
}

int EmailData::parse(const BCHAR *msg, size_t len)
{
    int ret = 0;
    size_t start, end;

    // Get attributes
    read      = checkFlag(msg, EMAIL_READ);
    forwarded = checkFlag(msg, EMAIL_FORW);
    replied   = checkFlag(msg, EMAIL_REPL);
    deleted   = checkFlag(msg, EMAIL_DELE);
    flagged   = checkFlag(msg, EMAIL_FLAG);

    if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TREC, NULL, &start, &end) ) {
        received = StringBuffer(msg+start, end-start);
    }
    else received = T("");

    if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TCRE, NULL, &start, &end) ) {
        created = StringBuffer(msg+start, end-start);
    }
    else created = T("");

    if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TMOD, NULL, &start, &end) ) {
        modified = StringBuffer(msg+start, end-start);
    }
    else modified = T("");

    // Get content
    if( XMLProcessor::getEscapedElementContent(msg, EMAIL_ITEM, NULL, &start, &end) ) {
		StringBuffer item(msg+start, end-start);
        item.replaceAll("<", "<");
        item.replaceAll(">", ">");

        unsigned int startAttr=0, endAttr=0;
        size_t itemlen = end-start;

        if(XMLProcessor::getElementAttributes(msg, EMAIL_ITEM, &startAttr, &endAttr, true)){
            if(bstrstr(msg+startAttr, "quoted-printable")) {
                char *decoded = qp_decode(item);
                item = decoded;
                delete [] decoded;
            }
        }
        // item must start with CDATA
        size_t item_start = item.find("![CDATA");
        if(item_start > 10){
            LOG.error(T("EMailData: can't find inner CDATA section."));
            return -1;
        }
        size_t item_end = item.rfind("]]>");
        // If not found, try also the old case
        if(item.length() - item_end > 10){
            item_end = item.rfind("]]&gt;");
            if(item.length() - item_end > 10){
                LOG.error(T("EMailData: can't find CDATA end tag."));
                return -1;
            }
        }
        // okay, move the start pointer to the end of
        item_start += bstrlen("![CDATA");

        ret=emailItem.parse( item.c_str()+item_start, item_end - item_start );

    }
    else {
        LOG.info(T("EMailData: no <emailitem> tag."));
        // It is not an error, just log it for info.
    }
    return ret;
}

BCHAR *EmailData::format() {
    StringBuffer out;

    out.reserve(150);

    out = T("<![CDATA[\n<Email>\n");
    out += XMLProcessor::makeElement(EMAIL_READ, read);
    out += XMLProcessor::makeElement(EMAIL_FORW, forwarded);
    out += XMLProcessor::makeElement(EMAIL_REPL, replied);
    out += XMLProcessor::makeElement(EMAIL_TREC, received);
    out += XMLProcessor::makeElement(EMAIL_TCRE, created);
    out += XMLProcessor::makeElement(EMAIL_TMOD, modified);
    out += XMLProcessor::makeElement(EMAIL_DELE, deleted);
    out += XMLProcessor::makeElement(EMAIL_FLAG, flagged);
    out += T("<emailitem>\n<![CDATA[");
    BCHAR *item = emailItem.format();
    if ( item ) {
        out += item;
        delete [] item;
    }
    out += T("]]>\n</emailitem>\n</Email>\n]]>\n");
    return stringdup(out.c_str());
}

<|endoftext|>


<commit_before>#ifndef MECHANICROTSHAFT_HPP_INCLUDED
#define MECHANICROTSHAFT_HPP_INCLUDED

#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"

//!
//! @file MechanicRotShaft.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Thu 28 Jun 2012 09:14:24
//! @brief Rotational shaft with torsional spring
//! @ingroup MechanicComponents
//!
//This component is generated by COMPGEN for HOPSAN-NG simulation
//from
/*{, C:, Documents and Settings, petkr14, My Documents, \
CompgenNG}/Mechanic1DNG.nb*/

using namespace hopsan;

class MechanicRotShaft : public ComponentC
{
private:
     double mKs;
     double malpha;
     Port *mpPmr1;
     Port *mpPmr2;
     int mNstep;
     //Port Pmr1 variable
     double tormr1;
     double thetamr1;
     double wmr1;
     double cmr1;
     double Zcmr1;
     double eqInertiamr1;
     //Port Pmr2 variable
     double tormr2;
     double thetamr2;
     double wmr2;
     double cmr2;
     double Zcmr2;
     double eqInertiamr2;
     //inputVariables
     //outputVariables
     //LocalExpressions variables
     double cmr10;
     double cmr20;
     //Expressions variables
     double cmr1f;
     double cmr2f;
     //Port Pmr1 pointer
     double *mpND_tormr1;
     double *mpND_thetamr1;
     double *mpND_wmr1;
     double *mpND_cmr1;
     double *mpND_Zcmr1;
     double *mpND_eqInertiamr1;
     //Port Pmr2 pointer
     double *mpND_tormr2;
     double *mpND_thetamr2;
     double *mpND_wmr2;
     double *mpND_cmr2;
     double *mpND_Zcmr2;
     double *mpND_eqInertiamr2;
     //Delay declarations
     //inputVariables pointers
     //outputVariables pointers
     EquationSystemSolver *mpSolver;

public:
     static Component *Creator()
     {
        return new MechanicRotShaft();
     }

     void configure()
     {
        const double Ks = 1000.;
        const double alpha = 0.9;

        mNstep=9;
        mKs = Ks;
        malpha = alpha;

        //Add ports to the component
        mpPmr1=addPowerPort("Pmr1","NodeMechanicRotational");
        mpPmr2=addPowerPort("Pmr2","NodeMechanicRotational");

        //Add inputVariables ports to the component

        //Add outputVariables ports to the component

        //Register changable parameters to the HOPSAN++ core
        registerParameter("Ks", "Spring constant", "Nm/rad", mKs);
        registerParameter("alpha", "damping factor", "", malpha);
     }

    void initialize()
     {
        //Read port variable pointers from nodes
        //Port Pmr1
        mpND_tormr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::Torque);
        mpND_thetamr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::Angle);
        mpND_wmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::AngularVelocity);
        mpND_cmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::WaveVariable);
        mpND_Zcmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::CharImpedance);
        mpND_eqInertiamr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::EquivalentInertia);
        //Port Pmr2
        mpND_tormr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::Torque);
        mpND_thetamr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::Angle);
        mpND_wmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::AngularVelocity);
        mpND_cmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::WaveVariable);
        mpND_Zcmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::CharImpedance);
        mpND_eqInertiamr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::EquivalentInertia);
        //Read inputVariables pointers from nodes
        //Read outputVariable pointers from nodes

        //Read variables from nodes
        //Port Pmr1
        tormr1 = (*mpND_tormr1);
        thetamr1 = (*mpND_thetamr1);
        wmr1 = (*mpND_wmr1);
        cmr1 = (*mpND_cmr1);
        Zcmr1 = (*mpND_Zcmr1);
        eqInertiamr1 = (*mpND_eqInertiamr1);
        //Port Pmr2
        tormr2 = (*mpND_tormr2);
        thetamr2 = (*mpND_thetamr2);
        wmr2 = (*mpND_wmr2);
        cmr2 = (*mpND_cmr2);
        Zcmr2 = (*mpND_Zcmr2);
        eqInertiamr2 = (*mpND_eqInertiamr2);

        //Read inputVariables from nodes

        //Read outputVariables from nodes

        //InitialExpressions
        cmr1 = tormr1 - (mKs*mTimestep*wmr1)/(1 - malpha);
        cmr2 = tormr2 - (mKs*mTimestep*wmr2)/(1 - malpha);
        cmr1f = tormr1;
        cmr2f = tormr2;

        //LocalExpressions
        cmr10 = cmr2 + (2*mKs*mTimestep*wmr2)/(1 - malpha);
        cmr20 = cmr1 + (2*mKs*mTimestep*wmr1)/(1 - malpha);

        //Initialize delays

     }
    void simulateOneTimestep()
     {
        //Read variables from nodes
        //Port Pmr1
        tormr1 = (*mpND_tormr1);
        thetamr1 = (*mpND_thetamr1);
        wmr1 = (*mpND_wmr1);
        eqInertiamr1 = (*mpND_eqInertiamr1);
        //Port Pmr2
        tormr2 = (*mpND_tormr2);
        thetamr2 = (*mpND_thetamr2);
        wmr2 = (*mpND_wmr2);
        eqInertiamr2 = (*mpND_eqInertiamr2);

        //Read inputVariables from nodes

        //LocalExpressions
        cmr10 = cmr2 + (2*mKs*mTimestep*wmr2)/(1 - malpha);
        cmr20 = cmr1 + (2*mKs*mTimestep*wmr1)/(1 - malpha);

          //Expressions
          cmr1 = cmr1f;
          cmr2 = cmr2f;
          cmr1f = cmr10*(1 - malpha) + cmr1f*malpha;
          cmr2f = cmr20*(1 - malpha) + cmr2f*malpha;
          Zcmr1 = (mKs*mTimestep)/(1 - malpha);
          Zcmr2 = (mKs*mTimestep)/(1 - malpha);

        //Calculate the delayed parts

        //Write new values to nodes
        //Port Pmr1
        (*mpND_cmr1)=cmr1;
        (*mpND_Zcmr1)=Zcmr1;
        //Port Pmr2
        (*mpND_cmr2)=cmr2;
        (*mpND_Zcmr2)=Zcmr2;
        //outputVariables

        //Update the delayed variabels

     }
};
#endif // MECHANICROTSHAFT_HPP_INCLUDED
<commit_msg>revised parameters<commit_after>#ifndef MECHANICROTSHAFT_HPP_INCLUDED
#define MECHANICROTSHAFT_HPP_INCLUDED

#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"

//!
//! @file MechanicRotShaft.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Tue 30 Apr 2013 14:45:54
//! @brief Rotational shaft with torsional spring
//! @ingroup MechanicComponents
//!
//==This code has been autogenerated using Compgen==
//from
/*{, C:, HopsanTrunk, HOPSAN++, CompgenModels}/Mechanic1dComponents.nb*/

using namespace hopsan;

class MechanicRotShaft : public ComponentC
{
private:
     double Ks;
     double alpha;
     Port *mpPmr1;
     Port *mpPmr2;
     int mNstep;
     //Port Pmr1 variable
     double tormr1;
     double thetamr1;
     double wmr1;
     double cmr1;
     double Zcmr1;
     double eqInertiamr1;
     //Port Pmr2 variable
     double tormr2;
     double thetamr2;
     double wmr2;
     double cmr2;
     double Zcmr2;
     double eqInertiamr2;
//==This code has been autogenerated using Compgen==
     //inputVariables
     //outputVariables
     //InitialExpressions variables
     double cmr1f;
     double cmr2f;
     //LocalExpressions variables
     double cmr10;
     double cmr20;
     //Expressions variables
     //Port Pmr1 pointer
     double *mpND_tormr1;
     double *mpND_thetamr1;
     double *mpND_wmr1;
     double *mpND_cmr1;
     double *mpND_Zcmr1;
     double *mpND_eqInertiamr1;
     //Port Pmr2 pointer
     double *mpND_tormr2;
     double *mpND_thetamr2;
     double *mpND_wmr2;
     double *mpND_cmr2;
     double *mpND_Zcmr2;
     double *mpND_eqInertiamr2;
     //Delay declarations
//==This code has been autogenerated using Compgen==
     //inputVariables pointers
     //outputVariables pointers
     EquationSystemSolver *mpSolver;

public:
     static Component *Creator()
     {
        return new MechanicRotShaft();
     }

     void configure()
     {
//==This code has been autogenerated using Compgen==

        mNstep=9;

        //Add ports to the component
        mpPmr1=addPowerPort("Pmr1","NodeMechanicRotational");
        mpPmr2=addPowerPort("Pmr2","NodeMechanicRotational");
        //Add inputVariables to the component

        //Add outputVariables to the component

//==This code has been autogenerated using Compgen==
        //Add constants/parameters
            addConstant("Ks", "Spring constant", "Nm/rad", 1000.,Ks);
            addConstant("alpha", "damping factor", "", 0.9,alpha);
     }

    void initialize()
     {
        //Read port variable pointers from nodes
        //Port Pmr1
        mpND_tormr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::Torque);
        mpND_thetamr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::Angle);
        mpND_wmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::AngularVelocity);
        mpND_cmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::WaveVariable);
        mpND_Zcmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::CharImpedance);
        mpND_eqInertiamr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::EquivalentInertia);
        //Port Pmr2
        mpND_tormr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::Torque);
        mpND_thetamr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::Angle);
        mpND_wmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::AngularVelocity);
        mpND_cmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::WaveVariable);
        mpND_Zcmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::CharImpedance);
        mpND_eqInertiamr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::EquivalentInertia);

        //Read variables from nodes
        //Port Pmr1
        tormr1 = (*mpND_tormr1);
        thetamr1 = (*mpND_thetamr1);
        wmr1 = (*mpND_wmr1);
        cmr1 = (*mpND_cmr1);
        Zcmr1 = (*mpND_Zcmr1);
        eqInertiamr1 = (*mpND_eqInertiamr1);
        //Port Pmr2
        tormr2 = (*mpND_tormr2);
        thetamr2 = (*mpND_thetamr2);
        wmr2 = (*mpND_wmr2);
        cmr2 = (*mpND_cmr2);
        Zcmr2 = (*mpND_Zcmr2);
        eqInertiamr2 = (*mpND_eqInertiamr2);

        //Read inputVariables from nodes

        //Read outputVariables from nodes

//==This code has been autogenerated using Compgen==
        //InitialExpressions
        cmr1 = tormr1 - (Ks*mTimestep*wmr1)/(1 - alpha);
        cmr2 = tormr2 - (Ks*mTimestep*wmr2)/(1 - alpha);
        cmr1f = tormr1;
        cmr2f = tormr2;

        //LocalExpressions
        cmr10 = cmr2 + (2*Ks*mTimestep*wmr2)/(1 - alpha);
        cmr20 = cmr1 + (2*Ks*mTimestep*wmr1)/(1 - alpha);

        //Initialize delays

     }
    void simulateOneTimestep()
     {
        //Read variables from nodes
        //Port Pmr1
        tormr1 = (*mpND_tormr1);
        thetamr1 = (*mpND_thetamr1);
        wmr1 = (*mpND_wmr1);
        eqInertiamr1 = (*mpND_eqInertiamr1);
        //Port Pmr2
        tormr2 = (*mpND_tormr2);
        thetamr2 = (*mpND_thetamr2);
        wmr2 = (*mpND_wmr2);
        eqInertiamr2 = (*mpND_eqInertiamr2);

        //Read inputVariables from nodes

        //LocalExpressions
        cmr10 = cmr2 + (2*Ks*mTimestep*wmr2)/(1 - alpha);
        cmr20 = cmr1 + (2*Ks*mTimestep*wmr1)/(1 - alpha);

          //Expressions
          cmr1 = cmr1f;
          cmr2 = cmr2f;
          cmr1f = (1 - alpha)*cmr10 + alpha*cmr1f;
          cmr2f = (1 - alpha)*cmr20 + alpha*cmr2f;
          Zcmr1 = (Ks*mTimestep)/(1 - alpha);
          Zcmr2 = (Ks*mTimestep)/(1 - alpha);

        //Calculate the delayed parts

        //Write new values to nodes
        //Port Pmr1
        (*mpND_cmr1)=cmr1;
        (*mpND_Zcmr1)=Zcmr1;
        //Port Pmr2
        (*mpND_cmr2)=cmr2;
        (*mpND_Zcmr2)=Zcmr2;
        //outputVariables

        //Update the delayed variabels

     }
    void deconfigure()
    {
        delete mpSolver;
    }
};
#endif // MECHANICROTSHAFT_HPP_INCLUDED
<|endoftext|>


<commit_before>// Barst.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "cpl defs.h"
#include "named pipes.h"
#include "Log buffer.h"
#include "mem pool.h"
#include "ftdi device.h"
#include "rtv device.h"
#include "serial device.h"
#include "mcdaq_device.h"
#include "misc tools.h"

CMainManager::CMainManager() : CDevice(_T("Main"))
{
	m_pcComm= NULL;
	m_pcMemPool= new CMemPool;		// main program buffer pool
	m_hClose= CreateEvent(NULL, TRUE, FALSE, NULL);
	m_bError= false;
	if (!m_hClose)
		m_bError= true;
}

// when shutting down, first the pipe is disconnected.
CMainManager::~CMainManager()
{
	if (m_pcComm)
		m_pcComm->Close();
	for (size_t i= 0; i<m_acManagers.size(); ++i)
		delete m_acManagers[i];
	CloseHandle(m_hClose);
	delete m_pcComm;
	delete m_pcMemPool;
}

// only one thread ever calls this since there's only thread in this communicator
void CMainManager::ProcessData(const void *pHead, DWORD dwSize, __int64 llId)
{
	if (m_bError)
		return;
	SData sData;
	sData.pDevice= this;
	sData.dwSize= sizeof(SBaseIn);
	SBaseIn sBase;
	memset(&sBase, 0, sizeof(SBaseIn));
	sBase.dwSize= sizeof(SBaseIn);
	sBase.nChan= -1;
	bool bRes= true;

	if (!pHead || dwSize < sizeof(SBaseIn) || dwSize != ((SBaseIn*)pHead)->dwSize)	// incorrect size read
	{
		sBase.nError= SIZE_MISSMATCH;
	} else if (((SBaseIn*)pHead)->eType == eVersion && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn) &&
		((SBaseIn*)pHead)->nChan == -1)	// send lib version
	{
		sBase.dwInfo= BARST_VERSION;
		sBase.eType= eVersion;
	} else if (((SBaseIn*)pHead)->eType == eDelete && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn))	// close manager
	{
		if (((SBaseIn*)pHead)->nChan == -1)	// close main program
			SetEvent(m_hClose);
		else if (((SBaseIn*)pHead)->nChan >= 0 && ((SBaseIn*)pHead)->nChan < m_acManagers.size() &&
			m_acManagers[((SBaseIn*)pHead)->nChan])	// close other manager
		{
			delete m_acManagers[((SBaseIn*)pHead)->nChan];
			m_acManagers[((SBaseIn*)pHead)->nChan]= NULL;
		}
		else
			sBase.nError= INVALID_CHANN;
		sBase.nChan= ((SBaseIn*)pHead)->nChan;
		sBase.eType= eDelete;
	} else if (((SBaseIn*)pHead)->eType == eSet && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn))	// add a manager
	{
		// prepare array element for manager
		size_t t= 0;
		for (; t < m_acManagers.size() && m_acManagers[t]; ++t);
		if (t == m_acManagers.size())
			m_acManagers.push_back(NULL);
		sBase.eType= eSet;
		switch (((SBaseIn*)pHead)->eType2)	// the device to open
		{
		case eFTDIMan:
		{
			int nPos= -1;
			for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
				if (m_acManagers[i] && _tcscmp(FTDI_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
					nPos= (int)i;
			if (nPos != -1)	// found
			{
				sBase.nError= ALREADY_OPEN;
				sBase.nChan= nPos;
				break;
			}
			CManagerFTDI* pMan= new CManagerFTDI(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
			if (!sBase.nError)
			{
				sBase.nChan= (int)t;
				m_acManagers[t]= pMan;
			} else
				delete pMan;
			break;
		}
		case eRTVMan:
		{
			int nPos= -1;
			for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
				if (m_acManagers[i] && _tcscmp(RTV_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
					nPos= (int)i;
			if (nPos != -1)	// found
			{
				sBase.nError= ALREADY_OPEN;
				sBase.nChan= nPos;
				break;
			}
			CManagerRTV* pMan= new CManagerRTV(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
			if (!sBase.nError)
			{
				sBase.nChan= (int)t;
				m_acManagers[t]= pMan;
			} else
				delete pMan;
			break;
		}
		case eSerialMan:
		{
			int nPos= -1;
			for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
				if (m_acManagers[i] && _tcscmp(SERIAL_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
					nPos= (int)i;
			if (nPos != -1)	// found
			{
				sBase.nError= ALREADY_OPEN;
				sBase.nChan= nPos;
				break;
			}
			CManagerSerial* pMan= new CManagerSerial(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
			if (!sBase.nError)
			{
				sBase.nChan= (int)t;
				m_acManagers[t]= pMan;
			} else
				delete pMan;
			break;
		}
		case eMCDAQMan:
		{
			int nPos= -1;
			for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
				if (m_acManagers[i] && _tcscmp(MCDAQ_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
					nPos= (int)i;
			if (nPos != -1)	// found
			{
				sBase.nError= ALREADY_OPEN;
				sBase.nChan= nPos;
				break;
			}
			CManagerMCDAQ* pMan= new CManagerMCDAQ(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
			if (!sBase.nError)
			{
				sBase.nChan= (int)t;
				m_acManagers[t]= pMan;
			} else
				delete pMan;
			break;
		}
		default:
			sBase.nError= INVALID_MAN;
			break;
		}
	} else if (((SBaseIn*)pHead)->nChan == -1 && ((SBaseIn*)pHead)->eType == eQuery)
	{
		sData.dwSize = sizeof(SBaseIn) + sizeof(SBase) + sizeof(SPerfTime);
		void *pHead = sData.pHead = m_pcMemPool->PoolAcquire(sData.dwSize);
		if (pHead)
		{
			((SBaseIn*)pHead)->dwSize= sizeof(SBaseIn) + sizeof(SBase) + sizeof(SPerfTime);
			((SBaseIn*)pHead)->eType= eQuery;
			((SBaseIn*)pHead)->nChan= -1;
			((SBaseIn*)pHead)->nError= 0;
			pHead = (char*)pHead + sizeof(SBaseIn);

			((SBase *)pHead)->dwSize = sizeof(SPerfTime) + sizeof(SBase);
			((SBase *)pHead)->eType = eServerTime;
			pHead= (char *)pHead + sizeof(SBase);

			FILETIME sTime;
			ULARGE_INTEGER ulTime;
			((SPerfTime *)pHead)->dRelativeTime = g_cTimer.Seconds();
			GetSystemTimeAsFileTime(&sTime);
			ulTime.HighPart = sTime.dwHighDateTime;
			ulTime.LowPart = sTime.dwLowDateTime;
			((SPerfTime *)pHead)->dUTCTime = ulTime.QuadPart / 10000000.0;
			m_pcComm->SendData(&sData, llId);
		}
	} else if (((SBaseIn*)pHead)->nChan < 0 || ((SBaseIn*)pHead)->nChan >= m_acManagers.size() ||
		!m_acManagers[((SBaseIn*)pHead)->nChan])	// verify manager exists
	{
		sBase.nError= INVALID_CHANN;
		sBase.eType= ((SBaseIn*)pHead)->eType;
	} else if (((SBaseIn*)pHead)->eType == eQuery && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn))	// send info on this manager
	{
		bRes= false;
		DWORD dwResSize= m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(NULL, 0);	// size of response
		sData.pHead= m_pcMemPool->PoolAcquire(dwResSize);
		if (sData.pHead)
		{
			m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(sData.pHead, dwResSize);	// get response
			sData.dwSize= dwResSize;
			m_pcComm->SendData(&sData, llId);
		}
	} else if (((SBaseIn*)pHead)->eType == ePassOn)	// pass following data to manager
	{
		bRes= false;
		m_acManagers[((SBaseIn*)pHead)->nChan]->ProcessData((char*)pHead + sizeof(SBaseIn), dwSize-sizeof(SBaseIn), llId);
	} else
		sBase.nError= INVALID_COMMAND;

	if (bRes)	// respond
	{
		sData.pHead= m_pcMemPool->PoolAcquire(sData.dwSize);
		if (sData.pHead)
		{
			memcpy(sData.pHead, &sBase, sizeof(SBaseIn));
			m_pcComm->SendData(&sData, llId);
		}
	}
}

int CMainManager::Run(int argc, TCHAR* argv[])
{
	if (argc != 4 && argc != 5)
		return BAD_INPUT_PARAMS;
	DWORD dwBuffSizeIn, dwBuffSizeOut;	// size of pipe buffers
	std::tstringstream in(argv[2]), out(argv[3]);
	g_llMaxQueueBytes = -1;
	if (argc == 5)
	{
		std::tstringstream ssMaxBytes(argv[4]);
		ssMaxBytes >> g_llMaxQueueBytes;	// queue limit, -1 means
	}
	in >> dwBuffSizeIn;		// user writing to pipe size
	out >> dwBuffSizeOut;	// user reading from pipe
	m_csPipe= argv[1];		// pipe name to use

	if (in.fail() || out.fail() || _tcschr(argv[2],  _T('-'))
		|| _tcschr(argv[3],  _T('-')))	// cannot be negative #
		return BAD_INPUT_PARAMS;
	// check if it exists already
	HANDLE hPipe= CreateFile(argv[1], GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (hPipe != INVALID_HANDLE_VALUE || GetLastError() == ERROR_PIPE_BUSY)
		return ALREADY_OPEN;
	CloseHandle(hPipe);
	m_pcComm= new CPipeServer();	// main program pipe
	int nRes;
	// only use one thread to ensure thread safety
	if (nRes= static_cast<CPipeServer*>(m_pcComm)->Init(argv[1], 1, dwBuffSizeIn, dwBuffSizeOut, this, NULL))
		return nRes;
	if (WAIT_OBJECT_0 != WaitForSingleObject(m_hClose, INFINITE))	// wait here until closing
		return WIN_ERROR(GetLastError(), nRes);
	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	InitializeQueueLimit();
	g_cTimer.ResetTimer();
	ShowWindow(GetConsoleWindow(), SW_HIDE);
	CMainManager* pMainManager= new CMainManager;
	int nRes= pMainManager->Run(argc, argv);	// program sits here until stopped
	delete pMainManager;
	return nRes;
}

// WM_COPYDATA http://www.cplusplus.com/forum/windows/23232/
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms633573%28v=vs.85%29.aspx
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms632593%28v=vs.85%29.aspx
<commit_msg>Don't hide window in debug mode.<commit_after>// Barst.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "cpl defs.h"
#include "named pipes.h"
#include "Log buffer.h"
#include "mem pool.h"
#include "ftdi device.h"
#include "rtv device.h"
#include "serial device.h"
#include "mcdaq_device.h"
#include "misc tools.h"

CMainManager::CMainManager() : CDevice(_T("Main"))
{
	m_pcComm= NULL;
	m_pcMemPool= new CMemPool;		// main program buffer pool
	m_hClose= CreateEvent(NULL, TRUE, FALSE, NULL);
	m_bError= false;
	if (!m_hClose)
		m_bError= true;
}

// when shutting down, first the pipe is disconnected.
CMainManager::~CMainManager()
{
	if (m_pcComm)
		m_pcComm->Close();
	for (size_t i= 0; i<m_acManagers.size(); ++i)
		delete m_acManagers[i];
	CloseHandle(m_hClose);
	delete m_pcComm;
	delete m_pcMemPool;
}

// only one thread ever calls this since there's only thread in this communicator
void CMainManager::ProcessData(const void *pHead, DWORD dwSize, __int64 llId)
{
	if (m_bError)
		return;
	SData sData;
	sData.pDevice= this;
	sData.dwSize= sizeof(SBaseIn);
	SBaseIn sBase;
	memset(&sBase, 0, sizeof(SBaseIn));
	sBase.dwSize= sizeof(SBaseIn);
	sBase.nChan= -1;
	bool bRes= true;

	if (!pHead || dwSize < sizeof(SBaseIn) || dwSize != ((SBaseIn*)pHead)->dwSize)	// incorrect size read
	{
		sBase.nError= SIZE_MISSMATCH;
	} else if (((SBaseIn*)pHead)->eType == eVersion && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn) &&
		((SBaseIn*)pHead)->nChan == -1)	// send lib version
	{
		sBase.dwInfo= BARST_VERSION;
		sBase.eType= eVersion;
	} else if (((SBaseIn*)pHead)->eType == eDelete && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn))	// close manager
	{
		if (((SBaseIn*)pHead)->nChan == -1)	// close main program
			SetEvent(m_hClose);
		else if (((SBaseIn*)pHead)->nChan >= 0 && ((SBaseIn*)pHead)->nChan < m_acManagers.size() &&
			m_acManagers[((SBaseIn*)pHead)->nChan])	// close other manager
		{
			delete m_acManagers[((SBaseIn*)pHead)->nChan];
			m_acManagers[((SBaseIn*)pHead)->nChan]= NULL;
		}
		else
			sBase.nError= INVALID_CHANN;
		sBase.nChan= ((SBaseIn*)pHead)->nChan;
		sBase.eType= eDelete;
	} else if (((SBaseIn*)pHead)->eType == eSet && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn))	// add a manager
	{
		// prepare array element for manager
		size_t t= 0;
		for (; t < m_acManagers.size() && m_acManagers[t]; ++t);
		if (t == m_acManagers.size())
			m_acManagers.push_back(NULL);
		sBase.eType= eSet;
		switch (((SBaseIn*)pHead)->eType2)	// the device to open
		{
		case eFTDIMan:
		{
			int nPos= -1;
			for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
				if (m_acManagers[i] && _tcscmp(FTDI_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
					nPos= (int)i;
			if (nPos != -1)	// found
			{
				sBase.nError= ALREADY_OPEN;
				sBase.nChan= nPos;
				break;
			}
			CManagerFTDI* pMan= new CManagerFTDI(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
			if (!sBase.nError)
			{
				sBase.nChan= (int)t;
				m_acManagers[t]= pMan;
			} else
				delete pMan;
			break;
		}
		case eRTVMan:
		{
			int nPos= -1;
			for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
				if (m_acManagers[i] && _tcscmp(RTV_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
					nPos= (int)i;
			if (nPos != -1)	// found
			{
				sBase.nError= ALREADY_OPEN;
				sBase.nChan= nPos;
				break;
			}
			CManagerRTV* pMan= new CManagerRTV(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
			if (!sBase.nError)
			{
				sBase.nChan= (int)t;
				m_acManagers[t]= pMan;
			} else
				delete pMan;
			break;
		}
		case eSerialMan:
		{
			int nPos= -1;
			for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
				if (m_acManagers[i] && _tcscmp(SERIAL_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
					nPos= (int)i;
			if (nPos != -1)	// found
			{
				sBase.nError= ALREADY_OPEN;
				sBase.nChan= nPos;
				break;
			}
			CManagerSerial* pMan= new CManagerSerial(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
			if (!sBase.nError)
			{
				sBase.nChan= (int)t;
				m_acManagers[t]= pMan;
			} else
				delete pMan;
			break;
		}
		case eMCDAQMan:
		{
			int nPos= -1;
			for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
				if (m_acManagers[i] && _tcscmp(MCDAQ_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
					nPos= (int)i;
			if (nPos != -1)	// found
			{
				sBase.nError= ALREADY_OPEN;
				sBase.nChan= nPos;
				break;
			}
			CManagerMCDAQ* pMan= new CManagerMCDAQ(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
			if (!sBase.nError)
			{
				sBase.nChan= (int)t;
				m_acManagers[t]= pMan;
			} else
				delete pMan;
			break;
		}
		default:
			sBase.nError= INVALID_MAN;
			break;
		}
	} else if (((SBaseIn*)pHead)->nChan == -1 && ((SBaseIn*)pHead)->eType == eQuery)
	{
		sData.dwSize = sizeof(SBaseIn) + sizeof(SBase) + sizeof(SPerfTime);
		void *pHead = sData.pHead = m_pcMemPool->PoolAcquire(sData.dwSize);
		if (pHead)
		{
			((SBaseIn*)pHead)->dwSize= sizeof(SBaseIn) + sizeof(SBase) + sizeof(SPerfTime);
			((SBaseIn*)pHead)->eType= eQuery;
			((SBaseIn*)pHead)->nChan= -1;
			((SBaseIn*)pHead)->nError= 0;
			pHead = (char*)pHead + sizeof(SBaseIn);

			((SBase *)pHead)->dwSize = sizeof(SPerfTime) + sizeof(SBase);
			((SBase *)pHead)->eType = eServerTime;
			pHead= (char *)pHead + sizeof(SBase);

			FILETIME sTime;
			ULARGE_INTEGER ulTime;
			((SPerfTime *)pHead)->dRelativeTime = g_cTimer.Seconds();
			GetSystemTimeAsFileTime(&sTime);
			ulTime.HighPart = sTime.dwHighDateTime;
			ulTime.LowPart = sTime.dwLowDateTime;
			((SPerfTime *)pHead)->dUTCTime = ulTime.QuadPart / 10000000.0;
			m_pcComm->SendData(&sData, llId);
		}
	} else if (((SBaseIn*)pHead)->nChan < 0 || ((SBaseIn*)pHead)->nChan >= m_acManagers.size() ||
		!m_acManagers[((SBaseIn*)pHead)->nChan])	// verify manager exists
	{
		sBase.nError= INVALID_CHANN;
		sBase.eType= ((SBaseIn*)pHead)->eType;
	} else if (((SBaseIn*)pHead)->eType == eQuery && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn))	// send info on this manager
	{
		bRes= false;
		DWORD dwResSize= m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(NULL, 0);	// size of response
		sData.pHead= m_pcMemPool->PoolAcquire(dwResSize);
		if (sData.pHead)
		{
			m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(sData.pHead, dwResSize);	// get response
			sData.dwSize= dwResSize;
			m_pcComm->SendData(&sData, llId);
		}
	} else if (((SBaseIn*)pHead)->eType == ePassOn)	// pass following data to manager
	{
		bRes= false;
		m_acManagers[((SBaseIn*)pHead)->nChan]->ProcessData((char*)pHead + sizeof(SBaseIn), dwSize-sizeof(SBaseIn), llId);
	} else
		sBase.nError= INVALID_COMMAND;

	if (bRes)	// respond
	{
		sData.pHead= m_pcMemPool->PoolAcquire(sData.dwSize);
		if (sData.pHead)
		{
			memcpy(sData.pHead, &sBase, sizeof(SBaseIn));
			m_pcComm->SendData(&sData, llId);
		}
	}
}

int CMainManager::Run(int argc, TCHAR* argv[])
{
	if (argc != 4 && argc != 5)
		return BAD_INPUT_PARAMS;
	DWORD dwBuffSizeIn, dwBuffSizeOut;	// size of pipe buffers
	std::tstringstream in(argv[2]), out(argv[3]);
	g_llMaxQueueBytes = -1;
	if (argc == 5)
	{
		std::tstringstream ssMaxBytes(argv[4]);
		ssMaxBytes >> g_llMaxQueueBytes;	// queue limit, -1 means
	}
	in >> dwBuffSizeIn;		// user writing to pipe size
	out >> dwBuffSizeOut;	// user reading from pipe
	m_csPipe= argv[1];		// pipe name to use

	if (in.fail() || out.fail() || _tcschr(argv[2],  _T('-'))
		|| _tcschr(argv[3],  _T('-')))	// cannot be negative #
		return BAD_INPUT_PARAMS;
	// check if it exists already
	HANDLE hPipe= CreateFile(argv[1], GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (hPipe != INVALID_HANDLE_VALUE || GetLastError() == ERROR_PIPE_BUSY)
		return ALREADY_OPEN;
	CloseHandle(hPipe);
	m_pcComm= new CPipeServer();	// main program pipe
	int nRes;
	// only use one thread to ensure thread safety
	if (nRes= static_cast<CPipeServer*>(m_pcComm)->Init(argv[1], 1, dwBuffSizeIn, dwBuffSizeOut, this, NULL))
		return nRes;
	if (WAIT_OBJECT_0 != WaitForSingleObject(m_hClose, INFINITE))	// wait here until closing
		return WIN_ERROR(GetLastError(), nRes);
	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	InitializeQueueLimit();
	g_cTimer.ResetTimer();
#ifndef _DEBUG
	ShowWindow(GetConsoleWindow(), SW_HIDE);
#endif
	CMainManager* pMainManager= new CMainManager;
	int nRes= pMainManager->Run(argc, argv);	// program sits here until stopped
	delete pMainManager;
	return nRes;
}

// WM_COPYDATA http://www.cplusplus.com/forum/windows/23232/
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms633573%28v=vs.85%29.aspx
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms632593%28v=vs.85%29.aspx
<|endoftext|>


<commit_before>#include "layouterCSS.h"

#include <vector>
#include <string>
#include <memory>
#include <algorithm>

static uint8_t hex2num(char c)
{
  switch (c)
  {
    case '0': return 0;
    case '1': return 1;
    case '2': return 2;
    case '3': return 3;
    case '4': return 4;
    case '5': return 5;
    case '6': return 6;
    case '7': return 7;
    case '8': return 8;
    case '9': return 9;
    case 'a':
    case 'A': return 10;
    case 'b':
    case 'B': return 11;
    case 'c':
    case 'C': return 12;
    case 'd':
    case 'D': return 13;
    case 'e':
    case 'E': return 14;
    case 'f':
    case 'F': return 15;
    default:  return 0;
  }
}

static uint8_t hex2byte(char c1, char c2)
{
  return hex2num(c1)* 16 + hex2num(c2);
}

void evalColor(const std::string & col, uint8_t & r, uint8_t & g, uint8_t &b)
{
  if (col[0] == '#' && col.length() >= 7)
  {
    r = hex2byte(col[1], col[2]);
    g = hex2byte(col[3], col[4]);
    b = hex2byte(col[5], col[6]);
  }
}

double evalSize(const std::string & sz)
{
  // right now we accept only pixel sizes
  size_t l = sz.length();

  if (sz[l-2] == 'p' && sz[l-1] == 'x')
  {
    return atof(sz.c_str());
  }

  // TODO exception
  return 0;
}

static bool ruleFits(const std::string & sel, const pugi::xml_node & node)
{
  if (sel == "*")         return true;
  if (sel == node.name()) return true;

  return false;
}

static uint16_t rulePrio(const std::string & sel)
{
  if (sel == "*") return 0;

  return 1;
}

const std::string & textStyleSheet_c::getValue(const pugi::xml_node & node, const std::string & attribute) const
{
  static std::string defaultValue("");

  // go through all rules, check only the ones that give a value to the requested attribute
  // evaluate rule by priority (look at the CSS priority rules
  // choose the highest priority
  int16_t bestPrio = -1;
  std::string & res = defaultValue;

  for (auto & r : rules)
  {
    if (ruleFits(r.selector, node) && r.attribute == attribute && rulePrio(r.selector) > bestPrio)
    {
      res = r.value;
      bestPrio = rulePrio(r.selector);
    }
  }

  return res;
}

void textStyleSheet_c::font(const std::string& family, const std::string& file, const std::string& style, const std::string& variant, const std::string& weight, const std::string& stretch)
{
  if (families.size())
  {
    font(families.begin()->second->getCache(), family, file, style, variant, weight, stretch);
  }
  else
  {
    font(std::make_shared<fontCache_c>(), family, file, style, variant, weight, stretch);
  }
}

void textStyleSheet_c::font(std::shared_ptr<fontCache_c> fc, const std::string& family, const std::string& file, const std::string& style, const std::string& variant, const std::string& weight, const std::string& stretch)
{
  auto i = families.find(family);

  if (i == families.end())
  {
    i = families.insert(std::make_pair(family, std::make_shared<fontFamily_c>(fc))).first;
  }

  i->second->addFont(file, style, variant, weight, stretch);
}

<commit_msg>implement class selector in CSS<commit_after>#include "layouterCSS.h"

#include <vector>
#include <string>
#include <memory>
#include <algorithm>

static uint8_t hex2num(char c)
{
  switch (c)
  {
    case '0': return 0;
    case '1': return 1;
    case '2': return 2;
    case '3': return 3;
    case '4': return 4;
    case '5': return 5;
    case '6': return 6;
    case '7': return 7;
    case '8': return 8;
    case '9': return 9;
    case 'a':
    case 'A': return 10;
    case 'b':
    case 'B': return 11;
    case 'c':
    case 'C': return 12;
    case 'd':
    case 'D': return 13;
    case 'e':
    case 'E': return 14;
    case 'f':
    case 'F': return 15;
    default:  return 0;
  }
}

static uint8_t hex2byte(char c1, char c2)
{
  return hex2num(c1)* 16 + hex2num(c2);
}

void evalColor(const std::string & col, uint8_t & r, uint8_t & g, uint8_t &b)
{
  if (col[0] == '#' && col.length() >= 7)
  {
    r = hex2byte(col[1], col[2]);
    g = hex2byte(col[3], col[4]);
    b = hex2byte(col[5], col[6]);
  }
}

double evalSize(const std::string & sz)
{
  // right now we accept only pixel sizes
  size_t l = sz.length();

  if (sz[l-2] == 'p' && sz[l-1] == 'x')
  {
    return atof(sz.c_str());
  }

  // TODO exception
  return 0;
}

static bool ruleFits(const std::string & sel, const pugi::xml_node & node)
{
  if (sel == "*")         return true;
  if (sel == node.name()) return true;
  if (sel[0] == '.')
  {
    auto attr = node.attribute("class");

    if (!attr.empty())
    {
      if (attr.value() == sel.substr(1))
      {
        return true;
      }
    }
  }

  return false;
}

static uint16_t rulePrio(const std::string & sel)
{
  if (sel == "*") return 0;
  if (sel[0] == '.') return 1;

  return 2;
}

const std::string & textStyleSheet_c::getValue(const pugi::xml_node & node, const std::string & attribute) const
{
  static std::string defaultValue("");

  // go through all rules, check only the ones that give a value to the requested attribute
  // evaluate rule by priority (look at the CSS priority rules
  // choose the highest priority
  int16_t bestPrio = -1;
  std::string & res = defaultValue;

  for (auto & r : rules)
  {
    if (ruleFits(r.selector, node) && r.attribute == attribute && rulePrio(r.selector) > bestPrio)
    {
      res = r.value;
      bestPrio = rulePrio(r.selector);
    }
  }

  return res;
}

void textStyleSheet_c::font(const std::string& family, const std::string& file, const std::string& style, const std::string& variant, const std::string& weight, const std::string& stretch)
{
  if (families.size())
  {
    font(families.begin()->second->getCache(), family, file, style, variant, weight, stretch);
  }
  else
  {
    font(std::make_shared<fontCache_c>(), family, file, style, variant, weight, stretch);
  }
}

void textStyleSheet_c::font(std::shared_ptr<fontCache_c> fc, const std::string& family, const std::string& file, const std::string& style, const std::string& variant, const std::string& weight, const std::string& stretch)
{
  auto i = families.find(family);

  if (i == families.end())
  {
    i = families.insert(std::make_pair(family, std::make_shared<fontFamily_c>(fc))).first;
  }

  i->second->addFont(file, style, variant, weight, stretch);
}

<|endoftext|>


<commit_before>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TGeoManager.h>
#include <TGeoNode.h>
#include <TEveManager.h>
#include <TEveGeoNode.h>

#include <AliEveEventManager.h>
#endif

void geom_emcal()
{
  AliEveEventManager::GetMaster()->AssertGeometry();

  TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("XEN1_1");
  if (!node) {
    Warning("geom_emcal()", "Node XEN1_1 not found.");
    return;
  }

  TEveGeoTopNode* emcal_re = new TEveGeoTopNode(gGeoManager, node);
    emcal_re->SetVisLevel(1);
  gEve->AddGlobalElement(emcal_re);
  gEve->Redraw3D();
}
<commit_msg>EMCal's geom added to RPhi projection.<commit_after>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TGeoManager.h>
#include <TGeoNode.h>
#include <TEveManager.h>
#include <TEveGeoNode.h>

#include <AliEveEventManager.h>
#include <AliEveMultiView.h>
#endif

void geom_emcal()
{
    AliEveEventManager::GetMaster()->AssertGeometry();
    AliEveMultiView *mv = AliEveMultiView::Instance();

    TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("XEN1_1");
    if (!node) {
        Warning("geom_emcal()", "Node XEN1_1 not found.");
        return;
    }

    TEveGeoTopNode* emcal_re = new TEveGeoTopNode(gGeoManager, node);
    emcal_re->SetVisLevel(1);
    emcal_re->SetMainTransparency(70);

    // 3D view:
    gEve->AddGlobalElement(emcal_re);

    // RPhi
    mv->ImportGeomRPhi(emcal_re);
    emcal_re->ProjectAllChildren();
    emcal_re->PropagateRnrStateToProjecteds();
    g_proj = gEve->SpawnNewScene("emcal proj", "emcal proj");
    AliEveMultiView::Instance()->GetRPhiView()->AddScene(g_proj);
    g_proj->SetElementName("EMCal geom RPhi");
    g_proj->AddElement(emcal_re);

    gSystem->ProcessEvents();
    gEve->Redraw3D();
}
<|endoftext|>


<commit_before>#include "myHeader.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

void printStringArr(const string a[], int n, ostream &os) {
	for (int i = 0; i < n; i++)
		os << "\n" << a[i];
}

int getIntInRange(int start, int end) {
	int x = getInt();

	while (x < start || x > end) {
		cout
			<< "\a\tYour number must be "
			<< (x < start ? "greater" : "less")
			<< " than or equal to "
			<< (x < start ? start : end)
			<< ". \n\tTry again: ";
		x = getInt();
	}

	return x;
}

int getInt() {
	double x = getNum();

	while (int(x) != x) {
		cout << "\a\tYour number is not an integer! \n\tTry Again: ";
		x = getNum();
	}

	return int(x);
}

double getNum() {
	double x;

	while (!(cin >> x)) {
		cin.clear();	cin.ignore(30, '\n');
		cout << "\a\tPlease no inapropriate characters! \n\tTry again: ";
	}
	cin.ignore(80, '\n');

	return x;
}

void loadStringArrayFromFile(string a[], int n, ifstream &ifs, bool &isLoaded) {
	for (int i = 0; i < n; i++)
		getline(ifs, a[i]);

	isLoaded = true;
}

void loadStats(int &gamesPlayed, int whoWon[], double whoWonPercent[], double numMoves[], int n, ifstream &ifs, bool &isLoaded) {

	while (ifs.peek() < '0' || ifs.peek() > '9')
		ifs.ignore();
	ifs >> gamesPlayed;

	while (ifs.peek() < '0' || ifs.peek() > '9')
		ifs.ignore();
	for (int i = 0; i < n; i++)
		ifs >> whoWon[i];

	while (ifs.peek() < '0' || ifs.peek() > '9')
		ifs.ignore();
	for (int i = 0; i < n; i++) {
		ifs >> whoWonPercent[i];
		ifs.ignore();	// for discarding '%'
	}

	while (ifs.peek() < '0' || ifs.peek() > '9')
		ifs.ignore();
	for (int i = 0; i < n; i++)
		ifs >> numMoves[i];

	isLoaded = true;
}

void printStats(int gamesPld, const int whoWon[], const double winPct[], const double numMvs[], int n, ostream &os) {

	os
		<< fixed << setprecision(1)
		<< "\nHunt the Wumpus Game Statistics"
		<< "\n\n\tGames Played: " << gamesPld
		<< "\n\n\tWho Won:"
		<< "\n\tPlayer\tWumpus\tPit\n";

	for (int i = 0; i < n; i++)
		os << "\t" << whoWon[i];

	os
		<< "\n\n\tWin Rate:"
		<< "\n\tPlayer\tWumpus\tPit\n";

	for (int i = 0; i < n; i++)
		os << "\t" << winPct[i] << "%";

	os
		<< "\n\n\tMoves per Game:"
		<< "\n\tLeast\tMost\tAverage\n"
		<< "\t" << int(numMvs[0])
		<< "\t" << int(numMvs[1])
		<< "\t" << numMvs[2];
}

void load2DArr(int map[][SIZE_EXITS], int const n, int const m) {
	int tempMap[21][3] = {
		{ 0, 0, 0 },		// room not actually used
		{ 2, 4, 19 },
		{ 1, 3, 6 },
		{ 2, 8, 20 },
		{ 1, 5, 9 },
		{ 4, 6, 11 },
		{ 2, 5, 7 },
		{ 6, 8, 12 },
		{ 3, 7, 13 },
		{ 4, 10, 16 },
		{ 9, 11, 14 },
		{ 5, 10, 12 },
		{ 7, 11, 15 },
		{ 8, 15, 18 },
		{ 10, 15, 17 },
		{ 12, 13, 14 },
		{ 9, 17, 19 },
		{ 14, 16, 18 },
		{ 13, 17, 20 },
		{ 1, 16, 20 },
		{ 3, 18, 19 }
	};

	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			map[i][j] = tempMap[i][j];
}

void print2DArr(int map[][3], int n, int m, ostream &os) {
	cout << "\n";
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cout << "\t" << map[i][j] << (j % m == m - 1 ? "\n" : ", ");
}

int startHunt(int const map[][3], int player, int wumpus, int bat1, int bat2, int pit1, int pit2, int &count) {
	count = 0;

	while (true) {
		if (player == wumpus) {
			cout << "\n\tYou awakened the Wumpus. He eats you. \n\tYou lose.";
			return -1;
		}
		else if (player == pit1 || player == pit2) {
			cout << "\n\tYou fell into a bottomless pit. \n\tYou lose... eventually...";
			return 0;
		}

		/*if (isWumpusNear(player, wumpus))
			cout << "\n\tYou smell the unmistakable stench of a Wumpus";

		if (isPitNear(player, pit1, pit2))
			cout << "\n\tYou smell the unmistakable stench of a Wumpus";

		if (isBatNear(player, wumpus))
			cout << "\n\tYou smell the unmistakable stench of a Wumpus";

		cout << "You "*/
	}
}<commit_msg>finished messaging for hazards<commit_after>#include "myHeader.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

void printStringArr(const string a[], int n, ostream &os) {
	for (int i = 0; i < n; i++)
		os << "\n" << a[i];
}

int getIntInRange(int start, int end) {
	int x = getInt();

	while (x < start || x > end) {
		cout
			<< "\a\tYour number must be "
			<< (x < start ? "greater" : "less")
			<< " than or equal to "
			<< (x < start ? start : end)
			<< ". \n\tTry again: ";
		x = getInt();
	}

	return x;
}

int getInt() {
	double x = getNum();

	while (int(x) != x) {
		cout << "\a\tYour number is not an integer! \n\tTry Again: ";
		x = getNum();
	}

	return int(x);
}

double getNum() {
	double x;

	while (!(cin >> x)) {
		cin.clear();	cin.ignore(30, '\n');
		cout << "\a\tPlease no inapropriate characters! \n\tTry again: ";
	}
	cin.ignore(80, '\n');

	return x;
}

void loadStringArrayFromFile(string a[], int n, ifstream &ifs, bool &isLoaded) {
	for (int i = 0; i < n; i++)
		getline(ifs, a[i]);

	isLoaded = true;
}

void loadStats(int &gamesPlayed, int whoWon[], double whoWonPercent[], double numMoves[], int n, ifstream &ifs, bool &isLoaded) {

	while (ifs.peek() < '0' || ifs.peek() > '9')
		ifs.ignore();
	ifs >> gamesPlayed;

	while (ifs.peek() < '0' || ifs.peek() > '9')
		ifs.ignore();
	for (int i = 0; i < n; i++)
		ifs >> whoWon[i];

	while (ifs.peek() < '0' || ifs.peek() > '9')
		ifs.ignore();
	for (int i = 0; i < n; i++) {
		ifs >> whoWonPercent[i];
		ifs.ignore();	// for discarding '%'
	}

	while (ifs.peek() < '0' || ifs.peek() > '9')
		ifs.ignore();
	for (int i = 0; i < n; i++)
		ifs >> numMoves[i];

	isLoaded = true;
}

void printStats(int gamesPld, const int whoWon[], const double winPct[], const double numMvs[], int n, ostream &os) {

	os
		<< fixed << setprecision(1)
		<< "\nHunt the Wumpus Game Statistics"
		<< "\n\n\tGames Played: " << gamesPld
		<< "\n\n\tWho Won:"
		<< "\n\tPlayer\tWumpus\tPit\n";

	for (int i = 0; i < n; i++)
		os << "\t" << whoWon[i];

	os
		<< "\n\n\tWin Rate:"
		<< "\n\tPlayer\tWumpus\tPit\n";

	for (int i = 0; i < n; i++)
		os << "\t" << winPct[i] << "%";

	os
		<< "\n\n\tMoves per Game:"
		<< "\n\tLeast\tMost\tAverage\n"
		<< "\t" << int(numMvs[0])
		<< "\t" << int(numMvs[1])
		<< "\t" << numMvs[2];
}

void load2DArr(int map[][SIZE_EXITS], int const n, int const m) {
	int tempMap[21][3] = {
		{ 0, 0, 0 },		// room not actually used
		{ 2, 4, 19 },
		{ 1, 3, 6 },
		{ 2, 8, 20 },
		{ 1, 5, 9 },
		{ 4, 6, 11 },
		{ 2, 5, 7 },
		{ 6, 8, 12 },
		{ 3, 7, 13 },
		{ 4, 10, 16 },
		{ 9, 11, 14 },
		{ 5, 10, 12 },
		{ 7, 11, 15 },
		{ 8, 15, 18 },
		{ 10, 15, 17 },
		{ 12, 13, 14 },
		{ 9, 17, 19 },
		{ 14, 16, 18 },
		{ 13, 17, 20 },
		{ 1, 16, 20 },
		{ 3, 18, 19 }
	};

	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			map[i][j] = tempMap[i][j];
}

void print2DArr(int map[][3], int n, int m, ostream &os) {
	cout << "\n";
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cout << "\t" << map[i][j] << (j % m == m - 1 ? "\n" : ", ");
}

int startHunt(int const map[][3], int player, int wumpus, int bat1, int bat2, int pit1, int pit2, int &count) {
	count = 0;

	while (true) {
		if (player == wumpus) {
			cout << "\n\n\tYou awakened the Wumpus. He eats you. \n\tYou lose.";
			return -1;
		}
		else if (player == pit1 || player == pit2) {
			cout << "\n\n\tYou fell into a bottomless pit. \n\tYou lose... eventually...";
			return 0;
		}

		if (isWumpusNear(player, wumpus))
			cout << "\n\n\tYou smell the unmistakable stench of a Wumpus";

		if (isBatNear(player, bat1, bat2))
			cout << "\n\n\tYou hear the flapping of large wings";

		if (isPitNear(player, pit1, pit2))
			cout << "\n\n\tYou feel an ominous breeze";

		cout << "\n\nYou are in room " << player;
	}
}<|endoftext|>


<commit_before><commit_msg>label position and bounds rounding<commit_after><|endoftext|>


<commit_before>/*
 *  ______                   __  __              __
 * /\  _  \           __    /\ \/\ \            /\ \__
 * \ \ \L\ \  __  __ /\_\   \_\ \ \ \____    ___\ \ ,_\   ____
 *  \ \  __ \/\ \/\ \\/\ \  /'_` \ \ '__`\  / __`\ \ \/  /',__\
 *   \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\
 *    \ \_\ \_\ \___/  \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/
 *     \/_/\/_/\/__/    \/_/\/__,_ /\/___/  \/___/  \/__/\/___/
 * @copyright Copyright 2017 Avidbots Corp.
 * @name	flatland_server_ndoe.cpp
 * @brief	Load params and run the ros node for flatland_server
 * @author Joseph Duchesne
 *
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2017, Avidbots Corp.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *      copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Avidbots Corp. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */

#include <ros/ros.h>
#include <signal.h>
#include <string>

#include "flatland_server/simulation_manager.h"

/** Global variables */
flatland_server::SimulationManager *simulation_manager;

/**
 * @name        SigintHandler
 * @brief       Interrupt handler - sends shutdown signal to simulation_manager
 * @param[in]   sig: signal itself
 */
void SigintHandler(int sig) {
  ROS_WARN_NAMED("Node", "*** Shutting down... ***");

  if (simulation_manager != nullptr) {
    simulation_manager->Shutdown();
    delete simulation_manager;
    simulation_manager = nullptr;
  }
  ROS_INFO_STREAM_NAMED("Node", "Beginning ros shutdown");
  ros::shutdown();
}

/**
 * @name        main
 * @brief       Entrypoint for Flatland Server ros node
 */
int main(int argc, char **argv) {
  ros::init(argc, argv, "Node", ros::init_options::NoSigintHandler);
  ros::NodeHandle node_handle("~");

  // Load parameters
  float initial_rate = 60.0;  // The physics update rate (Hz)
  std::string world_path;
  if (node_handle.getParam("initial_rate", initial_rate)) {
    ROS_INFO_STREAM_NAMED("Node", "initial rate: " << initial_rate);
  } else {
    ROS_INFO_STREAM_NAMED("Node", "assuming initial rate: " << initial_rate);
  }

  if (node_handle.getParam("world_path", world_path)) {
    ROS_INFO_STREAM_NAMED("Node", "world path: " << world_path);
  } else {
    ROS_FATAL_NAMED("Node", "No world_path parameter given!");
    ros::shutdown();
    return 1;
  }

  // Create simulation manager object
  simulation_manager =
      new flatland_server::SimulationManager(world_path, initial_rate);

  // Register sigint shutdown handler
  signal(SIGINT, SigintHandler);

  ROS_INFO_STREAM_NAMED("Node", "Initialized");
  simulation_manager->Main();

  ROS_INFO_STREAM_NAMED("Node", "Returned from simulation manager main");
  delete simulation_manager;
  simulation_manager = nullptr;
  return 0;
}
<commit_msg>added another comment<commit_after>/*
 *  ______                   __  __              __
 * /\  _  \           __    /\ \/\ \            /\ \__
 * \ \ \L\ \  __  __ /\_\   \_\ \ \ \____    ___\ \ ,_\   ____
 *  \ \  __ \/\ \/\ \\/\ \  /'_` \ \ '__`\  / __`\ \ \/  /',__\
 *   \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\
 *    \ \_\ \_\ \___/  \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/
 *     \/_/\/_/\/__/    \/_/\/__,_ /\/___/  \/___/  \/__/\/___/
 * @copyright Copyright 2017 Avidbots Corp.
 * @name	flatland_server_ndoe.cpp
 * @brief	Load params and run the ros node for flatland_server
 * @author Joseph Duchesne
 *
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2017, Avidbots Corp.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *      copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Avidbots Corp. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */

#include <ros/ros.h>
#include <signal.h>
#include <string>

#include "flatland_server/simulation_manager.h"

/** Global variables */
flatland_server::SimulationManager *simulation_manager;

/**
 * @name        SigintHandler
 * @brief       Interrupt handler - sends shutdown signal to simulation_manager
 * @param[in]   sig: signal itself
 */
void SigintHandler(int sig) {
  ROS_WARN_NAMED("Node", "*** Shutting down... ***");

  if (simulation_manager != nullptr) {
    simulation_manager->Shutdown();
    delete simulation_manager;
    simulation_manager = nullptr;
  }
  ROS_INFO_STREAM_NAMED("Node", "Beginning ros shutdown");
  ros::shutdown();
}

/**
 * @name        main
 * @brief       Entrypoint for Flatland Server ros node
 */
int main(int argc, char **argv) {
  ros::init(argc, argv, "Node", ros::init_options::NoSigintHandler);
  ros::NodeHandle node_handle("~");

  // Load parameters
  float initial_rate = 60.0;  // The physics update rate (Hz)
  std::string world_path;     // The file path to the world.yaml file

  if (node_handle.getParam("initial_rate", initial_rate)) {
    ROS_INFO_STREAM_NAMED("Node", "initial rate: " << initial_rate);
  } else {
    ROS_INFO_STREAM_NAMED("Node", "assuming initial rate: " << initial_rate);
  }

  if (node_handle.getParam("world_path", world_path)) {
    ROS_INFO_STREAM_NAMED("Node", "world path: " << world_path);
  } else {
    ROS_FATAL_NAMED("Node", "No world_path parameter given!");
    ros::shutdown();
    return 1;
  }

  // Create simulation manager object
  simulation_manager =
      new flatland_server::SimulationManager(world_path, initial_rate);

  // Register sigint shutdown handler
  signal(SIGINT, SigintHandler);

  ROS_INFO_STREAM_NAMED("Node", "Initialized");
  simulation_manager->Main();

  ROS_INFO_STREAM_NAMED("Node", "Returned from simulation manager main");
  delete simulation_manager;
  simulation_manager = nullptr;
  return 0;
}
<|endoftext|>