<commit_before>/*
 * This file is part of TelepathyQt4Logger
 *
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This 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 Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "tpl-tool.h"
#include <tools/_gen/tpl-tool.moc.hpp>
#include <TelepathyQt4Logger/utils.h>
#include <QApplication>
#include <TelepathyQt4/Account>
#include <TelepathyQt4/AccountSet>
#include <TelepathyQt4/AccountManager>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4Logger/Entity>
#include <TelepathyQt4Logger/LogManager>
#include <TelepathyQt4Logger/PendingDates>
#include <TelepathyQt4Logger/PendingEntities>
#include <TelepathyQt4Logger/PendingEvents>
#include <TelepathyQt4Logger/PendingSearch>
#include <TelepathyQt4Logger/Init>
#include <glib-object.h>
#include <QGst/Init>
#include <QDebug>

TplToolApplication::TplToolApplication(int &argc, char **argv)
    : QCoreApplication(argc, argv)
{
    debugfn();

    mAccountManager = Tp::AccountManager::create();
    connect(mAccountManager->becomeReady(Tp::AccountManager::FeatureCore),
            SIGNAL(finished(Tp::PendingOperation*)),
            this,
            SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}

Tp::AccountPtr TplToolApplication::accountPtr(const QString &id)
{
    debugfn();

    mAccountPtr = Tpl::Utils::instance()->accountPtr(id.toAscii());
    if (!mAccountPtr->isValid()) {
        return mAccountPtr;
    }

    connect(mAccountPtr->becomeReady(Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureAvatar),
            SIGNAL(finished(Tp::PendingOperation*)),
            this,
            SLOT(onAccountReady(Tp::PendingOperation*)));

    return mAccountPtr;
}

Tpl::EntityPtr TplToolApplication::entityPtr(const QString &id)
{
    debugfn();

    return Tpl::Entity::create(id.toAscii(), Tpl::EntityTypeContact, NULL, NULL);
}

bool TplToolApplication::parseArgs1()
{
    debugfn();

    QStringList args = arguments();

    Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();
    if (logManager.isNull()) {
        qWarning() << "LogManager not found";
        return false;
    }

    if (args.size() == 2 && args.at(1) == "accounts") {
        Tp::AccountSetPtr accountSet = Tpl::Utils::instance()->accountManagerPtr()->validAccounts();
        QList<Tp::AccountPtr> accounts = accountSet->accounts();
        Tp::AccountPtr account;
        int i = 0;
        Q_FOREACH(account, accounts) {
            qDebug() << "account " << i++ << account->objectPath();
        }
        this->exit();
        return true;
    } else if ((args.size() == 3 && args.at(1) == "contacts") ||
               (args.size() == 4 && args.at(1) == "exists") ||
               (args.size() == 3 && args.at(1) == "entities") ||
               (args.size() == 4 && args.at(1) == "dates") ||
               (args.size() == 4 && args.at(1) == "events") ||
               (args.size() == 5 && args.at(1) == "filteredEvents")) {
        Tp::AccountPtr account = accountPtr(args.at(2).toAscii());
        if (account.isNull()) {
            qWarning() << "Account not found " << args.at(2);
        }
        return true;
    } else if (args.size() == 3 && args.at(1) == "search") {
        Tpl::PendingSearch *ps = logManager->search(args.at(2), Tpl::EventTypeMaskAny);
        debugfn() << "PendingSearch=" << ps;
        if (!ps) {
            qWarning() << "Error in search";
            this->exit(-1);
            return false;
        }

        connect(ps,
                SIGNAL(finished(Tpl::PendingOperation*)),
                this,
                SLOT(onPendingSearch(Tpl::PendingOperation*)));

        ps->start();

        return true;
    }

    qDebug() << "Telepathy logger command line tool (qt4)";
    qDebug() << "";
    qDebug() << "General usage: tpl-tool <command> <parameters>";
    qDebug() << "";
    qDebug() << "tpl-tool accounts";
    qDebug() << "tpl-tool contacts <account>";
    qDebug() << "tpl-tool exists <account> <entity>";
    qDebug() << "tpl-tool entities <account>";
    qDebug() << "tpl-tool dates <account> <entity>";
    qDebug() << "tpl-tool events <account> <entity>";
    qDebug() << "tpl-tool filteredEvents <account> <entity> <numEvents>";
    qDebug() << "tpl-tool search <text>";
    this->exit(-1);

    return false;
}

bool TplToolApplication::parseArgs2()
{
    debugfn();

    QStringList args = arguments();

    Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();
    if (logManager.isNull()) {
        qWarning() << "LogManager not found";
        return false;
    }

    if (args.size() == 3 && args.at(1) == "contacts") {
        Tp::Contacts contacts = mAccountPtr->connection()->contactManager()->allKnownContacts();
        debugfn() << "number of contacts = " << contacts.size();

        Tp::ContactPtr contact;
        int i = 0;
        Q_FOREACH(contact, contacts) {
            qDebug() << "contact " << i++ << contact->id();
        }
        this->exit();
        return true;
    } else if (args.size() == 4 && args.at(1) == "exists") {
        Tpl::EntityPtr entity = entityPtr(args.at(3));
        if (entity.isNull()) {
            qWarning() << "Entity not found " << args.at(3);
        }

        bool ret = logManager->exists(mAccountPtr, entity, Tpl::EventTypeMaskAny);
        qDebug() << "tpl-tool exists " << args.at(2) << args.at(3) << " -> " << ret;
        this->exit();
        return true;
    } else if (args.at(0) == "entities") {
    } else if (args.at(0) == "dates") {
    } else if (args.at(0) == "events") {
    } else if (args.at(0) == "filteredEvents") {
    }

    return false;
}

void TplToolApplication::onAccountManagerReady(Tp::PendingOperation *po)
{
    debugfn() << "po=" << po << "isError=" << po->isError();

    if (po->isError()) {
        return;
    }

    Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();
    if (logManager.isNull()) {
        qWarning() << "LogManager not found";
        return;
    }

    logManager->setAccountManagerPtr(mAccountManager);

    parseArgs1();
}

void TplToolApplication::onAccountReady(Tp::PendingOperation *po)
{
    debugfn() << "po=" << po << "isError=" << po->isError();

    if (po->isError()) {
        return;
    }

    Tp::ConnectionPtr connection = mAccountPtr->connection();
    if (connection.isNull()) {
        return;
    }

    connect(mAccountPtr->connection()->becomeReady(Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureSelfContact << Tp::Connection::FeatureRoster),
        SIGNAL(finished(Tp::PendingOperation*)),
        this,
        SLOT(onConnectionReady(Tp::PendingOperation*)));
}

void TplToolApplication::onConnectionReady(Tp::PendingOperation *po)
{
    debugfn() << "po=" << po << "isError=" << po->isError();

    if (po->isError()) {
        return;
    }

    parseArgs2();
}

void TplToolApplication::onPendingSearch(Tpl::PendingOperation *po)
{
    Tpl::PendingSearch *ps = (Tpl::PendingSearch*) po;

    debugfn() << " search hits " << ps->hits().size();

    Tpl::SearchHit hit;
    Q_FOREACH(hit, ps->hits()) {
        //debugfn() << "account=" << hit.account << "date=" << hit.date << "target=" << hit.target ? hit.target->identifier() : "null";
        debugfn() << "account=" << hit.account;
        debugfn() << "date=" << hit.date;
        debugfn() << "entity=" << (hit.target.isNull() ? "null" : hit.target->identifier());
    }

    this->exit();
}

int main(int argc, char **argv)
{
    g_type_init();
    Tp::registerTypes();

    TplToolApplication app(argc, argv);
    Tpl::init();

    return app.exec();
}
<commit_msg>Adapting search to last changes Added some debug output to tpl-tool<commit_after>/*
 * This file is part of TelepathyQt4Logger
 *
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This 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 Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "tpl-tool.h"
#include <tools/_gen/tpl-tool.moc.hpp>
#include <TelepathyQt4Logger/utils.h>
#include <QApplication>
#include <TelepathyQt4/Account>
#include <TelepathyQt4/AccountSet>
#include <TelepathyQt4/AccountManager>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4Logger/Entity>
#include <TelepathyQt4Logger/LogManager>
#include <TelepathyQt4Logger/PendingDates>
#include <TelepathyQt4Logger/PendingEntities>
#include <TelepathyQt4Logger/PendingEvents>
#include <TelepathyQt4Logger/PendingSearch>
#include <TelepathyQt4Logger/Init>
#include <glib-object.h>
#include <QGst/Init>
#include <QDebug>

TplToolApplication::TplToolApplication(int &argc, char **argv)
    : QCoreApplication(argc, argv)
{
    debugfn();

    mAccountManager = Tp::AccountManager::create();
    connect(mAccountManager->becomeReady(Tp::AccountManager::FeatureCore),
            SIGNAL(finished(Tp::PendingOperation*)),
            this,
            SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}

Tp::AccountPtr TplToolApplication::accountPtr(const QString &id)
{
    debugfn();

    mAccountPtr = Tpl::Utils::instance()->accountPtr(id.toAscii());
    if (!mAccountPtr->isValid()) {
        return mAccountPtr;
    }

    connect(mAccountPtr->becomeReady(Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureAvatar),
            SIGNAL(finished(Tp::PendingOperation*)),
            this,
            SLOT(onAccountReady(Tp::PendingOperation*)));

    return mAccountPtr;
}

Tpl::EntityPtr TplToolApplication::entityPtr(const QString &id)
{
    debugfn();

    return Tpl::Entity::create(id.toAscii(), Tpl::EntityTypeContact, NULL, NULL);
}

bool TplToolApplication::parseArgs1()
{
    debugfn();

    QStringList args = arguments();

    Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();
    if (logManager.isNull()) {
        qWarning() << "LogManager not found";
        return false;
    }

    if (args.size() == 2 && args.at(1) == "accounts") {
        Tp::AccountSetPtr accountSet = Tpl::Utils::instance()->accountManagerPtr()->validAccounts();
        QList<Tp::AccountPtr> accounts = accountSet->accounts();
        Tp::AccountPtr account;
        int i = 0;
        Q_FOREACH(account, accounts) {
            qDebug() << "account " << i++ << account->objectPath();
        }
        this->exit();
        return true;
    } else if ((args.size() == 3 && args.at(1) == "contacts") ||
               (args.size() == 4 && args.at(1) == "exists") ||
               (args.size() == 3 && args.at(1) == "entities") ||
               (args.size() == 4 && args.at(1) == "dates") ||
               (args.size() == 4 && args.at(1) == "events") ||
               (args.size() == 5 && args.at(1) == "filteredEvents")) {
        Tp::AccountPtr account = accountPtr(args.at(2).toAscii());
        if (account.isNull()) {
            qWarning() << "Account not found " << args.at(2);
        }
        return true;
    } else if (args.size() == 3 && args.at(1) == "search") {
        Tpl::PendingSearch *ps = logManager->search(args.at(2), Tpl::EventTypeMaskAny);
        debugfn() << "PendingSearch=" << ps;
        if (!ps) {
            qWarning() << "Error in search";
            this->exit(-1);
            return false;
        }

        connect(ps,
                SIGNAL(finished(Tpl::PendingOperation*)),
                this,
                SLOT(onPendingSearch(Tpl::PendingOperation*)));

        ps->start();

        return true;
    }

    qDebug() << "Telepathy logger command line tool (qt4)";
    qDebug() << "";
    qDebug() << "General usage: tpl-tool <command> <parameters>";
    qDebug() << "";
    qDebug() << "tpl-tool accounts";
    qDebug() << "tpl-tool contacts <account>";
    qDebug() << "tpl-tool exists <account> <entity>";
    qDebug() << "tpl-tool entities <account>";
    qDebug() << "tpl-tool dates <account> <entity>";
    qDebug() << "tpl-tool events <account> <entity>";
    qDebug() << "tpl-tool filteredEvents <account> <entity> <numEvents>";
    qDebug() << "tpl-tool search <text>";
    this->exit(-1);

    return false;
}

bool TplToolApplication::parseArgs2()
{
    debugfn();

    QStringList args = arguments();

    Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();
    if (logManager.isNull()) {
        qWarning() << "LogManager not found";
        return false;
    }

    if (args.size() == 3 && args.at(1) == "contacts") {
        Tp::Contacts contacts = mAccountPtr->connection()->contactManager()->allKnownContacts();
        debugfn() << "number of contacts = " << contacts.size();

        Tp::ContactPtr contact;
        int i = 0;
        Q_FOREACH(contact, contacts) {
            qDebug() << "contact " << i++ << contact->id();
        }
        this->exit();
        return true;
    } else if (args.size() == 4 && args.at(1) == "exists") {
        Tpl::EntityPtr entity = entityPtr(args.at(3));
        if (entity.isNull()) {
            qWarning() << "Entity not found " << args.at(3);
        }

        bool ret = logManager->exists(mAccountPtr, entity, Tpl::EventTypeMaskAny);
        qDebug() << "tpl-tool exists " << args.at(2) << args.at(3) << " -> " << ret;
        this->exit();
        return true;
    } else if (args.at(0) == "entities") {
    } else if (args.at(0) == "dates") {
    } else if (args.at(0) == "events") {
    } else if (args.at(0) == "filteredEvents") {
    }

    return false;
}

void TplToolApplication::onAccountManagerReady(Tp::PendingOperation *po)
{
    debugfn() << "po=" << po << "isError=" << po->isError();

    if (po->isError()) {
        qWarning() << "error getting account mananger ready";
        exit(-1);
        return;
    }

    Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();
    if (logManager.isNull()) {
        qWarning() << "LogManager not found";
        exit(-1);
        return;
    }

    logManager->setAccountManagerPtr(mAccountManager);

    parseArgs1();
}

void TplToolApplication::onAccountReady(Tp::PendingOperation *po)
{
    debugfn() << "po=" << po << "isError=" << po->isError();

    if (po->isError()) {
        qWarning() << "error getting account ready";
        exit(-1);
        return;
    }

    Tp::ConnectionPtr connection = mAccountPtr->connection();
    if (connection.isNull()) {
        qWarning() << "error null connection";
        exit(-1);
        return;
    }

    connect(mAccountPtr->connection()->becomeReady(Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureSelfContact << Tp::Connection::FeatureRoster),
        SIGNAL(finished(Tp::PendingOperation*)),
        this,
        SLOT(onConnectionReady(Tp::PendingOperation*)));
}

void TplToolApplication::onConnectionReady(Tp::PendingOperation *po)
{
    debugfn() << "po=" << po << "isError=" << po->isError();

    if (po->isError()) {
        qWarning() << "error getting connection ready";
        exit(-1);
        return;
    }

    parseArgs2();
}

void TplToolApplication::onPendingSearch(Tpl::PendingOperation *po)
{
    Tpl::PendingSearch *ps = (Tpl::PendingSearch*) po;

    if (ps->isError()) {
        qWarning() << "error in search";
        exit(-1);
        return;
    }

    Tpl::SearchHitList *hits = ps->hits();
    debugfn() << " search hits " << hits->size();

    Tpl::SearchHit *hit;
    Q_FOREACH(hit, *hits) {
        //debugfn() << "account=" << hit->account << "date=" << hit->date << "target=" << hit->target ? hit->target->identifier() : "null";
        debugfn() << "account=" << hit->account;
        debugfn() << "date=" << hit->date;
        debugfn() << "entity=" << (hit->target.isNull() ? "null" : hit->target->identifier());
    }

    this->exit();
}

int main(int argc, char **argv)
{
    g_type_init();
    Tp::registerTypes();

    TplToolApplication app(argc, argv);
    Tpl::init();

    return app.exec();
}
<|endoftext|>


<commit_before>#include <boost/thread.hpp>

#include "ros_igtl_bridge.h"
#include "ShowPolyData.h"

#include "rib_converter_point.h"
#include "rib_converter_pointcloud.h"
#include "rib_converter_transform.h"
#include "rib_converter_polydata.h"
#include "rib_converter_string.h"
#include "rib_converter_image.h"

//----------------------------------------------------------------------
ROS_IGTL_Bridge::ROS_IGTL_Bridge(int argc, char *argv[], const char* node_name)
{
  ros::init(argc, argv, node_name);
  nh = new ros::NodeHandle;

  // run bridge as client or server
  std::string type;
  ROS_INFO("[ROS-IGTL-Bridge] a");
  if(nh->getParam("/RIB_type",type))
    {
    ROS_INFO("[ROS-IGTL-Bridge] b ");
    if(type == "client")
      ConnectToIGTLServer();
    else if(type == "server")
      CreateIGTLServer();
    else
      ROS_ERROR("[ROS-IGTL-Bridge] Unknown Value for Parameter 'RIB_type'");
    }
  else
    {
    short srvcl = 0;
    while(1)
      {
      std::cout<<"[ROS-IGTL-Bridge] Please type <1> or <2> to run node as OpenIGTLink client or server"<<std::endl<<"1 : SERVER"<<std::endl<<"2 : CLIENT"<<std::endl;
      std::cin>>srvcl;

      if (srvcl==1)
        {
        CreateIGTLServer();
        break;
        }
      else if (srvcl==2)
        {
        ConnectToIGTLServer();
        break;
        }
      }
    }

  ROS_INFO("[ROS-IGTL-Bridge] ROS-IGTL-Bridge up and Running.");

  //this->ribcpoint = new RIBConverterPoint;
  //ribcpoint->setup(nh, socket, 10);
  //ribcpoint->publish("IGTL_POINT_IN");
  //ribcpoint->subscribe("IGTL_POINT_OUT");
  //
  //this->ribctransform = new RIBConverterTransform;
  //ribctransform->setup(nh, socket, 10);
  //ribctransform->publish("IGTL_TRANSFORM_IN");
  //ribctransform->subscribe("IGTL_TRANSFORM_OUT");
  //
  //this->ribcpolydata = new RIBConverterPolyData;
  //ribcpolydata->setup(nh, socket, 10);
  //ribcpolydata->publish("IGTL_POLYDATA_IN");
  //ribcpolydata->subscribe("IGTL_POLYDATA_OUT");
  //
  //this->ribcstring = new RIBConverterString;
  //ribcstring->setup(nh, socket, 10);
  //ribcstring->publish("IGTL_STRING_IN");
  //ribcstring->subscribe("IGTL_STRING_OUT");
  //
  //this->ribcimage = new RIBConverterImage;
  //ribcimage->setup(nh, socket, 5);
  //ribcimage->publish("IGTL_IMAGE_IN");
  //ribcimage->subscribe("IGTL_IMAGE_OUT");
  //
  //this->ribcpointcloud = new RIBConverterPointCloud;
  //ribcpointcloud->setup(nh, socket, 5);
  //ribcpointcloud->publish("IGTL_POINTCLOUD_IN");
  //ribcpointcloud->subscribe("IGTL_POINTCLOUD_OUT");

  RIBConverterPoint * point = new RIBConverterPoint;
  this->AddConverter(point, 10, "IGTL_POINT_IN", "IGTL_POINT_OUT");

  RIBConverterTransform* transform = new RIBConverterTransform;
  this->AddConverter(transform, 10, "IGTL_TRANSFORM_IN", "IGTL_TRANSFORM_OUT");

  RIBConverterPolyData* polydata = new RIBConverterPolyData;
  this->AddConverter(polydata, 10, "IGTL_POLYDATA_IN", "IGTL_POLYDATA_OUT");

  RIBConverterString* string = new RIBConverterString;
  this->AddConverter(string, 10, "IGTL_STRING_IN", "IGTL_STRING_OUT");

  RIBConverterImage* image = new RIBConverterImage;
  this->AddConverter(image, 10, "IGTL_IMAGE_IN", "IGTL_IMAGE_OUT");

  RIBConverterPointCloud* pointcloud = new RIBConverterPointCloud;
  this->AddConverter(pointcloud, 10, "IGTL_POINTCLOUD_IN", "IGTL_POINTCLOUD_OUT");

  // start receiver thread
  boost::thread* receiver_thread = new boost::thread(boost::bind(&ROS_IGTL_Bridge::IGTLReceiverThread, this));
}

//----------------------------------------------------------------------
ROS_IGTL_Bridge::~ROS_IGTL_Bridge()
{
  socket->CloseSocket();
}

//----------------------------------------------------------------------
void ROS_IGTL_Bridge::Run()
{
  ros::spin();
}

//----------------------------------------------------------------------
igtl::Socket::Pointer ROS_IGTL_Bridge::GetSocketPointer()
{
  igtl::Socket::Pointer socket_ptr = static_cast<igtl::Socket::Pointer>(socket);
  return socket_ptr;
}

//----------------------------------------------------------------------
void ROS_IGTL_Bridge::CreateIGTLServer()
{
  int    port     = 18944;  // std port
  if(nh->getParam("/RIB_port",port))
    {}
  else
    {
    ROS_INFO("[ROS-IGTL-Bridge] Input socket port: ");
    std::cin >> port;
    }
  igtl::ServerSocket::Pointer serverSocket;
  serverSocket = igtl::ServerSocket::New();
  int c = serverSocket->CreateServer(port);

  if (c < 0)
    {
    ROS_ERROR("[ROS-IGTL-Bridge] Cannot create a server socket.");
    }
  ROS_INFO("[ROS-IGTL-Bridge] Server socket created. Please connect to port: %d",port);

  // wait for connection
  while (1)
    {
    socket = serverSocket->WaitForConnection(1000);
    if (ROS_IGTL_Bridge::socket.IsNotNull())
      {
      break;
      }
    }
}

//----------------------------------
void ROS_IGTL_Bridge::ConnectToIGTLServer()
{
  igtl::ClientSocket::Pointer clientsocket;
  clientsocket = igtl::ClientSocket::New();

  int    port     = 18944; // std port
  std::string ip;
  // get ip
  if(nh->getParam("/RIB_server_ip",ip))
    {}
  else
    {
    ROS_INFO("[ROS-IGTL-Bridge] Please enter ServerIP: ");
    std::cin >> ip;
    }
  // get port
  if(nh->getParam("/RIB_port",port))
    {}
  else
    {
    ROS_INFO("[ROS-IGTL-Bridge] Please enter ServerPort:  ");
    std::cin >> port;
    }
  // connect to server
  int r = clientsocket->ConnectToServer(ip.c_str(), port);

  if (r != 0)
    {
    ROS_ERROR("[ROS-IGTL-Bridge] Cannot connect to server.");
    exit(0);
    }
  socket = (igtl::Socket *)(clientsocket);
}

// ----- receiving from slicer -----------------------------------------
//----------------------------------------------------------------------
void ROS_IGTL_Bridge::IGTLReceiverThread()
{
  igtl::MessageHeader::Pointer headerMsg;
  headerMsg = igtl::MessageHeader::New();
  int rs = 0;
  while(1)
    {
    headerMsg->InitPack();
    // receive packet
    rs = socket->Receive(headerMsg->GetPackPointer(), headerMsg->GetPackSize());

    if (rs == 0)
      socket->CloseSocket();
    if (rs != headerMsg->GetPackSize())
      continue;

    headerMsg->Unpack();

    std::vector< RIBConverterBase* >::iterator iter;
    for (iter = this->converters.begin(); iter != this->converters.end(); iter ++)
      {
        if (strcmp(headerMsg->GetDeviceType(), (*iter)->messageTypeString()) == 0)
          {
            (*iter)->onIGTLMessage(headerMsg);
            break;
          }
      }
    if (iter == this->converters.end())
      {
        socket->Skip(headerMsg->GetBodySizeToRead(),0);
      }
    }

    //// DATATYPE POINT ----------------------------------------------
    //if (strcmp(headerMsg->GetDeviceType(), "POINT") == 0)
    //  {
    //    this->ribcpoint->onIGTLMessage(headerMsg);
    //  }
    //// DATATYPE STRING ---------------------------------------------
    //else if (strcmp(headerMsg->GetDeviceType(), "STRING") == 0)
    //  {
    //    this->ribcstring->onIGTLMessage(headerMsg);
    //  }
    //// DATATYPE TRANSFORM ------------------------------------------
    //else if (strcmp(headerMsg->GetDeviceType(), "TRANSFORM") == 0)
    //  {
    //    this->ribctransform->onIGTLMessage(headerMsg);
    //  }
    //// DATATYPE POLYDATA -------------------------------------------
    //else if (strcmp(headerMsg->GetDeviceType(), "POLYDATA") == 0)
    //  {
    //    this->ribcpolydata->onIGTLMessage(headerMsg);
    //  }
    //// DATATYPE IMAGE -------------------------------------------
    //else if (strcmp(headerMsg->GetDeviceType(), "IMAGE") == 0)
    //  {
    //    this->ribcimage->onIGTLMessage(headerMsg);
    //  }
    //// SKIP DATA
    //else
    //  {
    //  socket->Skip(headerMsg->GetBodySizeToRead(),0);
    //  }
    //}
}

void ROS_IGTL_Bridge::AddConverter(RIBConverterBase* converter, uint32_t size, const char* topicPublish, const char* topicSubscribe)
{
  converter->setup(this->nh, this->socket, size);
  converter->publish(topicPublish);
  converter->subscribe(topicSubscribe);
  this->converters.push_back(converter);
}

<commit_msg>Remove comments.<commit_after>#include <boost/thread.hpp>

#include "ros_igtl_bridge.h"
#include "ShowPolyData.h"

#include "rib_converter_point.h"
#include "rib_converter_pointcloud.h"
#include "rib_converter_transform.h"
#include "rib_converter_polydata.h"
#include "rib_converter_string.h"
#include "rib_converter_image.h"

//----------------------------------------------------------------------
ROS_IGTL_Bridge::ROS_IGTL_Bridge(int argc, char *argv[], const char* node_name)
{
  ros::init(argc, argv, node_name);
  nh = new ros::NodeHandle;

  // run bridge as client or server
  std::string type;
  ROS_INFO("[ROS-IGTL-Bridge] a");
  if(nh->getParam("/RIB_type",type))
    {
    ROS_INFO("[ROS-IGTL-Bridge] b ");
    if(type == "client")
      ConnectToIGTLServer();
    else if(type == "server")
      CreateIGTLServer();
    else
      ROS_ERROR("[ROS-IGTL-Bridge] Unknown Value for Parameter 'RIB_type'");
    }
  else
    {
    short srvcl = 0;
    while(1)
      {
      std::cout<<"[ROS-IGTL-Bridge] Please type <1> or <2> to run node as OpenIGTLink client or server"<<std::endl<<"1 : SERVER"<<std::endl<<"2 : CLIENT"<<std::endl;
      std::cin>>srvcl;

      if (srvcl==1)
        {
        CreateIGTLServer();
        break;
        }
      else if (srvcl==2)
        {
        ConnectToIGTLServer();
        break;
        }
      }
    }

  ROS_INFO("[ROS-IGTL-Bridge] ROS-IGTL-Bridge up and Running.");

  RIBConverterPoint * point = new RIBConverterPoint;
  this->AddConverter(point, 10, "IGTL_POINT_IN", "IGTL_POINT_OUT");

  RIBConverterTransform* transform = new RIBConverterTransform;
  this->AddConverter(transform, 10, "IGTL_TRANSFORM_IN", "IGTL_TRANSFORM_OUT");

  RIBConverterPolyData* polydata = new RIBConverterPolyData;
  this->AddConverter(polydata, 10, "IGTL_POLYDATA_IN", "IGTL_POLYDATA_OUT");

  RIBConverterString* string = new RIBConverterString;
  this->AddConverter(string, 10, "IGTL_STRING_IN", "IGTL_STRING_OUT");

  RIBConverterImage* image = new RIBConverterImage;
  this->AddConverter(image, 10, "IGTL_IMAGE_IN", "IGTL_IMAGE_OUT");

  RIBConverterPointCloud* pointcloud = new RIBConverterPointCloud;
  this->AddConverter(pointcloud, 10, "IGTL_POINTCLOUD_IN", "IGTL_POINTCLOUD_OUT");

  // start receiver thread
  boost::thread* receiver_thread = new boost::thread(boost::bind(&ROS_IGTL_Bridge::IGTLReceiverThread, this));
}

//----------------------------------------------------------------------
ROS_IGTL_Bridge::~ROS_IGTL_Bridge()
{
  socket->CloseSocket();
}

//----------------------------------------------------------------------
void ROS_IGTL_Bridge::Run()
{
  ros::spin();
}

//----------------------------------------------------------------------
igtl::Socket::Pointer ROS_IGTL_Bridge::GetSocketPointer()
{
  igtl::Socket::Pointer socket_ptr = static_cast<igtl::Socket::Pointer>(socket);
  return socket_ptr;
}

//----------------------------------------------------------------------
void ROS_IGTL_Bridge::CreateIGTLServer()
{
  int    port     = 18944;  // std port
  if(nh->getParam("/RIB_port",port))
    {}
  else
    {
    ROS_INFO("[ROS-IGTL-Bridge] Input socket port: ");
    std::cin >> port;
    }
  igtl::ServerSocket::Pointer serverSocket;
  serverSocket = igtl::ServerSocket::New();
  int c = serverSocket->CreateServer(port);

  if (c < 0)
    {
    ROS_ERROR("[ROS-IGTL-Bridge] Cannot create a server socket.");
    }
  ROS_INFO("[ROS-IGTL-Bridge] Server socket created. Please connect to port: %d",port);

  // wait for connection
  while (1)
    {
    socket = serverSocket->WaitForConnection(1000);
    if (ROS_IGTL_Bridge::socket.IsNotNull())
      {
      break;
      }
    }
}

//----------------------------------
void ROS_IGTL_Bridge::ConnectToIGTLServer()
{
  igtl::ClientSocket::Pointer clientsocket;
  clientsocket = igtl::ClientSocket::New();

  int    port     = 18944; // std port
  std::string ip;
  // get ip
  if(nh->getParam("/RIB_server_ip",ip))
    {}
  else
    {
    ROS_INFO("[ROS-IGTL-Bridge] Please enter ServerIP: ");
    std::cin >> ip;
    }
  // get port
  if(nh->getParam("/RIB_port",port))
    {}
  else
    {
    ROS_INFO("[ROS-IGTL-Bridge] Please enter ServerPort:  ");
    std::cin >> port;
    }
  // connect to server
  int r = clientsocket->ConnectToServer(ip.c_str(), port);

  if (r != 0)
    {
    ROS_ERROR("[ROS-IGTL-Bridge] Cannot connect to server.");
    exit(0);
    }
  socket = (igtl::Socket *)(clientsocket);
}

// ----- receiving from slicer -----------------------------------------
//----------------------------------------------------------------------
void ROS_IGTL_Bridge::IGTLReceiverThread()
{
  igtl::MessageHeader::Pointer headerMsg;
  headerMsg = igtl::MessageHeader::New();
  int rs = 0;
  while(1)
    {
    headerMsg->InitPack();
    // receive packet
    rs = socket->Receive(headerMsg->GetPackPointer(), headerMsg->GetPackSize());

    if (rs == 0)
      socket->CloseSocket();
    if (rs != headerMsg->GetPackSize())
      continue;

    headerMsg->Unpack();

    std::vector< RIBConverterBase* >::iterator iter;
    for (iter = this->converters.begin(); iter != this->converters.end(); iter ++)
      {
        if (strcmp(headerMsg->GetDeviceType(), (*iter)->messageTypeString()) == 0)
          {
            (*iter)->onIGTLMessage(headerMsg);
            break;
          }
      }
    if (iter == this->converters.end())
      {
        socket->Skip(headerMsg->GetBodySizeToRead(),0);
      }
    }
}

void ROS_IGTL_Bridge::AddConverter(RIBConverterBase* converter, uint32_t size, const char* topicPublish, const char* topicSubscribe)
{
  converter->setup(this->nh, this->socket, size);
  converter->publish(topicPublish);
  converter->subscribe(topicSubscribe);
  this->converters.push_back(converter);
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com>
**
****************************************************************************/

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQmlEngine>
#include <QtQml>
#include <QTimer>
#include <QTranslator>
#include <QDir>
#include <QScreen>
#include <QDBusConnection>

//#include "qdeclarativemozview.h"
#include "quickmozview.h"
#include "qmozcontext.h"

#include "declarativebookmarkmodel.h"
#include "declarativewebutils.h"
#include "browserservice.h"
#include "downloadmanager.h"
#include "settingmanager.h"
#include "closeeventfilter.h"
#include "declarativetab.h"
#include "declarativetabmodel.h"
#include "declarativehistorymodel.h"

#include <signonuiservice.h>

#ifdef HAS_BOOSTER
#include <MDeclarativeCache>
#endif

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    // EGL FPS are lower with threaded render loop
    // that's why this workaround.
    // See JB#7358
    setenv("QML_BAD_GUI_RENDER_LOOP", "1", 1);
    setenv("USE_ASYNC", "1", 1);
#ifdef HAS_BOOSTER
    QScopedPointer<QGuiApplication> app(MDeclarativeCache::qApplication(argc, argv));
    QScopedPointer<QQuickView> view(MDeclarativeCache::qQuickView());
#else
    QScopedPointer<QGuiApplication> app(new QGuiApplication(argc, argv));
    QScopedPointer<QQuickView> view(new QQuickView);
#endif
    app->setQuitOnLastWindowClosed(false);

    // TODO : Remove this and set custom user agent always
    // Don't set custom user agent string when arguments contains -developerMode, give url as last argument
    if (!app->arguments().contains("-developerMode")) {
        setenv("CUSTOM_UA", "Mozilla/5.0 (Linux; U; Jolla; Sailfish; Mobile; rv:20.0) Gecko/20.0 Firefox/20.0 Sailfish Browser/1.0 Mobile", 1);
    }

    BrowserService *service = new BrowserService(app.data());
    // Handle command line launch
    if (!service->registered()) {
        QDBusMessage message = QDBusMessage::createMethodCall(service->serviceName(), "/",
                                                              service->serviceName(), "openUrl");
        QStringList args;
        // Pass url argument if given
        if (app->arguments().count() > 1) {
            args << app->arguments().at(1);
        }
        message.setArguments(QVariantList() << args);

        QDBusConnection::sessionBus().asyncCall(message);
        if (QCoreApplication::hasPendingEvents()) {
            QCoreApplication::processEvents();
        }

        return 0;
    }

    //% "Browser"
    QT_TRID_NOOP("sailfish-browser-ap-name");

    QString translationPath("/usr/share/translations/");
    QTranslator engineeringEnglish;
    engineeringEnglish.load("sailfish-browser_eng_en", translationPath);
    qApp->installTranslator(&engineeringEnglish);

    QTranslator translator;
    translator.load(QLocale(), "sailfish-browser", "-", translationPath);
    qApp->installTranslator(&translator);

    // We want to have SignonUI in process, if user wants to create account from Browser
    SignonUiService ssoui(0, true); // in process
    ssoui.setInProcessServiceName(QLatin1String("org.sailfishos.browser"));
    ssoui.setInProcessObjectPath(QLatin1String("/JollaBrowserSignonUi"));

    QDBusConnection sessionBus = QDBusConnection::sessionBus();
    bool registeredService = sessionBus.registerService(QLatin1String("org.sailfishos.browser"));
    bool registeredObject = sessionBus.registerObject(QLatin1String("/JollaBrowserSignonUi"), &ssoui,
            QDBusConnection::ExportAllContents);

    if (!registeredService || !registeredObject) {
        qWarning() << Q_FUNC_INFO << "CRITICAL: unable to register signon ui service:"
                   << QLatin1String("org.sailfishos.browser") << "at object path:"
                   << QLatin1String("/JollaBrowserSignonUi");
    }

    view->rootContext()->setContextProperty("jolla_signon_ui_service", &ssoui);

    qmlRegisterType<DeclarativeBookmarkModel>("Sailfish.Browser", 1, 0, "BookmarkModel");
    qmlRegisterType<DeclarativeTabModel>("Sailfish.Browser", 1, 0, "TabModel");
    qmlRegisterType<DeclarativeHistoryModel>("Sailfish.Browser", 1, 0, "HistoryModel");
    qmlRegisterType<DeclarativeTab>("Sailfish.Browser", 1, 0, "Tab");

    QString componentPath(DEFAULT_COMPONENTS_PATH);
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteBinComponents.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteJSComponents.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteJSScripts.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteOverrides.manifest"));

    app->setApplicationName(QString("sailfish-browser"));
    app->setOrganizationName(QString("org.sailfishos"));

    DeclarativeWebUtils * utils = new DeclarativeWebUtils(app->arguments(), service, app.data());
    view->rootContext()->setContextProperty("WebUtils", utils);
    view->rootContext()->setContextProperty("MozContext", QMozContext::GetInstance());

    DownloadManager  * dlMgr = new DownloadManager(service, app.data());
    CloseEventFilter * clsEventFilter = new CloseEventFilter(dlMgr, app.data());
    view->installEventFilter(clsEventFilter);
    QObject::connect(service, SIGNAL(openUrlRequested(QString)),
                     clsEventFilter, SLOT(cancelStopApplication()));

    SettingManager * settingMgr = new SettingManager(app.data());
    QObject::connect(QMozContext::GetInstance(), SIGNAL(onInitialized()),
                     settingMgr, SLOT(initialize()));

    QObject::connect(QMozContext::GetInstance(), SIGNAL(newWindowRequested(QString,uint,QNewWindowResponse*)),
                     utils, SLOT(openUrl(QString)));

    bool isDesktop = qApp->arguments().contains("-desktop");

    QString path;
    if (isDesktop) {
        path = qApp->applicationDirPath() + QDir::separator();
    } else {
        path = QString(DEPLOYMENT_PATH);
    }
    view->setSource(QUrl::fromLocalFile(path+"browser.qml"));
    view->showFullScreen();

    // Setup embedding
    QTimer::singleShot(0, QMozContext::GetInstance(), SLOT(runEmbedding()));

    return app->exec();
}
<commit_msg>[sailfish-browser] Update for custom user agent. Contributes to JB#8552<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com>
**
****************************************************************************/

#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQmlEngine>
#include <QtQml>
#include <QTimer>
#include <QTranslator>
#include <QDir>
#include <QScreen>
#include <QDBusConnection>

//#include "qdeclarativemozview.h"
#include "quickmozview.h"
#include "qmozcontext.h"

#include "declarativebookmarkmodel.h"
#include "declarativewebutils.h"
#include "browserservice.h"
#include "downloadmanager.h"
#include "settingmanager.h"
#include "closeeventfilter.h"
#include "declarativetab.h"
#include "declarativetabmodel.h"
#include "declarativehistorymodel.h"

#include <signonuiservice.h>

#ifdef HAS_BOOSTER
#include <MDeclarativeCache>
#endif

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    // EGL FPS are lower with threaded render loop
    // that's why this workaround.
    // See JB#7358
    setenv("QML_BAD_GUI_RENDER_LOOP", "1", 1);
    setenv("USE_ASYNC", "1", 1);
#ifdef HAS_BOOSTER
    QScopedPointer<QGuiApplication> app(MDeclarativeCache::qApplication(argc, argv));
    QScopedPointer<QQuickView> view(MDeclarativeCache::qQuickView());
#else
    QScopedPointer<QGuiApplication> app(new QGuiApplication(argc, argv));
    QScopedPointer<QQuickView> view(new QQuickView);
#endif
    app->setQuitOnLastWindowClosed(false);

    // TODO : Remove this and set custom user agent always
    // Don't set custom user agent string when arguments contains -developerMode, give url as last argument
    if (!app->arguments().contains("-developerMode")) {
        setenv("CUSTOM_UA", "Mozilla/5.0 (Linux; U; Jolla; Sailfish; Mobile; rv:20.0) Gecko/20.0 Firefox/20.0 Sailfish Browser/1.0 like Safari/535.19", 1);
    }

    BrowserService *service = new BrowserService(app.data());
    // Handle command line launch
    if (!service->registered()) {
        QDBusMessage message = QDBusMessage::createMethodCall(service->serviceName(), "/",
                                                              service->serviceName(), "openUrl");
        QStringList args;
        // Pass url argument if given
        if (app->arguments().count() > 1) {
            args << app->arguments().at(1);
        }
        message.setArguments(QVariantList() << args);

        QDBusConnection::sessionBus().asyncCall(message);
        if (QCoreApplication::hasPendingEvents()) {
            QCoreApplication::processEvents();
        }

        return 0;
    }

    //% "Browser"
    QT_TRID_NOOP("sailfish-browser-ap-name");

    QString translationPath("/usr/share/translations/");
    QTranslator engineeringEnglish;
    engineeringEnglish.load("sailfish-browser_eng_en", translationPath);
    qApp->installTranslator(&engineeringEnglish);

    QTranslator translator;
    translator.load(QLocale(), "sailfish-browser", "-", translationPath);
    qApp->installTranslator(&translator);

    // We want to have SignonUI in process, if user wants to create account from Browser
    SignonUiService ssoui(0, true); // in process
    ssoui.setInProcessServiceName(QLatin1String("org.sailfishos.browser"));
    ssoui.setInProcessObjectPath(QLatin1String("/JollaBrowserSignonUi"));

    QDBusConnection sessionBus = QDBusConnection::sessionBus();
    bool registeredService = sessionBus.registerService(QLatin1String("org.sailfishos.browser"));
    bool registeredObject = sessionBus.registerObject(QLatin1String("/JollaBrowserSignonUi"), &ssoui,
            QDBusConnection::ExportAllContents);

    if (!registeredService || !registeredObject) {
        qWarning() << Q_FUNC_INFO << "CRITICAL: unable to register signon ui service:"
                   << QLatin1String("org.sailfishos.browser") << "at object path:"
                   << QLatin1String("/JollaBrowserSignonUi");
    }

    view->rootContext()->setContextProperty("jolla_signon_ui_service", &ssoui);

    qmlRegisterType<DeclarativeBookmarkModel>("Sailfish.Browser", 1, 0, "BookmarkModel");
    qmlRegisterType<DeclarativeTabModel>("Sailfish.Browser", 1, 0, "TabModel");
    qmlRegisterType<DeclarativeHistoryModel>("Sailfish.Browser", 1, 0, "HistoryModel");
    qmlRegisterType<DeclarativeTab>("Sailfish.Browser", 1, 0, "Tab");

    QString componentPath(DEFAULT_COMPONENTS_PATH);
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteBinComponents.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/components/EmbedLiteJSComponents.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteJSScripts.manifest"));
    QMozContext::GetInstance()->addComponentManifest(componentPath + QString("/chrome/EmbedLiteOverrides.manifest"));

    app->setApplicationName(QString("sailfish-browser"));
    app->setOrganizationName(QString("org.sailfishos"));

    DeclarativeWebUtils * utils = new DeclarativeWebUtils(app->arguments(), service, app.data());
    view->rootContext()->setContextProperty("WebUtils", utils);
    view->rootContext()->setContextProperty("MozContext", QMozContext::GetInstance());

    DownloadManager  * dlMgr = new DownloadManager(service, app.data());
    CloseEventFilter * clsEventFilter = new CloseEventFilter(dlMgr, app.data());
    view->installEventFilter(clsEventFilter);
    QObject::connect(service, SIGNAL(openUrlRequested(QString)),
                     clsEventFilter, SLOT(cancelStopApplication()));

    SettingManager * settingMgr = new SettingManager(app.data());
    QObject::connect(QMozContext::GetInstance(), SIGNAL(onInitialized()),
                     settingMgr, SLOT(initialize()));

    QObject::connect(QMozContext::GetInstance(), SIGNAL(newWindowRequested(QString,uint,QNewWindowResponse*)),
                     utils, SLOT(openUrl(QString)));

    bool isDesktop = qApp->arguments().contains("-desktop");

    QString path;
    if (isDesktop) {
        path = qApp->applicationDirPath() + QDir::separator();
    } else {
        path = QString(DEPLOYMENT_PATH);
    }
    view->setSource(QUrl::fromLocalFile(path+"browser.qml"));
    view->showFullScreen();

    // Setup embedding
    QTimer::singleShot(0, QMozContext::GetInstance(), SLOT(runEmbedding()));

    return app->exec();
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id:   AliAODPWG4ParticleCorrelation.h $ */

//-------------------------------------------------------------------------
//     AOD class for photon and other particles storage and
//     correlation studies
//     Author: Yves Schutz, CERN, Gustavo Conesa, INFN
//-------------------------------------------------------------------------

//-- ROOT system --

//-- Analysis system
#include "AliAODPWG4ParticleCorrelation.h"

ClassImp(AliAODPWG4ParticleCorrelation)

//______________________________________________________________________________
 AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation() :
   AliAODPWG4Particle(), fIsolated(kFALSE),
   fLeadingDetector(""), fLeading(), fCorrJet(),  fCorrBkg(), fRefJet(0),
   fListOfObjArrays(new TList)
{
  // constructor
}

//______________________________________________________________________________
AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(Double_t px, Double_t py, Double_t pz, Double_t e):
  AliAODPWG4Particle(), fIsolated(kFALSE),
  fLeadingDetector(""),  fLeading(), fCorrJet(),
  fCorrBkg(), fRefJet(0),  fListOfObjArrays(new TList)
{
  // constructor
  SetMomentum(new TLorentzVector(px, py, pz, e));
}

//______________________________________________________________________________
AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(TLorentzVector & p):
  AliAODPWG4Particle(p), fIsolated(kFALSE),
  fLeadingDetector(""),  fLeading(), fCorrJet(), fCorrBkg(), fRefJet(0),  fListOfObjArrays(new TList)
{
  // constructor
}

//______________________________________________________________________________
AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(AliAODPWG4Particle & p):
  AliAODPWG4Particle(p), fIsolated(kFALSE),
  fLeadingDetector(""),  fLeading(), fCorrJet(), fCorrBkg(),fRefJet(0),   fListOfObjArrays(new TList)
{
  // constructor

}

//______________________________________________________________________________
AliAODPWG4ParticleCorrelation::~AliAODPWG4ParticleCorrelation()
{
  // destructor
  if(fListOfObjArrays){
    fListOfObjArrays->Clear();
    delete   fListOfObjArrays ;
  }
}

//______________________________________________________________________________
AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(const AliAODPWG4ParticleCorrelation& part) :
  AliAODPWG4Particle(part), fIsolated(part.fIsolated),
  fLeadingDetector(part.fLeadingDetector), fLeading(part.fLeading),
  fCorrJet(part.fCorrJet), fCorrBkg(part.fCorrBkg), fRefJet(part.fRefJet),
  fListOfObjArrays()
{
  // Copy constructor

}

//______________________________________________________________________________
//AliAODPWG4ParticleCorrelation& AliAODPWG4ParticleCorrelation::operator=(const AliAODPWG4ParticleCorrelation& part)
//{
//  // Assignment operator
//  if(this!=&part) {
//
//    fIsolated = part.fIsolated;
//    fRefJet   = part.fRefJet ;
//    fLeadingDetector =part.fLeadingDetector;
//    fLeading  = part.fLeading;
//    fCorrJet  = part.fCorrJet ;
//    fCorrBkg  = part.fCorrBkg;
//    fListOfObjArrays = fListOfObjArrays;
//
//  }
//
//  return *this;
//}

//______________________________________________________________________________
void AliAODPWG4ParticleCorrelation::Print(Option_t* /*option*/) const
{
  // Print information of all data members
  AliAODPWG4Particle::Print("");

  if(fIsolated) printf("Isolated! \n");

  if(GetJet()) GetJet()->Print("");

  printf("Leading Detector : %s\n",fLeadingDetector.Data());
  printf("Leading Particle 4-vector:\n");
  printf("     E  = %13.3f",   fLeading.E() );
  printf("     Px = %13.3f",   fLeading.Px());
  printf("     Py = %13.3f",   fLeading.Py());
  printf("     Pz = %13.3f\n", fLeading.Pz());

  if( fListOfObjArrays)   fListOfObjArrays->Print("");
}
<commit_msg> Set Ownership to avoid mem leaking<commit_after>/**************************************************************************
 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id:   AliAODPWG4ParticleCorrelation.h $ */

//-------------------------------------------------------------------------
//     AOD class for photon and other particles storage and
//     correlation studies
//     Author: Yves Schutz, CERN, Gustavo Conesa, INFN
//-------------------------------------------------------------------------

//-- ROOT system --

//-- Analysis system
#include "AliAODPWG4ParticleCorrelation.h"

ClassImp(AliAODPWG4ParticleCorrelation)

//______________________________________________________________________________
 AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation() :
   AliAODPWG4Particle(), fIsolated(kFALSE),
   fLeadingDetector(""), fLeading(), fCorrJet(),  fCorrBkg(), fRefJet(0),
   fListOfObjArrays(new TList)
{
  // constructor
  fListOfObjArrays->SetOwner(kTRUE);
}

//______________________________________________________________________________
AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(Double_t px, Double_t py, Double_t pz, Double_t e):
  AliAODPWG4Particle(), fIsolated(kFALSE),
  fLeadingDetector(""),  fLeading(), fCorrJet(),
  fCorrBkg(), fRefJet(0),  fListOfObjArrays(new TList)
{
  // constructor
  SetMomentum(new TLorentzVector(px, py, pz, e));
  fListOfObjArrays->SetOwner(kTRUE);

}

//______________________________________________________________________________
AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(TLorentzVector & p):
  AliAODPWG4Particle(p), fIsolated(kFALSE),
  fLeadingDetector(""),  fLeading(), fCorrJet(), fCorrBkg(), fRefJet(0),  fListOfObjArrays(new TList)
{
  // constructor
  fListOfObjArrays->SetOwner(kTRUE);

}

//______________________________________________________________________________
AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(AliAODPWG4Particle & p):
  AliAODPWG4Particle(p), fIsolated(kFALSE),
  fLeadingDetector(""),  fLeading(), fCorrJet(), fCorrBkg(),fRefJet(0),   fListOfObjArrays(new TList)
{
  // constructor
  fListOfObjArrays->SetOwner(kTRUE);

}

//______________________________________________________________________________
AliAODPWG4ParticleCorrelation::~AliAODPWG4ParticleCorrelation()
{
  // destructor
  if(fListOfObjArrays){
    fListOfObjArrays->Clear();
    delete   fListOfObjArrays ;
  }
}

//______________________________________________________________________________
AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(const AliAODPWG4ParticleCorrelation& part) :
  AliAODPWG4Particle(part), fIsolated(part.fIsolated),
  fLeadingDetector(part.fLeadingDetector), fLeading(part.fLeading),
  fCorrJet(part.fCorrJet), fCorrBkg(part.fCorrBkg), fRefJet(part.fRefJet),
  fListOfObjArrays()
{
  // Copy constructor

}

//______________________________________________________________________________
//AliAODPWG4ParticleCorrelation& AliAODPWG4ParticleCorrelation::operator=(const AliAODPWG4ParticleCorrelation& part)
//{
//  // Assignment operator
//  if(this!=&part) {
//
//    fIsolated = part.fIsolated;
//    fRefJet   = part.fRefJet ;
//    fLeadingDetector =part.fLeadingDetector;
//    fLeading  = part.fLeading;
//    fCorrJet  = part.fCorrJet ;
//    fCorrBkg  = part.fCorrBkg;
//    fListOfObjArrays = fListOfObjArrays;
//
//  }
//
//  return *this;
//}

//______________________________________________________________________________
void AliAODPWG4ParticleCorrelation::Print(Option_t* /*option*/) const
{
  // Print information of all data members
  AliAODPWG4Particle::Print("");

  if(fIsolated) printf("Isolated! \n");

  if(GetJet()) GetJet()->Print("");

  printf("Leading Detector : %s\n",fLeadingDetector.Data());
  printf("Leading Particle 4-vector:\n");
  printf("     E  = %13.3f",   fLeading.E() );
  printf("     Px = %13.3f",   fLeading.Px());
  printf("     Py = %13.3f",   fLeading.Py());
  printf("     Pz = %13.3f\n", fLeading.Pz());

  if( fListOfObjArrays)   fListOfObjArrays->Print("");
}
<|endoftext|>


<commit_before>#include <memory>

#include <Box2D/Dynamics/b2World.h>
#include <Box2D/Dynamics/b2Body.h>

#include <duktape.h>

#include "dukdemo/scripting/util.h"
#include "dukdemo/scripting/World.h"
#include "dukdemo/scripting/loaders.h"

namespace dukdemo {
namespace scripting {
namespace world {

void
init(duk_context* pContext)
{
	duk_push_c_function(pContext, constructor, 1); // [ctor].

	// Initialise prototype.
	auto const prototypeIdx = duk_push_object(pContext); // [ctor, proto].
#define PUSH_METHOD(method, nargs) \
	duk_push_c_function(pContext, methods::method, nargs); \
	duk_put_prop_string(pContext, prototypeIdx, #method)

	PUSH_METHOD(setGravity, 2);
	PUSH_METHOD(getGravity, 1);
#undef PUSH_METHOD

	duk_dup(pContext, prototypeIdx); // [ctor, proto, proto].

	// Store the prototype globally under a hidden symbol.
	duk_put_global_string(pContext, g_worldProtoSym); // [ctor, proto].

	// Store the prototype on the constructor.
	duk_put_prop_string(pContext, -2, "prototype"); // [ctor].

	// Put the constructor on the global object.
	duk_put_global_string(pContext, g_worldCtorSym); // [].
}

b2World*
getOwnWorldPtr(duk_context* pContext)
{
	return static_cast<b2World*>(
		getPointerFromThis(pContext, g_ownWorldPtrSym));
}

void
initialiseWorldObject(duk_context* pContext, duk_idx_t objIdx, b2World* pWorld)
{
	assert(objIdx >= 0 && "Index must be non-negative");
	duk_get_global_string(pContext, g_worldProtoSym);
	duk_set_prototype(pContext, objIdx);
	duk_push_pointer(pContext, pWorld);
	duk_put_prop_string(pContext, objIdx, g_ownWorldPtrSym);
}

duk_idx_t
pushWorldWithoutFinalizer(duk_context* pContext, b2World* pWorld)
{
	auto const worldIdx = duk_push_object(pContext);
	initialiseWorldObject(pContext, worldIdx, pWorld);
	return worldIdx;
}

duk_idx_t
pushWorldWithFinalizer(duk_context* pContext, std::unique_ptr<b2World> pWorld)
{
	auto const objIdx = pushWorldWithoutFinalizer(pContext, pWorld.get());
	duk_push_c_function(pContext, finalizer, 1);
	duk_set_finalizer(pContext, -2);
	pWorld.release();
	return objIdx;
}

duk_ret_t
constructor(duk_context* pContext)
{
	if (!duk_is_constructor_call(pContext))
	{
		return DUK_RET_TYPE_ERROR;
	}

	b2Vec2 gravity{0.0f, 0.0f};
	if (!loadVec2(pContext, 0, &gravity))
	{
		return DUK_RET_TYPE_ERROR;
	}

	auto pWorld = std::make_unique<b2World>(gravity);
	duk_push_this(pContext);
	initialiseWorldObject(pContext, 1, pWorld.get());
	duk_push_c_function(pContext, finalizer, 1);
	duk_set_finalizer(pContext, -2);
	pWorld.release();
	return 0;
}

duk_ret_t
finalizer(duk_context* pContext)
{
	duk_get_prop_string(pContext, 0, g_ownWorldPtrSym);
	auto* const pWorld = static_cast<b2World*>(duk_get_pointer(pContext, 1));
	duk_pop(pContext);

	// If the world pointer is null, we're finalising something which has
	// already been destroyed, or the prototype itself, so can bail out.
	if (pWorld == nullptr)
	{
		return 0;
	}

	// Replace the world's internal pointer with a nullptr.
	duk_push_pointer(pContext, nullptr);
	duk_put_prop_string(pContext, 0, g_ownWorldPtrSym);
	pWorld->~b2World();
	return 0;
}

duk_ret_t
methods::setGravity(duk_context* pContext)
{
	assert(duk_is_number(pContext, 0) && duk_is_number(pContext, 1) &&
		"setGravity requires two arguments");
	b2Vec2 vec{
		float(duk_get_number(pContext, 0)),
		float(duk_get_number(pContext, 1))
	};
	duk_pop_2(pContext);

	auto* const pWorld = getOwnWorldPtr(pContext);
	pWorld->SetGravity(vec);
	return 0;
}

duk_ret_t
methods::getGravity(duk_context* pContext)
{
	assert(duk_is_array(pContext, 0) && "getGravity requires array argument");
	auto const* const pWorld = getOwnWorldPtr(pContext);
	writeVec2ToArray(pContext, 0, pWorld->GetGravity());
	return 1;
}

} // namespace world
} // namespace scripting
} // namespace dukdemo
<commit_msg>Add World#createBody<commit_after>#include <memory>

#include <Box2D/Dynamics/b2World.h>
#include <Box2D/Dynamics/b2Body.h>

#include <duktape.h>

#include "dukdemo/scripting/util.h"
#include "dukdemo/scripting/Body.h"
#include "dukdemo/scripting/World.h"
#include "dukdemo/scripting/loaders.h"

namespace dukdemo {
namespace scripting {
namespace world {

void
init(duk_context* pContext)
{
	duk_push_c_function(pContext, constructor, 1); // [ctor].

	// Initialise prototype.
	auto const prototypeIdx = duk_push_object(pContext); // [ctor, proto].
#define PUSH_METHOD(method, nargs) \
	duk_push_c_function(pContext, methods::method, nargs); \
	duk_put_prop_string(pContext, prototypeIdx, #method)

	PUSH_METHOD(setGravity, 2);
	PUSH_METHOD(getGravity, 1);
#undef PUSH_METHOD

	duk_dup(pContext, prototypeIdx); // [ctor, proto, proto].

	// Store the prototype globally under a hidden symbol.
	duk_put_global_string(pContext, g_worldProtoSym); // [ctor, proto].

	// Store the prototype on the constructor.
	duk_put_prop_string(pContext, -2, "prototype"); // [ctor].

	// Put the constructor on the global object.
	duk_put_global_string(pContext, g_worldCtorSym); // [].
}

b2World*
getOwnWorldPtr(duk_context* pContext)
{
	return static_cast<b2World*>(
		getPointerFromThis(pContext, g_ownWorldPtrSym));
}

void
initialiseWorldObject(duk_context* pContext, duk_idx_t objIdx, b2World* pWorld)
{
	assert(objIdx >= 0 && "Index must be non-negative");
	duk_get_global_string(pContext, g_worldProtoSym);
	duk_set_prototype(pContext, objIdx);
	duk_push_pointer(pContext, pWorld);
	duk_put_prop_string(pContext, objIdx, g_ownWorldPtrSym);
}

duk_idx_t
pushWorldWithoutFinalizer(duk_context* pContext, b2World* pWorld)
{
	auto const worldIdx = duk_push_object(pContext);
	initialiseWorldObject(pContext, worldIdx, pWorld);
	return worldIdx;
}

duk_idx_t
pushWorldWithFinalizer(duk_context* pContext, std::unique_ptr<b2World> pWorld)
{
	auto const objIdx = pushWorldWithoutFinalizer(pContext, pWorld.get());
	duk_push_c_function(pContext, finalizer, 1);
	duk_set_finalizer(pContext, -2);
	pWorld.release();
	return objIdx;
}

duk_ret_t
constructor(duk_context* pContext)
{
	if (!duk_is_constructor_call(pContext))
	{
		return DUK_RET_TYPE_ERROR;
	}

	b2Vec2 gravity{0.0f, 0.0f};
	if (!loadVec2(pContext, 0, &gravity))
	{
		return DUK_RET_TYPE_ERROR;
	}

	auto pWorld = std::make_unique<b2World>(gravity);
	duk_push_this(pContext);
	initialiseWorldObject(pContext, 1, pWorld.get());
	duk_push_c_function(pContext, finalizer, 1);
	duk_set_finalizer(pContext, -2);
	pWorld.release();
	return 0;
}

duk_ret_t
finalizer(duk_context* pContext)
{
	duk_get_prop_string(pContext, 0, g_ownWorldPtrSym);
	auto* const pWorld = static_cast<b2World*>(duk_get_pointer(pContext, 1));
	duk_pop(pContext);

	// If the world pointer is null, we're finalising something which has
	// already been destroyed, or the prototype itself, so can bail out.
	if (pWorld == nullptr)
	{
		return 0;
	}

	// Replace the world's internal pointer with a nullptr.
	duk_push_pointer(pContext, nullptr);
	duk_put_prop_string(pContext, 0, g_ownWorldPtrSym);
	pWorld->~b2World();
	return 0;
}

duk_ret_t
methods::setGravity(duk_context* pContext)
{
	assert(duk_is_number(pContext, 0) && duk_is_number(pContext, 1) &&
		"setGravity requires two arguments");
	b2Vec2 vec{
		float(duk_get_number(pContext, 0)),
		float(duk_get_number(pContext, 1))
	};
	duk_pop_2(pContext);

	auto* const pWorld = getOwnWorldPtr(pContext);
	pWorld->SetGravity(vec);
	return 0;
}

duk_ret_t
methods::getGravity(duk_context* pContext)
{
	assert(duk_is_array(pContext, 0) && "getGravity requires array argument");
	auto const* const pWorld = getOwnWorldPtr(pContext);
	writeVec2ToArray(pContext, 0, pWorld->GetGravity());
	return 1;
}

duk_ret_t
methods::createBody(duk_context* pContext)
{
	// Stack: [bodyDef].
	b2BodyDef bodyDef;
	if (!loadBodyDef(pContext, 0, &bodyDef))
	{
		return DUK_RET_TYPE_ERROR;
	}
	duk_pop(pContext);

	// Create object.
	auto const bodyIdx = duk_push_object(pContext);
	// Stack: [body].

	// Set internal prototype to Body.prototype.
	duk_get_global_string(pContext, g_bodyProtoSym);
	duk_set_prototype(pContext, bodyIdx);
	// Stack: [body].

	// Get the world pointer.
	duk_push_this(pContext);
	duk_get_prop_string(pContext, -1, g_ownWorldPtrSym);
	// Stack: [body, world, pWorld].

	auto* const pWorld = static_cast<b2World*>(duk_get_pointer(pContext, -1));
	duk_pop(pContext);
	// Stack: [body, world].

	duk_put_prop_string(pContext, bodyIdx, g_ownWorldPropSym);
	// Stack: [body].

	// Create the b2Body and add to the JS object.
	auto* const pBody = pWorld->CreateBody(&bodyDef);
	duk_push_pointer(pContext, pBody);
	duk_put_prop_string(pContext, bodyIdx, g_ownWorldPtrSym);
	// Stack: [body].
	return 1;
}

duk_ret_t
methods::destroyBody(duk_context* pContext)
{
	body::destroyBodyAt(pContext, 0);
	return 0;
}

duk_ret_t
methods::toString(duk_context* pContext)
{
	duk_push_string(pContext, "[World]");
	return 1;
}

} // namespace world
} // namespace scripting
} // namespace dukdemo
<|endoftext|>


<commit_before>/// HEADER
#include "assign_feature_classifications.h"

/// PROJECT
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex_ml/features_message.h>
#include <csapex/msg/generic_vector_message.hpp>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>

CSAPEX_REGISTER_CLASS(csapex::AssignFeatureClassifications, csapex::Node)

using namespace csapex;
using namespace connection_types;

AssignFeatureClassifications::AssignFeatureClassifications()
{

}

void AssignFeatureClassifications::setup(NodeModifier &node_modifier)
{
    in_features_ = node_modifier.addInput<GenericVectorMessage, FeaturesMessage>("Features");
    in_labels_   = node_modifier.addOptionalInput<GenericVectorMessage, int>("Classifications");
    out_         = node_modifier.addOutput<GenericVectorMessage, FeaturesMessage>("Labelled features");
}

void AssignFeatureClassifications::setupParameters(Parameterizable &parameters)
{
    parameters.addParameter(param::ParameterFactory::declareRange("label", 0, 255, 0, 1),
                            label_);
}

void AssignFeatureClassifications::process()
{
    std::shared_ptr<std::vector<FeaturesMessage> const> in_features =
            msg::getMessage<GenericVectorMessage, FeaturesMessage>(in_features_);
    std::shared_ptr<std::vector<FeaturesMessage>> out_features;

    if(msg::hasMessage(in_labels_)) {
        std::shared_ptr<std::vector<int> const> in_labels = msg::getMessage<GenericVectorMessage, int>(in_labels_);

        if(in_features->size() != in_labels->size())
            throw std::runtime_error("Label count != FeatureMsg count!");

        for(std::size_t i = 0 ; i < in_features->size() ; ++i) {
            FeaturesMessage feature = in_features->at(i);
            int label = (int) in_labels->at(i);
            feature.classification = label;
            out_features->emplace_back(feature);
        }
    } else {
        for(FeaturesMessage feature : *in_features) {
            feature.classification = label_;
            out_features->emplace_back(feature);
        }
    }
    msg::publish<GenericVectorMessage, FeaturesMessage>(out_, out_features);
}
<commit_msg>segfault fixed<commit_after>/// HEADER
#include "assign_feature_classifications.h"

/// PROJECT
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex_ml/features_message.h>
#include <csapex/msg/generic_vector_message.hpp>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>

CSAPEX_REGISTER_CLASS(csapex::AssignFeatureClassifications, csapex::Node)

using namespace csapex;
using namespace connection_types;

AssignFeatureClassifications::AssignFeatureClassifications()
{

}

void AssignFeatureClassifications::setup(NodeModifier &node_modifier)
{
    in_features_ = node_modifier.addInput<GenericVectorMessage, FeaturesMessage>("Features");
    in_labels_   = node_modifier.addOptionalInput<GenericVectorMessage, int>("Classifications");
    out_         = node_modifier.addOutput<GenericVectorMessage, FeaturesMessage>("Labelled features");
}

void AssignFeatureClassifications::setupParameters(Parameterizable &parameters)
{
    parameters.addParameter(param::ParameterFactory::declareRange("label", 0, 255, 0, 1),
                            label_);
}

void AssignFeatureClassifications::process()
{
    std::shared_ptr<std::vector<FeaturesMessage> const> in_features =
            msg::getMessage<GenericVectorMessage, FeaturesMessage>(in_features_);
    std::shared_ptr<std::vector<FeaturesMessage>> out_features = std::make_shared<std::vector<FeaturesMessage>>();

    if(msg::hasMessage(in_labels_)) {
        std::shared_ptr<std::vector<int> const> in_labels = msg::getMessage<GenericVectorMessage, int>(in_labels_);

        if(in_features->size() != in_labels->size())
            throw std::runtime_error("Label count != FeatureMsg count!");

        for(std::size_t i = 0 ; i < in_features->size() ; ++i) {
            FeaturesMessage feature = in_features->at(i);
            int label = (int) in_labels->at(i);
            feature.classification = label;
            out_features->emplace_back(feature);
        }
    } else {
        for(FeaturesMessage feature : *in_features) {
            feature.classification = label_;
            out_features->emplace_back(feature);
        }
    }
    msg::publish<GenericVectorMessage, FeaturesMessage>(out_, out_features);
}
<|endoftext|>


<commit_before>#include "dsa_common.h"

#include "session.h"

#include "client.h"
#include "server.h"

#include "stream/ack_stream.h"

namespace dsa {

Session::Session(LinkStrandRef strand, const std::string &session_id)
    : _strand(std::move(strand)),
      _session_id(session_id),
      requester(*this),
      responder(*this),
      _ack_stream(new AckStream(get_ref())) {}

Session::~Session() = default;

void Session::connected(shared_ptr_<Connection> connection) {
  if (_connection != nullptr) {
    _connection->close();
  }
  _connection = std::move(connection);
}

void Session::close_impl() {
  requester.close_impl();
  responder.close_impl();
  if (_connection != nullptr) {
    _connection->close();
  }
  _ack_stream.reset();
}

void Session::disconnected(const shared_ptr_<Connection> &connection) {
  if (_connection.get() == connection.get()) {
    _connection.reset();
  }
}

void Session::check_pending_acks(int32_t ack) {
  while (!_pending_acks.empty()) {
    AckHolder &first = _pending_acks.front();
    uint32_t d = static_cast<uint32_t>(ack - first.ack);
    if (d < 0x10000000) {
      first.callback(true);
      _pending_acks.pop_front();
    } else {
      return;
    }
  }
}

void Session::receive_message(MessageRef &&message) {
  LOG_TRACE(_strand->logger(), LOG << "receive message: " << message->type());

  if (message->need_ack()) {
    _ack_stream->add_ack(message->get_ack_id());
  }
  if (message->type() == MessageType::ACK) {
    check_pending_acks(DOWN_CAST<AckMessage *>(message.get())->get_ack_id());
    return;
  }
  if (message->is_request()) {
    // responder receive request and send response
    responder.receive_message(std::move(message));
  } else {
    // requester sent request and receive response
    requester.receive_message(std::move(message));
  }
}

ref_<MessageStream> Session::get_next_ready_stream() {
  while (!_write_streams.empty()) {
    ref_<MessageStream> stream = std::move(_write_streams.front());
    _write_streams.pop_front();
    if (stream->peek_next_message_size(0) > 0) {
      return std::move(stream);
    }
  }
  return nullptr;
}

size_t Session::peek_next_message(size_t availible) {
  while (!_write_streams.empty()) {
    ref_<MessageStream> &stream = _write_streams.front();
    size_t size = stream->peek_next_message_size(availible);
    if (size > 0) {
      return size;
    }
    _write_streams.pop_front();
  }
  return 0;
}

void Session::write_loop(ref_<Session> sthis) {
  Connection *connection = sthis->_connection.get();
  if (connection == nullptr) {
    sthis->_is_writing = false;
    return;
  }

  size_t next_message_size =
      sthis->peek_next_message(connection->max_buffer_size());
  if (next_message_size == 0) {
    sthis->_is_writing = false;
    return;
  }

  sthis->_is_writing = true;
  std::vector<uint8_t> &buf = connection->_write_buffer;

  size_t total_size = 0;
  while (next_message_size > 0 &&
         total_size < connection->preferred_buffer_size() &&
         total_size + next_message_size < connection->max_buffer_size()) {
    auto stream = sthis->get_next_ready_stream();
    AckCallback ack_callback;
    MessageCRef message = stream->get_next_message(ack_callback);

    if (buf.size() < connection->max_buffer_size() &&
        total_size + message->size() > buf.size()) {
      buf.resize(buf.size() * 4);
    }

    ++sthis->_waiting_ack;
    if (ack_callback != nullptr) {
      sthis->_pending_acks.push_back(
          AckHolder(sthis->_waiting_ack, std::move(ack_callback)));
    }

    LOG_TRACE(sthis->_strand->logger(),
              LOG << "send message: " << message->type());

    message->write(&buf[total_size], stream->rid, sthis->_waiting_ack);
    total_size += message->size();

    next_message_size =
        sthis->peek_next_message(connection->max_buffer_size() - total_size);
  }

  connection->write(
      buf.data(),
      total_size, [sthis = std::move(sthis)](
                      const boost::system::error_code &error) mutable {
        LinkStrandRef strand = sthis->_strand;
        (*strand)()->dispatch([sthis = std::move(sthis)]() mutable {
          Session::write_loop(std::move(sthis));
        });
      });
}

void Session::write_stream(ref_<MessageStream> &&stream) {
  _write_streams.push_back(std::move(stream));
  if (!_is_writing) {
    write_loop(get_ref());
  }
}

}  // namespace dsa<commit_msg>remove preferred packet size optimization<commit_after>#include "dsa_common.h"

#include "session.h"

#include "client.h"
#include "server.h"

#include "stream/ack_stream.h"

namespace dsa {

Session::Session(LinkStrandRef strand, const std::string &session_id)
    : _strand(std::move(strand)),
      _session_id(session_id),
      requester(*this),
      responder(*this),
      _ack_stream(new AckStream(get_ref())) {}

Session::~Session() = default;

void Session::connected(shared_ptr_<Connection> connection) {
  if (_connection != nullptr) {
    _connection->close();
  }
  _connection = std::move(connection);
}

void Session::close_impl() {
  requester.close_impl();
  responder.close_impl();
  if (_connection != nullptr) {
    _connection->close();
  }
  _ack_stream.reset();
}

void Session::disconnected(const shared_ptr_<Connection> &connection) {
  if (_connection.get() == connection.get()) {
    _connection.reset();
  }
}

void Session::check_pending_acks(int32_t ack) {
  while (!_pending_acks.empty()) {
    AckHolder &first = _pending_acks.front();
    uint32_t d = static_cast<uint32_t>(ack - first.ack);
    if (d < 0x10000000) {
      first.callback(true);
      _pending_acks.pop_front();
    } else {
      return;
    }
  }
}

void Session::receive_message(MessageRef &&message) {
  LOG_TRACE(_strand->logger(), LOG << "receive message: " << message->type());

  if (message->need_ack()) {
    _ack_stream->add_ack(message->get_ack_id());
  }
  if (message->type() == MessageType::ACK) {
    check_pending_acks(DOWN_CAST<AckMessage *>(message.get())->get_ack_id());
    return;
  }
  if (message->is_request()) {
    // responder receive request and send response
    responder.receive_message(std::move(message));
  } else {
    // requester sent request and receive response
    requester.receive_message(std::move(message));
  }
}

ref_<MessageStream> Session::get_next_ready_stream() {
  while (!_write_streams.empty()) {
    ref_<MessageStream> stream = std::move(_write_streams.front());
    _write_streams.pop_front();
    if (stream->peek_next_message_size(0) > 0) {
      return std::move(stream);
    }
  }
  return nullptr;
}

size_t Session::peek_next_message(size_t availible) {
  while (!_write_streams.empty()) {
    ref_<MessageStream> &stream = _write_streams.front();
    size_t size = stream->peek_next_message_size(availible);
    if (size > 0) {
      return size;
    }
    _write_streams.pop_front();
  }
  return 0;
}

void Session::write_loop(ref_<Session> sthis) {
  Connection *connection = sthis->_connection.get();
  if (connection == nullptr) {
    sthis->_is_writing = false;
    return;
  }

  size_t next_message_size =
      sthis->peek_next_message(connection->max_buffer_size());
  if (next_message_size == 0) {
    sthis->_is_writing = false;
    return;
  }

  sthis->_is_writing = true;
  std::vector<uint8_t> &buf = connection->_write_buffer;

  size_t total_size = 0;
  while (next_message_size > 0 &&
         total_size + next_message_size < connection->max_buffer_size()) {
    auto stream = sthis->get_next_ready_stream();
    AckCallback ack_callback;
    MessageCRef message = stream->get_next_message(ack_callback);

    if (buf.size() < connection->max_buffer_size() &&
        total_size + message->size() > buf.size()) {
      buf.resize(buf.size() * 4);
    }

    ++sthis->_waiting_ack;
    if (ack_callback != nullptr) {
      sthis->_pending_acks.push_back(
          AckHolder(sthis->_waiting_ack, std::move(ack_callback)));
    }

    LOG_TRACE(sthis->_strand->logger(),
              LOG << "send message: " << message->type());

    message->write(&buf[total_size], stream->rid, sthis->_waiting_ack);
    total_size += message->size();

    next_message_size =
        sthis->peek_next_message(connection->max_buffer_size() - total_size);
  }

  connection->write(
      buf.data(),
      total_size, [sthis = std::move(sthis)](
                      const boost::system::error_code &error) mutable {
        LinkStrandRef strand = sthis->_strand;
        (*strand)()->dispatch([sthis = std::move(sthis)]() mutable {
          Session::write_loop(std::move(sthis));
        });
      });
}

void Session::write_stream(ref_<MessageStream> &&stream) {
  _write_streams.push_back(std::move(stream));
  if (!_is_writing) {
    write_loop(get_ref());
  }
}

}  // namespace dsa<|endoftext|>


<commit_before>/*
 *    _aaaa,  _aa.  sa,  aaa              _aaaa,_  ac  .aa.   .aa.  .aa,  _a, sa
 *  .wWV!!!T  |Wm;  dQ[  $WF            _mWT!"?Y  ]QE  :Q#:   ]QW[  :WWk. ]Q[ dW
 * .jWf       :WW: .dQ[  dQ[           .mW(       )WE  :Q#:  .mSQh. :mWQa.]W[ dQ
 * |QW:       :Wm;  mQ[  dQ[           ]Qk        )Qmi_aQW:  <B:$Qc :WBWQ()W[ dQ
 * |W#:  .ww  ;WW;  dQ[  dQ[  .......  ]Qk        )QB?YYW#:  jf ]Qp.:mE)Qm]Q[ )W
 * +WQ;  :Wm  |Wm; .mQ[  dQ[ :qgggggga ]Qm.       ]WE  :Q# :=QasuQm;:Wk 3QQW[ )Y
 *  ]Wmi.:Wm  +$Q; .mW(  dQ[  !"!!"!!^ dQk,  ._   ]WE  :Q# :3D"!!$Qc.Wk -$WQ[
 *   "?????? ` "?!=m?!   ??'            -??????!  -?!  -?? -?'   "?"-?"  "??' "?
 *
 * Copyright (c) 2004 darkbits                              Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of darkbits nor the     :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * 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.
 */

/*
 * For comments regarding functions please see the header file.
 */

#include "guichan/exception.hpp"
#include "guichan/font.hpp"
#include "guichan/sdl/sdlgraphics.hpp"
#include "guichan/sdl/sdlpixel.hpp"
#include "config.hpp"

#include <cmath>

namespace gcn
{

  void SDLGraphics::setTarget(SDL_Surface* target)
  {
    mTarget = target;
    Rectangle area;
    area.x = 0;
    area.y = 0;
    area.width = target->w;
    area.height = target->h;
    pushClipArea(area);

  } // end setTarget

  bool SDLGraphics::pushClipArea(Rectangle area)
  {
    SDL_Rect rect;
    bool result = Graphics::pushClipArea(area);

    ClipRectangle carea = mClipStack.top();
    rect.x = carea.x;
    rect.y = carea.y;
    rect.w = carea.width;
    rect.h = carea.height;

    SDL_SetClipRect(mTarget, &rect);

    return result;

  } // end pushClipArea

  void SDLGraphics::popClipArea()
  {
    SDL_Rect rect;
    Graphics::popClipArea();

    ClipRectangle carea = mClipStack.top();
    rect.x = carea.x;
    rect.y = carea.y;
    rect.w = carea.width;
    rect.h = carea.height;

    SDL_SetClipRect(mTarget, &rect);

  } // end popClipArea

  SDL_Surface* SDLGraphics::getTarget() const
  {
    return mTarget;

  } // end getTarget

  void SDLGraphics::drawImage(const Image* image, int srcX,
                              int srcY, int dstX, int dstY,
                              int width, int height)
  {
    ClipRectangle top = mClipStack.top();
    SDL_Rect src;
    SDL_Rect dst;
    src.x = srcX;
    src.y = srcY;
    src.w = width;
    src.h = height;
    dst.x = dstX + top.xOffset;
    dst.y = dstY + top.yOffset;

    SDL_Surface* srcImage = (SDL_Surface*)image->_getData();

    SDL_BlitSurface(srcImage, &src, mTarget, &dst);

  } // end drawImage

  void SDLGraphics::fillRectangle(const Rectangle& rectangle)
  {

    Rectangle area = rectangle;
    ClipRectangle top = mClipStack.top();
    area.x += top.xOffset;
    area.y += top.yOffset;

    if(!area.intersect(top))
    {
      return;
    }

    SDL_Rect rect;
    rect.x = area.x;
    rect.y = area.y;
    rect.w = area.width;
    rect.h = area.height;

    Uint32 color = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);
    SDL_FillRect(mTarget, &rect, color);

  } // end fillRectangle

  void SDLGraphics::drawPoint(int x, int y)
  {
    ClipRectangle top = mClipStack.top();
    x += top.xOffset;
    y += top.yOffset;

    if(!top.isPointInRect(x,y))
      return;

    SDLputPixel(mTarget, x, y, mColor);

  } // end drawPoint

  void SDLGraphics::drawHLine(int x1, int y, int x2)
  {
    ClipRectangle top = mClipStack.top();
    x1 += top.xOffset;
    y += top.yOffset;
    x2 += top.xOffset;

    if (y < top.y || y >= top.y + top.height)
      return;

    if (x1 > x2)
    {
      x1 ^= x2;
      x2 ^= x1;
      x1 ^= x2;
    }

    if (top.x > x1)
    {
      if (top.x > x2)
      {
        return;
      }
      x1 = top.x;
    }

    if (top.x + top.width <= x2)
    {
      if (top.x + top.width <= x1)
      {
        return;
      }
      x2 = top.x + top.width -1;
    }

    int bpp = mTarget->format->BytesPerPixel;

    SDL_LockSurface(mTarget);

    Uint8 *p = (Uint8 *)mTarget->pixels + y * mTarget->pitch + x1 * bpp;

    Uint32 pixel = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);

    switch(bpp) {
      case 1:
      {
        for (;x1 <= x2; ++x1)
        {
          *(p++) = pixel;
        }
      } break;

      case 2:
      {
        Uint16* q = (Uint16*)p;
        for (;x1 <= x2; ++x1)
        {
          *(q++) = pixel;
        }
      } break;

      case 3:
      {
        if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
          for (;x1 <= x2; ++x1)
          {
            p[0] = (pixel >> 16) & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = pixel & 0xff;
            p += 3;
          }
        }
        else
        {
          for (;x1 <= x2; ++x1)
          {
            p[0] = pixel & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = (pixel >> 16) & 0xff;
            p += 3;
          }
        }
      } break;

      case 4:
      {
        Uint32* q = (Uint32*)p;
        for (;x1 <= x2; ++x1)
        {
          *(q++) = pixel;
        }
      } break;
    } // end switch

    SDL_UnlockSurface(mTarget);

  } // end drawHLine

  void SDLGraphics::drawVLine(int x, int y1, int y2)
  {
    ClipRectangle top = mClipStack.top();
    x += top.xOffset;
    y1 += top.yOffset;
    y2 += top.yOffset;

    if (x < top.x || x >= top.x + top.width)
      return;

    if (y1 > y2)
    {
      y1 ^= y2;
      y2 ^= y1;
      y1 ^= y2;
    }

    if (top.y > y1)
    {
      if (top.y > y2)
      {
        return;
      }
      y1 = top.y;
    }

    if (top.y + top.height <= y2)
    {
      if (top.y + top.height <= y1)
      {
        return;
      }
      y2 = top.y + top.height - 1;
    }

    int bpp = mTarget->format->BytesPerPixel;

    SDL_LockSurface(mTarget);

    Uint8 *p = (Uint8 *)mTarget->pixels + y1 * mTarget->pitch + x * bpp;

    Uint32 pixel = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);

    switch(bpp) {
      case 1:
      {
        for (;y1 <= y2; ++y1)
        {
          *p = pixel;
          p += mTarget->pitch;
        }
      } break;

      case 2:
      {
        for (;y1 <= y2; ++y1)
        {
          *(Uint16*)p = pixel;
          p += mTarget->pitch;
        }
      } break;

      case 3:
      {
        if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
          for (;y1 <= y2; ++y1)
          {
            p[0] = (pixel >> 16) & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = pixel & 0xff;
            p += mTarget->pitch;
          }
        }
        else
        {
          for (;y1 <= y2; ++y1)
          {
            p[0] = pixel & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = (pixel >> 16) & 0xff;
            p += mTarget->pitch;
          }
        }
      } break;

      case 4:
      {
        for (;y1 <= y2; ++y1)
        {
          *(Uint32*)p = pixel;
          p += mTarget->pitch;
        }
      } break;
    } // end switch

    SDL_UnlockSurface(mTarget);

  } // end drawVLine

  void SDLGraphics::drawRectangle(const Rectangle& rectangle)
  {
    int x1 = rectangle.x;
    int x2 = rectangle.x + rectangle.width - 1;
    int y1 = rectangle.y;
    int y2 = rectangle.y + rectangle.height - 1;

    drawHLine(x1, y1, x2);
    drawHLine(x1, y2, x2);

    drawVLine(x1, y1, y2);
    drawVLine(x2, y1, y2);

  } // end drawRectangle

  void SDLGraphics::drawLine(int x1, int y1, int x2, int y2)
  {

    if (x1 == x2)
    {
      drawVLine(x1, y1, y2);
      return;
    }
    if (y1 == y2)
    {
      drawHLine(x1, y1, x2);
      return;
    }

    bool yLonger = false;
    int incrementVal;
    int endVal;

    int shortLen = y2 - y1;
    int longLen = x2 - x1;

    if (std::abs(shortLen) > std::abs(longLen))
    {
      int swap = shortLen;
      shortLen = longLen;
      longLen = swap;
      yLonger = true;
    }

    endVal = longLen;

    if (longLen< 0)
    {
      incrementVal = -1;
      longLen = - longLen;
    }
    else
    {
      incrementVal = 1;
    }

    double decInc;

    if (longLen == 0)
    {
      decInc = (double)shortLen;
    }
    else
    {
      decInc = (double)shortLen / (double)longLen;
    }

    double j = 0.0;

    if (yLonger)
    {
      for (int i = 0; i != endVal; i += incrementVal)
      {
        drawPoint(x1 + (int)j, y1 + i);
        j += decInc;
      }
    }
    else
    {
      for (int i = 0; i != endVal; i += incrementVal)
      {
        drawPoint(x1 + i, y1 + (int)j);
        j += decInc;
      }
    }
  } // end drawLine

} // end gcn
<commit_msg>Fixed drawLine to draw the last pixel.<commit_after>/*
 *    _aaaa,  _aa.  sa,  aaa              _aaaa,_  ac  .aa.   .aa.  .aa,  _a, sa
 *  .wWV!!!T  |Wm;  dQ[  $WF            _mWT!"?Y  ]QE  :Q#:   ]QW[  :WWk. ]Q[ dW
 * .jWf       :WW: .dQ[  dQ[           .mW(       )WE  :Q#:  .mSQh. :mWQa.]W[ dQ
 * |QW:       :Wm;  mQ[  dQ[           ]Qk        )Qmi_aQW:  <B:$Qc :WBWQ()W[ dQ
 * |W#:  .ww  ;WW;  dQ[  dQ[  .......  ]Qk        )QB?YYW#:  jf ]Qp.:mE)Qm]Q[ )W
 * +WQ;  :Wm  |Wm; .mQ[  dQ[ :qgggggga ]Qm.       ]WE  :Q# :=QasuQm;:Wk 3QQW[ )Y
 *  ]Wmi.:Wm  +$Q; .mW(  dQ[  !"!!"!!^ dQk,  ._   ]WE  :Q# :3D"!!$Qc.Wk -$WQ[
 *   "?????? ` "?!=m?!   ??'            -??????!  -?!  -?? -?'   "?"-?"  "??' "?
 *
 * Copyright (c) 2004 darkbits                              Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of darkbits nor the     :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * 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.
 */

/*
 * For comments regarding functions please see the header file.
 */

#include "guichan/exception.hpp"
#include "guichan/font.hpp"
#include "guichan/sdl/sdlgraphics.hpp"
#include "guichan/sdl/sdlpixel.hpp"
#include "config.hpp"

#include <cmath>

namespace gcn
{

  void SDLGraphics::setTarget(SDL_Surface* target)
  {
    mTarget = target;
    Rectangle area;
    area.x = 0;
    area.y = 0;
    area.width = target->w;
    area.height = target->h;
    pushClipArea(area);

  } // end setTarget

  bool SDLGraphics::pushClipArea(Rectangle area)
  {
    SDL_Rect rect;
    bool result = Graphics::pushClipArea(area);

    ClipRectangle carea = mClipStack.top();
    rect.x = carea.x;
    rect.y = carea.y;
    rect.w = carea.width;
    rect.h = carea.height;

    SDL_SetClipRect(mTarget, &rect);

    return result;

  } // end pushClipArea

  void SDLGraphics::popClipArea()
  {
    SDL_Rect rect;
    Graphics::popClipArea();

    ClipRectangle carea = mClipStack.top();
    rect.x = carea.x;
    rect.y = carea.y;
    rect.w = carea.width;
    rect.h = carea.height;

    SDL_SetClipRect(mTarget, &rect);

  } // end popClipArea

  SDL_Surface* SDLGraphics::getTarget() const
  {
    return mTarget;

  } // end getTarget

  void SDLGraphics::drawImage(const Image* image, int srcX,
                              int srcY, int dstX, int dstY,
                              int width, int height)
  {
    ClipRectangle top = mClipStack.top();
    SDL_Rect src;
    SDL_Rect dst;
    src.x = srcX;
    src.y = srcY;
    src.w = width;
    src.h = height;
    dst.x = dstX + top.xOffset;
    dst.y = dstY + top.yOffset;

    SDL_Surface* srcImage = (SDL_Surface*)image->_getData();

    SDL_BlitSurface(srcImage, &src, mTarget, &dst);

  } // end drawImage

  void SDLGraphics::fillRectangle(const Rectangle& rectangle)
  {

    Rectangle area = rectangle;
    ClipRectangle top = mClipStack.top();
    area.x += top.xOffset;
    area.y += top.yOffset;

    if(!area.intersect(top))
    {
      return;
    }

    SDL_Rect rect;
    rect.x = area.x;
    rect.y = area.y;
    rect.w = area.width;
    rect.h = area.height;

    Uint32 color = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);
    SDL_FillRect(mTarget, &rect, color);

  } // end fillRectangle

  void SDLGraphics::drawPoint(int x, int y)
  {
    ClipRectangle top = mClipStack.top();
    x += top.xOffset;
    y += top.yOffset;

    if(!top.isPointInRect(x,y))
      return;

    SDLputPixel(mTarget, x, y, mColor);

  } // end drawPoint

  void SDLGraphics::drawHLine(int x1, int y, int x2)
  {
    ClipRectangle top = mClipStack.top();
    x1 += top.xOffset;
    y += top.yOffset;
    x2 += top.xOffset;

    if (y < top.y || y >= top.y + top.height)
      return;

    if (x1 > x2)
    {
      x1 ^= x2;
      x2 ^= x1;
      x1 ^= x2;
    }

    if (top.x > x1)
    {
      if (top.x > x2)
      {
        return;
      }
      x1 = top.x;
    }

    if (top.x + top.width <= x2)
    {
      if (top.x + top.width <= x1)
      {
        return;
      }
      x2 = top.x + top.width -1;
    }

    int bpp = mTarget->format->BytesPerPixel;

    SDL_LockSurface(mTarget);

    Uint8 *p = (Uint8 *)mTarget->pixels + y * mTarget->pitch + x1 * bpp;

    Uint32 pixel = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);

    switch(bpp) {
      case 1:
      {
        for (;x1 <= x2; ++x1)
        {
          *(p++) = pixel;
        }
      } break;

      case 2:
      {
        Uint16* q = (Uint16*)p;
        for (;x1 <= x2; ++x1)
        {
          *(q++) = pixel;
        }
      } break;

      case 3:
      {
        if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
          for (;x1 <= x2; ++x1)
          {
            p[0] = (pixel >> 16) & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = pixel & 0xff;
            p += 3;
          }
        }
        else
        {
          for (;x1 <= x2; ++x1)
          {
            p[0] = pixel & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = (pixel >> 16) & 0xff;
            p += 3;
          }
        }
      } break;

      case 4:
      {
        Uint32* q = (Uint32*)p;
        for (;x1 <= x2; ++x1)
        {
          *(q++) = pixel;
        }
      } break;
    } // end switch

    SDL_UnlockSurface(mTarget);

  } // end drawHLine

  void SDLGraphics::drawVLine(int x, int y1, int y2)
  {
    ClipRectangle top = mClipStack.top();
    x += top.xOffset;
    y1 += top.yOffset;
    y2 += top.yOffset;

    if (x < top.x || x >= top.x + top.width)
      return;

    if (y1 > y2)
    {
      y1 ^= y2;
      y2 ^= y1;
      y1 ^= y2;
    }

    if (top.y > y1)
    {
      if (top.y > y2)
      {
        return;
      }
      y1 = top.y;
    }

    if (top.y + top.height <= y2)
    {
      if (top.y + top.height <= y1)
      {
        return;
      }
      y2 = top.y + top.height - 1;
    }

    int bpp = mTarget->format->BytesPerPixel;

    SDL_LockSurface(mTarget);

    Uint8 *p = (Uint8 *)mTarget->pixels + y1 * mTarget->pitch + x * bpp;

    Uint32 pixel = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);

    switch(bpp) {
      case 1:
      {
        for (;y1 <= y2; ++y1)
        {
          *p = pixel;
          p += mTarget->pitch;
        }
      } break;

      case 2:
      {
        for (;y1 <= y2; ++y1)
        {
          *(Uint16*)p = pixel;
          p += mTarget->pitch;
        }
      } break;

      case 3:
      {
        if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
          for (;y1 <= y2; ++y1)
          {
            p[0] = (pixel >> 16) & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = pixel & 0xff;
            p += mTarget->pitch;
          }
        }
        else
        {
          for (;y1 <= y2; ++y1)
          {
            p[0] = pixel & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = (pixel >> 16) & 0xff;
            p += mTarget->pitch;
          }
        }
      } break;

      case 4:
      {
        for (;y1 <= y2; ++y1)
        {
          *(Uint32*)p = pixel;
          p += mTarget->pitch;
        }
      } break;
    } // end switch

    SDL_UnlockSurface(mTarget);

  } // end drawVLine

  void SDLGraphics::drawRectangle(const Rectangle& rectangle)
  {
    int x1 = rectangle.x;
    int x2 = rectangle.x + rectangle.width - 1;
    int y1 = rectangle.y;
    int y2 = rectangle.y + rectangle.height - 1;

    drawHLine(x1, y1, x2);
    drawHLine(x1, y2, x2);

    drawVLine(x1, y1, y2);
    drawVLine(x2, y1, y2);

  } // end drawRectangle

  void SDLGraphics::drawLine(int x1, int y1, int x2, int y2)
  {
    int i;

    if (x1 == x2)
    {
      drawVLine(x1, y1, y2);
      return;
    }
    if (y1 == y2)
    {
      drawHLine(x1, y1, x2);
      return;
    }

    bool yLonger = false;
    int incrementVal;
    int endVal;

    int shortLen = y2 - y1;
    int longLen = x2 - x1;

    if (std::abs(shortLen) > std::abs(longLen))
    {
      int swap = shortLen;
      shortLen = longLen;
      longLen = swap;
      yLonger = true;
    }

    endVal = longLen;

    if (longLen< 0)
    {
      incrementVal = -1;
      longLen = - longLen;
    }
    else
    {
      incrementVal = 1;
    }

    double decInc;

    if (longLen == 0)
    {
      decInc = (double)shortLen;
    }
    else
    {
      decInc = (double)shortLen / (double)longLen;
    }

    double j = 0.0;

    if (yLonger)
    {
      for (i = 0; i != endVal; i += incrementVal)
      {
        drawPoint(x1 + (int)j, y1 + i);
        j += decInc;
      }
      drawPoint(x1 + (int)j, y1 + i);
    }
    else
    {
      for (i = 0; i != endVal; i += incrementVal)
      {
        drawPoint(x1 + i, y1 + (int)j);
        j += decInc;
      }
      drawPoint(x1 + i, y1 + (int)j);
    }
  } // end drawLine

} // end gcn
<|endoftext|>