<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#include <hpp/core/collision-validation.hh>

#include <hpp/fcl/collision.h>

#include <pinocchio/multibody/geometry.hpp>

#include <hpp/pinocchio/body.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/collision-object.hh>
#include <hpp/pinocchio/configuration.hh>

#include <hpp/core/relative-motion.hh>
#include <hpp/core/collision-validation-report.hh>
#include <hpp/core/relative-motion.hh>

namespace hpp {
  namespace core {
    namespace {
      inline std::size_t collide (const CollisionPairs_t::const_iterator& _colPair,
          const fcl::CollisionRequest& req, fcl::CollisionResult& res) {
        res.clear();
        return fcl::collide (
                    _colPair->first ->fcl (),
                    _colPair->second->fcl (),
                    req, res);
      }

      inline bool collide (const CollisionPairs_t& pairs,
         const fcl::CollisionRequest& req, fcl::CollisionResult& res,
         CollisionPairs_t::const_iterator& _col) {
        for (_col = pairs.begin (); _col != pairs.end (); ++_col)
          if (collide (_col, req, res) != 0)
            return true;
        return false;
      }

      inline CollisionPair_t makeCollisionPair (const DevicePtr_t& d, const se3::CollisionPair& p)
      {
        CollisionObjectConstPtr_t o1 (new pinocchio::CollisionObject(d, p.first));
        CollisionObjectConstPtr_t o2 (new pinocchio::CollisionObject(d, p.second));
        return CollisionPair_t (o1, o2);
      }
    }
    CollisionValidationPtr_t CollisionValidation::create
    (const DevicePtr_t& robot)
    {
      CollisionValidation* ptr = new CollisionValidation (robot);
      return CollisionValidationPtr_t (ptr);
    }

    bool CollisionValidation::validate (const Configuration_t& config,
                                        ValidationReportPtr_t& validationReport)
    {
      robot_->currentConfiguration (config);
      robot_->computeForwardKinematics ();
      robot_->updateGeometryPlacements ();

      fcl::CollisionResult collisionResult;
      CollisionPairs_t::const_iterator _col;
      if(computeAllContacts_){
        hppDout(notice,"collision validation, computeAllContacts, num of pairs : "<<collisionPairs_.size());
        bool firstCollision(true);
        AllCollisionsValidationReportPtr_t allReport;
        for (CollisionPairs_t::const_iterator _col = collisionPairs_.begin (); _col != collisionPairs_.end (); ++_col){
          fcl::CollisionResult collisionResult;
          if (collide (_col, collisionRequest_, collisionResult) != 0){
            hppDout(notice,"in collision :  "<<_col->first->name()<<" / "<<_col->second->name());
            CollisionValidationReportPtr_t report (new CollisionValidationReport);
            report->object1 = _col->first;
            report->object2 = _col->second;
            report->result = collisionResult;
            if(firstCollision){
              allReport = AllCollisionsValidationReportPtr_t(new AllCollisionsValidationReport);
              allReport->object1 = _col->first;
              allReport->object2 = _col->second;
              allReport->result = collisionResult;
              firstCollision = false;
            }
            allReport->collisionReports.push_back(report);
          }
        }
        validationReport=allReport;
        return firstCollision;
      }else{
        fcl::CollisionResult collisionResult;
        if (collide (collisionPairs_, collisionRequest_, collisionResult, _col)
            ||
            ( checkParameterized_ &&
              collide (parameterizedPairs_, collisionRequest_, collisionResult, _col)
            )) {
          CollisionValidationReportPtr_t report (new CollisionValidationReport);
          report->object1 = _col->first;
          report->object2 = _col->second;
          report->result = collisionResult;
          validationReport = report;
          return false;
        }
        return true;
      }
    }

    void CollisionValidation::addObstacle (const CollisionObjectConstPtr_t& object)
    {
      const JointVector_t& jv = robot_->getJointVector ();
      for (JointVector_t::const_iterator it = jv.begin (); it != jv.end ();
          ++it) {
        JointPtr_t joint = JointPtr_t (new Joint(**it));
        addObstacleToJoint (object, joint, false);
      }
    }

    void CollisionValidation::addObstacleToJoint (const CollisionObjectConstPtr_t& object,
                                     const JointPtr_t& joint, const bool includeChildren)
    {
        BodyPtr_t body = joint->linkedBody ();
        if (body) {
            const ObjectVector_t& bodyObjects = body->innerObjects ();
            for (ObjectVector_t::const_iterator itInner = bodyObjects.begin ();
                itInner != bodyObjects.end (); ++itInner) {
              // TODO: check the objects are not in same joint
              collisionPairs_.push_back (CollisionPair_t (*itInner, object));
            }
          }
        if(includeChildren) {
            for(std::size_t i=0; i<joint->numberChildJoints(); ++i){
                addObstacleToJoint (object, joint->childJoint(i),includeChildren);
            }
        }
    }

    void CollisionValidation::removeObstacleFromJoint
    (const JointPtr_t& joint, const CollisionObjectConstPtr_t& obstacle)
    {
      BodyPtr_t body = joint->linkedBody ();
      if (body) {
        const ObjectVector_t& bodyObjects = body->innerObjects ();
        for (ObjectVector_t::const_iterator itInner = bodyObjects.begin ();
            itInner != bodyObjects.end (); ++itInner) {
          CollisionPair_t colPair (*itInner, obstacle);
          std::size_t nbDelPairs = 0;
          CollisionPairs_t::iterator _collisionPair (collisionPairs_.begin());
          while ( (_collisionPair = std::find (_collisionPair, collisionPairs_.end(), colPair))
              != collisionPairs_.end()) {
            _collisionPair = collisionPairs_.erase (_collisionPair);
            ++nbDelPairs;
          }
          if (nbDelPairs == 0) {
            std::ostringstream oss;
            oss << "CollisionValidation::removeObstacleFromJoint: obstacle \""
                << obstacle->name () <<
                "\" is not registered as obstacle for joint \"" << joint->name ()
                << "\".";
            throw std::runtime_error (oss.str ());
          } else if (nbDelPairs >= 2) {
            hppDout (error, "obstacle "<< obstacle->name () <<
                     " was registered " << nbDelPairs
                     << " times as obstacle for joint " << joint->name ()
                     << ".");
          }
        }
      }
    }

    void CollisionValidation::filterCollisionPairs (const RelativeMotion::matrix_type& matrix)
    {
      // Loop over collision pairs and remove disabled ones.
      CollisionPairs_t::iterator _colPair = collisionPairs_.begin ();
      se3::JointIndex j1, j2;
      fcl::CollisionResult unused;
      while (_colPair != collisionPairs_.end ()) {
        j1 = _colPair->first ->jointIndex();
        j2 = _colPair->second->jointIndex();

        switch (matrix(j1, j2)) {
          case RelativeMotion::Parameterized:
              hppDout(info, "Parameterized collision pairs between "
                  << _colPair->first ->name() << " and "
                  << _colPair->second->name());
              parameterizedPairs_.push_back (*_colPair);
              _colPair = collisionPairs_.erase (_colPair);
              break;
          case RelativeMotion::Constrained:
              hppDout(info, "Disabling collision between "
                  << _colPair->first ->name() << " and "
                  << _colPair->second->name());
              if (collide (_colPair, collisionRequest_, unused) != 0) {
                hppDout(warning, "Disabling collision detection between two "
                    "body in collision.");
              }
              disabledPairs_.push_back (*_colPair);
              _colPair = collisionPairs_.erase (_colPair);
              break;
          case RelativeMotion::Unconstrained: ++_colPair; break;
          default:
            hppDout (warning, "RelativeMotionType not understood");
            ++_colPair;
            break;
        }
      }
    }

    CollisionValidation::CollisionValidation (const DevicePtr_t& robot) :
      collisionRequest_(1, false, false, 1, false, true, fcl::GST_INDEP),
      robot_ (robot),
      parameterizedPairs_(), disabledPairs_(),
      checkParameterized_(false),
      computeAllContacts_(false)
    {
      const se3::GeometryModel& model = robot->geomModel();
      const se3::GeometryData & data  = robot->geomData();

      for (std::size_t i = 0; i < model.collisionPairs.size(); ++i)
        if (data.activeCollisionPairs[i])
          collisionPairs_.push_back(
              makeCollisionPair(robot, model.collisionPairs[i])
              );
    }

  } // namespace core
} // namespace hpp
<commit_msg>collision-validation : remove redundant variable declaration<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#include <hpp/core/collision-validation.hh>

#include <hpp/fcl/collision.h>

#include <pinocchio/multibody/geometry.hpp>

#include <hpp/pinocchio/body.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/collision-object.hh>
#include <hpp/pinocchio/configuration.hh>

#include <hpp/core/relative-motion.hh>
#include <hpp/core/collision-validation-report.hh>
#include <hpp/core/relative-motion.hh>

namespace hpp {
  namespace core {
    namespace {
      inline std::size_t collide (const CollisionPairs_t::const_iterator& _colPair,
          const fcl::CollisionRequest& req, fcl::CollisionResult& res) {
        res.clear();
        return fcl::collide (
                    _colPair->first ->fcl (),
                    _colPair->second->fcl (),
                    req, res);
      }

      inline bool collide (const CollisionPairs_t& pairs,
         const fcl::CollisionRequest& req, fcl::CollisionResult& res,
         CollisionPairs_t::const_iterator& _col) {
        for (_col = pairs.begin (); _col != pairs.end (); ++_col)
          if (collide (_col, req, res) != 0)
            return true;
        return false;
      }

      inline CollisionPair_t makeCollisionPair (const DevicePtr_t& d, const se3::CollisionPair& p)
      {
        CollisionObjectConstPtr_t o1 (new pinocchio::CollisionObject(d, p.first));
        CollisionObjectConstPtr_t o2 (new pinocchio::CollisionObject(d, p.second));
        return CollisionPair_t (o1, o2);
      }
    }
    CollisionValidationPtr_t CollisionValidation::create
    (const DevicePtr_t& robot)
    {
      CollisionValidation* ptr = new CollisionValidation (robot);
      return CollisionValidationPtr_t (ptr);
    }

    bool CollisionValidation::validate (const Configuration_t& config,
                                        ValidationReportPtr_t& validationReport)
    {
      robot_->currentConfiguration (config);
      robot_->computeForwardKinematics ();
      robot_->updateGeometryPlacements ();

      fcl::CollisionResult collisionResult;
      CollisionPairs_t::const_iterator _col;
      if(computeAllContacts_){
        hppDout(notice,"collision validation, computeAllContacts, num of pairs : "<<collisionPairs_.size());
        bool firstCollision(true);
        AllCollisionsValidationReportPtr_t allReport;
        for (CollisionPairs_t::const_iterator _col = collisionPairs_.begin (); _col != collisionPairs_.end (); ++_col){
          if (collide (_col, collisionRequest_, collisionResult) != 0){
            hppDout(notice,"in collision :  "<<_col->first->name()<<" / "<<_col->second->name());
            CollisionValidationReportPtr_t report (new CollisionValidationReport);
            report->object1 = _col->first;
            report->object2 = _col->second;
            report->result = collisionResult;
            if(firstCollision){
              allReport = AllCollisionsValidationReportPtr_t(new AllCollisionsValidationReport);
              allReport->object1 = _col->first;
              allReport->object2 = _col->second;
              allReport->result = collisionResult;
              firstCollision = false;
            }
            allReport->collisionReports.push_back(report);
          }
        }
        validationReport=allReport;
        return firstCollision;
      }else{
        fcl::CollisionResult collisionResult;
        if (collide (collisionPairs_, collisionRequest_, collisionResult, _col)
            ||
            ( checkParameterized_ &&
              collide (parameterizedPairs_, collisionRequest_, collisionResult, _col)
            )) {
          CollisionValidationReportPtr_t report (new CollisionValidationReport);
          report->object1 = _col->first;
          report->object2 = _col->second;
          report->result = collisionResult;
          validationReport = report;
          return false;
        }
        return true;
      }
    }

    void CollisionValidation::addObstacle (const CollisionObjectConstPtr_t& object)
    {
      const JointVector_t& jv = robot_->getJointVector ();
      for (JointVector_t::const_iterator it = jv.begin (); it != jv.end ();
          ++it) {
        JointPtr_t joint = JointPtr_t (new Joint(**it));
        addObstacleToJoint (object, joint, false);
      }
    }

    void CollisionValidation::addObstacleToJoint (const CollisionObjectConstPtr_t& object,
                                     const JointPtr_t& joint, const bool includeChildren)
    {
        BodyPtr_t body = joint->linkedBody ();
        if (body) {
            const ObjectVector_t& bodyObjects = body->innerObjects ();
            for (ObjectVector_t::const_iterator itInner = bodyObjects.begin ();
                itInner != bodyObjects.end (); ++itInner) {
              // TODO: check the objects are not in same joint
              collisionPairs_.push_back (CollisionPair_t (*itInner, object));
            }
          }
        if(includeChildren) {
            for(std::size_t i=0; i<joint->numberChildJoints(); ++i){
                addObstacleToJoint (object, joint->childJoint(i),includeChildren);
            }
        }
    }

    void CollisionValidation::removeObstacleFromJoint
    (const JointPtr_t& joint, const CollisionObjectConstPtr_t& obstacle)
    {
      BodyPtr_t body = joint->linkedBody ();
      if (body) {
        const ObjectVector_t& bodyObjects = body->innerObjects ();
        for (ObjectVector_t::const_iterator itInner = bodyObjects.begin ();
            itInner != bodyObjects.end (); ++itInner) {
          CollisionPair_t colPair (*itInner, obstacle);
          std::size_t nbDelPairs = 0;
          CollisionPairs_t::iterator _collisionPair (collisionPairs_.begin());
          while ( (_collisionPair = std::find (_collisionPair, collisionPairs_.end(), colPair))
              != collisionPairs_.end()) {
            _collisionPair = collisionPairs_.erase (_collisionPair);
            ++nbDelPairs;
          }
          if (nbDelPairs == 0) {
            std::ostringstream oss;
            oss << "CollisionValidation::removeObstacleFromJoint: obstacle \""
                << obstacle->name () <<
                "\" is not registered as obstacle for joint \"" << joint->name ()
                << "\".";
            throw std::runtime_error (oss.str ());
          } else if (nbDelPairs >= 2) {
            hppDout (error, "obstacle "<< obstacle->name () <<
                     " was registered " << nbDelPairs
                     << " times as obstacle for joint " << joint->name ()
                     << ".");
          }
        }
      }
    }

    void CollisionValidation::filterCollisionPairs (const RelativeMotion::matrix_type& matrix)
    {
      // Loop over collision pairs and remove disabled ones.
      CollisionPairs_t::iterator _colPair = collisionPairs_.begin ();
      se3::JointIndex j1, j2;
      fcl::CollisionResult unused;
      while (_colPair != collisionPairs_.end ()) {
        j1 = _colPair->first ->jointIndex();
        j2 = _colPair->second->jointIndex();

        switch (matrix(j1, j2)) {
          case RelativeMotion::Parameterized:
              hppDout(info, "Parameterized collision pairs between "
                  << _colPair->first ->name() << " and "
                  << _colPair->second->name());
              parameterizedPairs_.push_back (*_colPair);
              _colPair = collisionPairs_.erase (_colPair);
              break;
          case RelativeMotion::Constrained:
              hppDout(info, "Disabling collision between "
                  << _colPair->first ->name() << " and "
                  << _colPair->second->name());
              if (collide (_colPair, collisionRequest_, unused) != 0) {
                hppDout(warning, "Disabling collision detection between two "
                    "body in collision.");
              }
              disabledPairs_.push_back (*_colPair);
              _colPair = collisionPairs_.erase (_colPair);
              break;
          case RelativeMotion::Unconstrained: ++_colPair; break;
          default:
            hppDout (warning, "RelativeMotionType not understood");
            ++_colPair;
            break;
        }
      }
    }

    CollisionValidation::CollisionValidation (const DevicePtr_t& robot) :
      collisionRequest_(1, false, false, 1, false, true, fcl::GST_INDEP),
      robot_ (robot),
      parameterizedPairs_(), disabledPairs_(),
      checkParameterized_(false),
      computeAllContacts_(false)
    {
      const se3::GeometryModel& model = robot->geomModel();
      const se3::GeometryData & data  = robot->geomData();

      for (std::size_t i = 0; i < model.collisionPairs.size(); ++i)
        if (data.activeCollisionPairs[i])
          collisionPairs_.push_back(
              makeCollisionPair(robot, model.collisionPairs[i])
              );
    }

  } // namespace core
} // namespace hpp
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSbrCamera.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <math.h>
#include "vtkSbrCamera.hh"
#include "vtkSbrRenderWindow.hh"
#include "vtkSbrRenderer.hh"

// Description:
// Implement base class method.
void vtkSbrCamera::Render(vtkCamera *cam, vtkRenderer *ren)
{
  this->Render(cam, (vtkSbrRenderer *)ren);
}

// Description:
// Actual camera render method.
void vtkSbrCamera::Render(vtkCamera *cam, vtkSbrRenderer *ren)
{
  float aspect[3];
  float viewport[4];
  float *background;
  int stereo;
  int fd;
  int *size;
  int *screen_size;
  vtkSbrRenderWindow *rw;
  float view_size[2];
  float vdc_vals[6];
  fd = ren->GetFd();
  vtkMatrix4x4 matrix;

  // get the background color
  background = ren->GetBackground();
  // get size info
  rw = (vtkSbrRenderWindow*)(ren->GetRenderWindow());
  size = rw->GetSize();
  screen_size = rw->GetScreenSize();

  // find out if we should stereo render
  stereo = cam->GetStereo();

  // set this renderer's viewport, must turn off z-buffering when changing
  // viewport
  hidden_surface(fd, FALSE, FALSE);
  vtkDebugMacro(<< " SB_hidden_surface: False False\n");

  memcpy(viewport,ren->GetViewport(),sizeof(float)*4);

  // if were on a stereo renderer draw to special parts of screen
  if (stereo)
    {
    switch ((ren->GetRenderWindow())->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	if (cam->GetLeftEye())
	  {
	  viewport[1] = 0.5 + viewport[1]*0.5;
	  viewport[3] = 0.5 + viewport[3]*0.5;
	  }
	else
	  {
	  viewport[1] = viewport[1]*0.5;
	  viewport[3] = viewport[3]*0.5;
	  }
	break;
      }
    }

  view_size[0] = (viewport[2] - viewport[0])*size[0];
  view_size[1] = (viewport[3] - viewport[1])*size[1];
  vdc_vals[0] = -1.0 - viewport[0]*size[0]*2.0/view_size[0];
  vdc_vals[3] = vdc_vals[0] + 2.0*screen_size[0]/view_size[0];
  vdc_vals[4] = 1.0 + (1.0-viewport[3])*size[1]*2.0/view_size[1];
  vdc_vals[1] = vdc_vals[4] - 2.0*screen_size[1]/view_size[1];
  vdc_vals[2] = 0;
  vdc_vals[5] = 1.0;

  // make sure the aspect is up to date
  if (stereo)
    {
    switch ((ren->GetRenderWindow())->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	{
	aspect[0] = view_size[0]/(2.0*view_size[1]);
	aspect[1] = 1.0;
	}
	break;
      default:
	{
	aspect[0] = view_size[0]/view_size[1];
	aspect[1] = 1.0;
	}
      }
    }
  else
    {
    aspect[0] = view_size[0]/view_size[1];
    aspect[1] = 1.0;
    }
  ren->SetAspect(aspect);

  vdc_extent(fd,vdc_vals[0],vdc_vals[1],vdc_vals[2],
	     vdc_vals[3],vdc_vals[4],vdc_vals[5]);

  vtkDebugMacro(<< " screen_size " << screen_size[0] << " "
  << screen_size[1] << endl);
  vtkDebugMacro(<< " size " << size[0] << " " << size[1] << endl);
  vtkDebugMacro(<< " viewport " << viewport[0] << " " << viewport[1]
  << " " << viewport[2] << " " << viewport[3] << endl);

  // set viewport to clear entire window
  view_port(fd,-1.0,-1.0,1.0,1.0);
  hidden_surface(fd, TRUE, FALSE);
  vtkDebugMacro(<< " SB_hidden_surface: True False\n");

  // Set the background color and clear the display.
  // Since clear control was set to clear z buffer, this is done here
  // also.
  background_color(fd, background[0], background[1], background[2]);

  // clear the view surface so the new background color takes effect
  if (rw->GetErase())
    {
    clear_view_surface(fd);
    vtkDebugMacro(<< " SB_clear_view_surface\n");
    }

  hidden_surface(fd, FALSE, FALSE);
  vtkDebugMacro(<< " SB_hidden_surface: False False\n");

  // I think the z clipping is done before the divide by w
  vdc_extent(fd,vdc_vals[0],vdc_vals[1],vdc_vals[2],
	     vdc_vals[3],vdc_vals[4],vdc_vals[5]);

  view_port(fd,-1.0,-1.0,1.0,1.0);

  hidden_surface(fd, TRUE, FALSE);
  vtkDebugMacro(<< " SB_hidden_surface: True False\n");

  matrix = cam->GetCompositePerspectiveTransform(aspect[0]/aspect[1],0,1);
  matrix.Transpose();

  // insert model transformation
  view_matrix3d(fd, (float (*)[4])(matrix[0]),REPLACE_VW);

  clip_depth(fd,0.0,1.0);
}
<commit_msg>fixed problems with specularities<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSbrCamera.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <math.h>
#include "vtkSbrCamera.hh"
#include "vtkSbrRenderWindow.hh"
#include "vtkSbrRenderer.hh"

// Description:
// Implement base class method.
void vtkSbrCamera::Render(vtkCamera *cam, vtkRenderer *ren)
{
  this->Render(cam, (vtkSbrRenderer *)ren);
}

// Description:
// Actual camera render method.
void vtkSbrCamera::Render(vtkCamera *cam, vtkSbrRenderer *ren)
{
  float aspect[3];
  float viewport[4];
  float *background;
  int stereo;
  int fd;
  int *size;
  int *screen_size;
  vtkSbrRenderWindow *rw;
  float view_size[2];
  float vdc_vals[6];
  fd = ren->GetFd();
  vtkMatrix4x4 matrix;
  float *pos;

  // get the background color
  background = ren->GetBackground();
  // get size info
  rw = (vtkSbrRenderWindow*)(ren->GetRenderWindow());
  size = rw->GetSize();
  screen_size = rw->GetScreenSize();

  // find out if we should stereo render
  stereo = cam->GetStereo();

  // set this renderer's viewport, must turn off z-buffering when changing
  // viewport
  hidden_surface(fd, FALSE, FALSE);
  vtkDebugMacro(<< " SB_hidden_surface: False False\n");

  memcpy(viewport,ren->GetViewport(),sizeof(float)*4);

  // if were on a stereo renderer draw to special parts of screen
  if (stereo)
    {
    switch ((ren->GetRenderWindow())->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	if (cam->GetLeftEye())
	  {
	  viewport[1] = 0.5 + viewport[1]*0.5;
	  viewport[3] = 0.5 + viewport[3]*0.5;
	  }
	else
	  {
	  viewport[1] = viewport[1]*0.5;
	  viewport[3] = viewport[3]*0.5;
	  }
	break;
      }
    }

  view_size[0] = (viewport[2] - viewport[0])*size[0];
  view_size[1] = (viewport[3] - viewport[1])*size[1];
  vdc_vals[0] = -1.0 - viewport[0]*size[0]*2.0/view_size[0];
  vdc_vals[3] = vdc_vals[0] + 2.0*screen_size[0]/view_size[0];
  vdc_vals[4] = 1.0 + (1.0-viewport[3])*size[1]*2.0/view_size[1];
  vdc_vals[1] = vdc_vals[4] - 2.0*screen_size[1]/view_size[1];
  vdc_vals[2] = 0;
  vdc_vals[5] = 1.0;

  // make sure the aspect is up to date
  if (stereo)
    {
    switch ((ren->GetRenderWindow())->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	{
	aspect[0] = view_size[0]/(2.0*view_size[1]);
	aspect[1] = 1.0;
	}
	break;
      default:
	{
	aspect[0] = view_size[0]/view_size[1];
	aspect[1] = 1.0;
	}
      }
    }
  else
    {
    aspect[0] = view_size[0]/view_size[1];
    aspect[1] = 1.0;
    }
  ren->SetAspect(aspect);

  vdc_extent(fd,vdc_vals[0],vdc_vals[1],vdc_vals[2],
	     vdc_vals[3],vdc_vals[4],vdc_vals[5]);

  vtkDebugMacro(<< " screen_size " << screen_size[0] << " "
  << screen_size[1] << endl);
  vtkDebugMacro(<< " size " << size[0] << " " << size[1] << endl);
  vtkDebugMacro(<< " viewport " << viewport[0] << " " << viewport[1]
  << " " << viewport[2] << " " << viewport[3] << endl);

  // set viewport to clear entire window
  view_port(fd,-1.0,-1.0,1.0,1.0);
  hidden_surface(fd, TRUE, FALSE);
  vtkDebugMacro(<< " SB_hidden_surface: True False\n");

  // Set the background color and clear the display.
  // Since clear control was set to clear z buffer, this is done here
  // also.
  background_color(fd, background[0], background[1], background[2]);

  // clear the view surface so the new background color takes effect
  if (rw->GetErase())
    {
    clear_view_surface(fd);
    vtkDebugMacro(<< " SB_clear_view_surface\n");
    }

  hidden_surface(fd, FALSE, FALSE);
  vtkDebugMacro(<< " SB_hidden_surface: False False\n");

  // I think the z clipping is done before the divide by w
  vdc_extent(fd,vdc_vals[0],vdc_vals[1],vdc_vals[2],
	     vdc_vals[3],vdc_vals[4],vdc_vals[5]);

  view_port(fd,-1.0,-1.0,1.0,1.0);

  hidden_surface(fd, TRUE, FALSE);
  vtkDebugMacro(<< " SB_hidden_surface: True False\n");

  matrix = cam->GetCompositePerspectiveTransform(aspect[0]/aspect[1],0,1);
  matrix.Transpose();

  // insert model transformation
  view_matrix3d(fd, (float (*)[4])(matrix[0]),REPLACE_VW);

  pos = cam->GetPosition();
  viewpoint(fd,POSITIONAL,pos[0],pos[1],pos[2]);

  clip_depth(fd,0.0,1.0);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "tango_data.h"
const TangoCoordinateFramePair tango_frame_pairs_[]={{TANGO_COORDINATE_FRAME_START_OF_SERVICE,TANGO_COORDINATE_FRAME_DEVICE}};
TangoData::TangoData()
    : config_(nullptr),
      tango_position_(glm::vec3(0.0f, 0.0f, 0.0f)),
      tango_rotation_(glm::quat(1.0f, 0.0f, 0.0f, 0.0f)) {
}

// This callback function is called when new POSE updates become available.
static void onPoseAvailable(const TangoPoseData* pose) {
  TangoData::GetInstance().SetTangoPosition(
      glm::vec3(pose->translation[0], pose->translation[1],
                pose->translation[2]));
  TangoData::GetInstance().SetTangoRotation(
      glm::quat(pose->orientation[3], pose->orientation[0],
                pose->orientation[1], pose->orientation[2]));

  TangoData::GetInstance().SetTangoPoseStatus(pose->status_code);

//  glm::vec3 euler = glm::eulerAngles(
//      glm::quat(pose->orientation[3], pose->orientation[0],
//                pose->orientation[1], pose->orientation[2]));
//  LOGI("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f", pose->translation[0],
//       pose->translation[1], pose->translation[2], euler.x * 57.32f,
//       euler.y * 57.32f, euler.z * 57.32f);
//  if (pose->status_code == TANGO_POSE_INITIALIZING)
//    LOGI("%d", 0);
//  if (pose->status_code == TANGO_POSE_VALID)
//    LOGI("%d", 1);
}

bool TangoData::Initialize() {
  // Initialize Tango Service.
  if (TangoService_initialize() != 0) {
    LOGE("TangoService_initialize(): Failed");
    return false;
  }
  return true;
}

bool TangoData::SetConfig() {
  // Allocate a TangoConfig object.
  if ((config_ = TangoConfig_alloc()) == NULL) {
    LOGE("TangoService_allocConfig(): Failed");
    return false;
  }

  // Get the default TangoConfig.
  if (TangoService_getConfig(TANGO_CONFIG_DEFAULT, config_) != 0) {
    LOGE("TangoService_getConfig(): Failed");
    return false;
  }

  if (TangoService_connectOnPoseAvailable(onPoseAvailable) != 0) {
    LOGI("TangoService_connectOnPoseAvailable(): Failed");
    return false;
  }

//  std::list<TangoCoordinateFramePair> list;
//  TangoCoordinateFramePair frame_pair;
//  frame_pair.base = TANGO_COORDINATE_FRAME_START_OF_SERVICE;
//  frame_pair.target = TANGO_COORDINATE_FRAME_DEVICE;
//  list.push_back(frame_pair);

  if(TangoService_setPoseListenerFrames(1, tango_frame_pairs_)!=0){
    LOGE("TangoService_setPoseListenerFrames(): Failed");
    return false;
  }

  return true;
}

bool TangoData::LockConfig() {
  // Lock in this configuration.
  if (TangoService_lockConfig(config_) != 0) {
    LOGE("TangoService_lockConfig(): Failed");
    return false;
  }
  return true;
}

bool TangoData::UnlockConfig() {
  // Unlock current configuration.
  if (TangoService_unlockConfig() != 0) {
    LOGE("TangoService_unlockConfig(): Failed");
    return false;
  }
  return true;
}

// Connect to Tango Service, service will start running, and
// POSE can be queried.
bool TangoData::Connect() {
  if (TangoService_connect() != 0) {
    LOGE("TangoService_connect(): Failed");
    return false;
  }
  return true;
}

void TangoData::Disconnect() {
  // Disconnect Tango Service.
  TangoService_disconnect();
}

glm::vec3 TangoData::GetTangoPosition() {
  return tango_position_;
}

glm::quat TangoData::GetTangoRotation() {
  return tango_rotation_;
}

char TangoData::GetTangoPoseStatus(){
  switch (status_) {
    case TANGO_POSE_INITIALIZING:
      return 1;
    case TANGO_POSE_VALID:
      return 2;
    case TANGO_POSE_INVALID:
      return 3;
    default:
      return 0;
      break;
  }
}

void TangoData::SetTangoPosition(glm::vec3 position) {
  tango_position_ = position;
}

void TangoData::SetTangoRotation(glm::quat rotation) {
  tango_rotation_ = rotation;
}

void TangoData::SetTangoPoseStatus(TangoPoseStatusType status) {
  status_ = status;
}
<commit_msg>Move the setPoseListenerFrames() after connect to Tango Service.<commit_after>/*
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "tango_data.h"
TangoData::TangoData()
    : config_(nullptr),
      tango_position_(glm::vec3(0.0f, 0.0f, 0.0f)),
      tango_rotation_(glm::quat(1.0f, 0.0f, 0.0f, 0.0f)) {
}

// This callback function is called when new POSE updates become available.
static void onPoseAvailable(const TangoPoseData* pose) {
  TangoData::GetInstance().SetTangoPosition(
      glm::vec3(pose->translation[0], pose->translation[1],
                pose->translation[2]));
  TangoData::GetInstance().SetTangoRotation(
      glm::quat(pose->orientation[3], pose->orientation[0],
                pose->orientation[1], pose->orientation[2]));

  TangoData::GetInstance().SetTangoPoseStatus(pose->status_code);

//  glm::vec3 euler = glm::eulerAngles(
//      glm::quat(pose->orientation[3], pose->orientation[0],
//                pose->orientation[1], pose->orientation[2]));
//  LOGI("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f", pose->translation[0],
//       pose->translation[1], pose->translation[2], euler.x * 57.32f,
//       euler.y * 57.32f, euler.z * 57.32f);
//  if (pose->status_code == TANGO_POSE_INITIALIZING)
//    LOGI("%d", 0);
//  if (pose->status_code == TANGO_POSE_VALID)
//    LOGI("%d", 1);
}

bool TangoData::Initialize() {
  // Initialize Tango Service.
  if (TangoService_initialize() != 0) {
    LOGE("TangoService_initialize(): Failed");
    return false;
  }
  return true;
}

bool TangoData::SetConfig() {
  // Allocate a TangoConfig object.
  if ((config_ = TangoConfig_alloc()) == NULL) {
    LOGE("TangoService_allocConfig(): Failed");
    return false;
  }

  // Get the default TangoConfig.
  if (TangoService_getConfig(TANGO_CONFIG_DEFAULT, config_) != 0) {
    LOGE("TangoService_getConfig(): Failed");
    return false;
  }

  if (TangoService_connectOnPoseAvailable(onPoseAvailable) != 0) {
    LOGI("TangoService_connectOnPoseAvailable(): Failed");
    return false;
  }
  return true;
}

bool TangoData::LockConfig() {
  // Lock in this configuration.
  if (TangoService_lockConfig(config_) != 0) {
    LOGE("TangoService_lockConfig(): Failed");
    return false;
  }
  return true;
}

bool TangoData::UnlockConfig() {
  // Unlock current configuration.
  if (TangoService_unlockConfig() != 0) {
    LOGE("TangoService_unlockConfig(): Failed");
    return false;
  }
  return true;
}

// Connect to Tango Service, service will start running, and
// POSE can be queried.
bool TangoData::Connect() {
  if (TangoService_connect() != 0) {
    LOGE("TangoService_connect(): Failed");
    return false;
  }

//Set the reference frame pair after connect to service.
  TangoCoordinateFramePair pairs;
  pairs.base = TANGO_COORDINATE_FRAME_START_OF_SERVICE;
  pairs.target = TANGO_COORDINATE_FRAME_DEVICE;
  if (TangoService_setPoseListenerFrames(1, &pairs) != 0) {
    LOGE("TangoService_setPoseListenerFrames(): Failed");
    return false;
  }
  return true;
}

void TangoData::Disconnect() {
  // Disconnect Tango Service.
  TangoService_disconnect();
}

glm::vec3 TangoData::GetTangoPosition() {
  return tango_position_;
}

glm::quat TangoData::GetTangoRotation() {
  return tango_rotation_;
}

char TangoData::GetTangoPoseStatus() {
  switch (status_) {
    case TANGO_POSE_INITIALIZING:
      return 1;
    case TANGO_POSE_VALID:
      return 2;
    case TANGO_POSE_INVALID:
      return 3;
    default:
      return 0;
      break;
  }
}

void TangoData::SetTangoPosition(glm::vec3 position) {
  tango_position_ = position;
}

void TangoData::SetTangoRotation(glm::quat rotation) {
  tango_rotation_ = rotation;
}

void TangoData::SetTangoPoseStatus(TangoPoseStatusType status) {
  status_ = status;
}
<|endoftext|>


<commit_before><commit_msg>winlauncher: updated PATH modification order: jbr folders and then current PATH<commit_after><|endoftext|>


<commit_before><commit_msg>Disable LoadState net unittest: it's flakey<commit_after><|endoftext|>


<commit_before>/**
 *  @file statmech
 *       test problem for statistical mechanics in cantera
 */

//  Example
//
// Test case for the statistical mechanics in cantera
//

#include <iostream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>

/*****************************************************************/
/*****************************************************************/

//#include "cantera/Cantera.h"
#include "cantera/transport.h"
#include "cantera/IdealGasMix.h"
#include "cantera/equil/equil.h"

#include "cantera/transport/TransportFactory.h"

using namespace std;
using namespace Cantera;

int main(int argc, char** argv)
{

  try
    {
      int k;
      IdealGasMix g("test_stat_trans.xml");
      int nsp = g.nSpecies();
      double pres = 1.0E5;

      // init pecos transport
      int log_level = 0;
      Transport * tran = newTransportMgr("Pecos", &g, log_level=0);
      PecosTransport * tranMix = dynamic_cast<PecosTransport *>(tran);

      vector_fp Xset(nsp, 0.0);
      Xset[0] =  0.5 ;
      Xset[1] =  0.5;

      g.setState_TPX(1500.0, pres, DATA_PTR(Xset));
      equilibrate(g, "TP", -1);

      vector_fp cp_R(nsp, 0.0);
      g.getCp_R(DATA_PTR(cp_R));

      //for(int i=0;i<nsp;i++)
      //{
      //  std::cout.precision(10);
      //  std::cout << cp_R[i] << std::endl;
      //	}

      // error check-- exactly 2.5 for atoms
      if(cp_R[0] != 2.5)
	{
	  std::cout << "Error for monotomic Species!\n";
	  return 1;
	}

      // error check: analytical result is more complicated for
      // molecules. One species should suffice, lets try NO2, with
      // three vibrational modes:
      /// theta[0]: 1.07900e3
      /// theta[1]: 1.90000e3
      /// theta[2]: 2.32700e3
      // at T = 1500
      //
      // This is precisely: 6.655804161 (e.g. 5/2 + 2 + 3.1558..)
      //
      double theta[3];
      theta[0] = 1.07900e3;
      theta[1] = 1.90000e3;
      theta[2] = 2.32700e3;

      double T;
      T = 1500.0;

      double denom;
      double ctr = 0.0;
      double GasConstant = 1.0;

      for(int i = 0; i < 3; i++)
	{
	  denom = exp(2*theta[i]/T) - 2* exp(theta[i]/T) + 1;
	  ctr += GasConstant * theta[i] * (theta[i] * exp(theta[i]/T)/(T*T))/ (denom);
	  //std::cout << "survey says: " << ctr << " and denom is: " << denom << std::endl;
	}
      //std::cout << "survey says: " << ctr << " and denom is: " << denom << std::endl;
      double sol = ctr + 5/2 + 2;
      double tol = 1e-9;

      if(abs(cp_R[3] - sol) >= tol )
	{
	  double diff = cp_R[3]-sol;
	  std::cout << "Error for Species NO2!\n";
	  std::cout << "Diff was: " << diff << "\n";
	  return 1;
	}

    }
    catch (CanteraError)
      {
	showErrors(cout);
	return 1;
      }

  // Mark it zero!
  return 0;

}
<commit_msg>updating, even if it is not working... will fiddle further<commit_after>/**
 *  @file statmech
 *       test problem for statistical mechanics in cantera
 */

//  Example
//
// Test case for the statistical mechanics in cantera
//

#include <iostream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>

/*****************************************************************/
/*****************************************************************/

//#include "cantera/Cantera.h"
#include "cantera/transport.h"
#include "cantera/IdealGasMix.h"
#include "cantera/equil/equil.h"

#include "cantera/transport/TransportFactory.h"

using namespace std;
using namespace Cantera;

int main(int argc, char** argv)
{

  try
    {
      int k;
      IdealGasMix g("test_stat_trans.xml", "example");
      int nsp = g.nSpecies();
      double pres = 1.0E5;

      vector_fp Xset(nsp, 0.0);
      Xset[0] =  0.5 ;
      Xset[1] =  0.5;

      g.setState_TPX(1500.0, pres, DATA_PTR(Xset));
      equilibrate(g, "TP", -1);

      // init pecos transport
      int log_level = 0;
      Transport * tran = newTransportMgr("Pecos", &g, log_level=0);
      PecosTransport * tranMix = dynamic_cast<PecosTransport *>(tran);

      cout << "here";

      vector_fp cp_R(nsp, 0.0);
      g.getCp_R(DATA_PTR(cp_R));

      //for(int i=0;i<nsp;i++)
      //{
      //  std::cout.precision(10);
      //  std::cout << cp_R[i] << std::endl;
      //	}

      // error check-- exactly 2.5 for atoms
      if(cp_R[0] != 2.5)
	{
	  std::cout << "Error for monotomic Species!\n";
	  return 1;
	}

      // error check: analytical result is more complicated for
      // molecules. One species should suffice, lets try NO2, with
      // three vibrational modes:
      /// theta[0]: 1.07900e3
      /// theta[1]: 1.90000e3
      /// theta[2]: 2.32700e3
      // at T = 1500
      //
      // This is precisely: 6.655804161 (e.g. 5/2 + 2 + 3.1558..)
      //
      double theta[3];
      theta[0] = 1.07900e3;
      theta[1] = 1.90000e3;
      theta[2] = 2.32700e3;

      double T;
      T = 1500.0;

      double denom;
      double ctr = 0.0;
      double GasConstant = 1.0;

      for(int i = 0; i < 3; i++)
	{
	  denom = exp(2*theta[i]/T) - 2* exp(theta[i]/T) + 1;
	  ctr += GasConstant * theta[i] * (theta[i] * exp(theta[i]/T)/(T*T))/ (denom);
	  //std::cout << "survey says: " << ctr << " and denom is: " << denom << std::endl;
	}
      //std::cout << "survey says: " << ctr << " and denom is: " << denom << std::endl;
      double sol = ctr + 5/2 + 2;
      double tol = 1e-9;

      if(abs(cp_R[3] - sol) >= tol )
	{
	  double diff = cp_R[3]-sol;
	  std::cout << "Error for Species NO2!\n";
	  std::cout << "Diff was: " << diff << "\n";
	  return 1;
	}

    }
    catch (CanteraError)
      {
	showErrors(cout);
	return 1;
      }

  // Mark it zero!
  return 0;

}
<|endoftext|>


<commit_before>#include "CrashHandler.h"

#include "SkTypes.h"

#include <stdlib.h>

#if defined(SK_BUILD_FOR_MAC)

// We only use local unwinding, so we can define this to select a faster implementation.
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#include <cxxabi.h>

static void handler(int sig) {
    unw_context_t context;
    unw_getcontext(&context);

    unw_cursor_t cursor;
    unw_init_local(&cursor, &context);

    SkDebugf("\nSignal %d:\n", sig);
    while (unw_step(&cursor) > 0) {
        static const size_t kMax = 256;
        char mangled[kMax], demangled[kMax];
        unw_word_t offset;
        unw_get_proc_name(&cursor, mangled, kMax, &offset);

        int ok;
        size_t len = kMax;
        abi::__cxa_demangle(mangled, demangled, &len, &ok);

        SkDebugf("%s (+0x%zx)\n", ok == 0 ? demangled : mangled, (size_t)offset);
    }
    SkDebugf("\n");

    // Exit NOW.  Don't notify other threads, don't call anything registered with atexit().
    _Exit(sig);
}

#elif defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_NACL)   // NACL doesn't have backtrace().

// We'd use libunwind here too, but it's a pain to get installed for both 32 and 64 bit on bots.
// Doesn't matter much: catchsegv is best anyway.
#include <execinfo.h>

static void handler(int sig) {
    static const int kMax = 64;
    void* stack[kMax];
    const int count = backtrace(stack, kMax);

    SkDebugf("\nSignal %d:\n", sig);
    backtrace_symbols_fd(stack, count, 2/*stderr*/);

    // Exit NOW.  Don't notify other threads, don't call anything registered with atexit().
    _Exit(sig);
}

#endif

#if defined(SK_BUILD_FOR_MAC) || (defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_NACL))
#include <signal.h>

void SetupCrashHandler() {
    static const int kSignals[] = {
        SIGABRT,
        SIGBUS,
        SIGFPE,
        SIGILL,
        SIGSEGV,
    };

    for (size_t i = 0; i < sizeof(kSignals) / sizeof(kSignals[0]); i++) {
        // Register our signal handler unless something's already done so (e.g. catchsegv).
        void (*prev)(int) = signal(kSignals[i], handler);
        if (prev != SIG_DFL) {
            signal(kSignals[i], prev);
        }
    }
}

#elif defined(SK_BUILD_FOR_WIN)

#include <DbgHelp.h>

static const struct {
    const char* name;
    int code;
} kExceptions[] = {
#define _(E) {#E, E}
    _(EXCEPTION_ACCESS_VIOLATION),
    _(EXCEPTION_BREAKPOINT),
    _(EXCEPTION_INT_DIVIDE_BY_ZERO),
    _(EXCEPTION_STACK_OVERFLOW),
    // TODO: more?
#undef _
};

static LONG WINAPI handler(EXCEPTION_POINTERS* e) {
    const DWORD code = e->ExceptionRecord->ExceptionCode;
    SkDebugf("\nCaught exception %u", code);
    for (size_t i = 0; i < SK_ARRAY_COUNT(kExceptions); i++) {
        if (kExceptions[i].code == code) {
            SkDebugf(" %s", kExceptions[i].name);
        }
    }
    SkDebugf("\n");

    // We need to run SymInitialize before doing any of the stack walking below.
    HANDLE hProcess = GetCurrentProcess();
    SymInitialize(hProcess, 0, true);

    STACKFRAME64 frame;
    sk_bzero(&frame, sizeof(frame));
    // Start frame off from the frame that triggered the exception.
    CONTEXT* c = e->ContextRecord;
    frame.AddrPC.Mode      = AddrModeFlat;
    frame.AddrStack.Mode   = AddrModeFlat;
    frame.AddrFrame.Mode   = AddrModeFlat;
#if defined(_X86_)
    frame.AddrPC.Offset    = c->Eip;
    frame.AddrStack.Offset = c->Esp;
    frame.AddrFrame.Offset = c->Ebp;
    const DWORD machineType = IMAGE_FILE_MACHINE_I386;
#elif defined(_AMD64_)
    frame.AddrPC.Offset    = c->Rip;
    frame.AddrStack.Offset = c->Rsp;
    frame.AddrFrame.Offset = c->Rbp;
    const DWORD machineType = IMAGE_FILE_MACHINE_AMD64;
#endif

    while (StackWalk64(machineType,
                       GetCurrentProcess(),
                       GetCurrentThread(),
                       &frame,
                       c,
                       NULL,
                       SymFunctionTableAccess64,
                       SymGetModuleBase64,
                       NULL)) {
        // Buffer to store symbol name in.
        static const int kMaxNameLength = 1024;
        uint8_t buffer[sizeof(IMAGEHLP_SYMBOL64) + kMaxNameLength];
        sk_bzero(buffer, sizeof(buffer));

        // We have to place IMAGEHLP_SYMBOL64 at the front, and fill in how much space it can use.
        IMAGEHLP_SYMBOL64* symbol = reinterpret_cast<IMAGEHLP_SYMBOL64*>(&buffer);
        symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
        symbol->MaxNameLength = kMaxNameLength - 1;

        // Translate the current PC into a symbol and byte offset from the symbol.
        DWORD64 offset;
        SymGetSymFromAddr64(hProcess, frame.AddrPC.Offset, &offset, symbol);

        SkDebugf("%s +%x\n", symbol->Name, offset);
    }

    // Exit NOW.  Don't notify other threads, don't call anything registered with atexit().
    _exit(1);

    // The compiler wants us to return something.  This is what we'd do if we didn't _exit().
    return EXCEPTION_EXECUTE_HANDLER;
}

void SetupCrashHandler() {
    SetUnhandledExceptionFilter(handler);
}

#else

void SetupCrashHandler() { }

#endif
<commit_msg>CrashHandler calls strsignal on linux<commit_after>#include "CrashHandler.h"

#include "SkTypes.h"

#include <stdlib.h>

#if defined(SK_BUILD_FOR_MAC)

// We only use local unwinding, so we can define this to select a faster implementation.
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#include <cxxabi.h>

static void handler(int sig) {
    unw_context_t context;
    unw_getcontext(&context);

    unw_cursor_t cursor;
    unw_init_local(&cursor, &context);

    SkDebugf("\nSignal %d:\n", sig);
    while (unw_step(&cursor) > 0) {
        static const size_t kMax = 256;
        char mangled[kMax], demangled[kMax];
        unw_word_t offset;
        unw_get_proc_name(&cursor, mangled, kMax, &offset);

        int ok;
        size_t len = kMax;
        abi::__cxa_demangle(mangled, demangled, &len, &ok);

        SkDebugf("%s (+0x%zx)\n", ok == 0 ? demangled : mangled, (size_t)offset);
    }
    SkDebugf("\n");

    // Exit NOW.  Don't notify other threads, don't call anything registered with atexit().
    _Exit(sig);
}

#elif defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_NACL)   // NACL doesn't have backtrace().

// We'd use libunwind here too, but it's a pain to get installed for both 32 and 64 bit on bots.
// Doesn't matter much: catchsegv is best anyway.
#include <execinfo.h>

static void handler(int sig) {
    static const int kMax = 64;
    void* stack[kMax];
    const int count = backtrace(stack, kMax);

    SkDebugf("\nSignal %d [%s]:\n", sig, strsignal(sig));
    backtrace_symbols_fd(stack, count, 2/*stderr*/);

    // Exit NOW.  Don't notify other threads, don't call anything registered with atexit().
    _Exit(sig);
}

#endif

#if defined(SK_BUILD_FOR_MAC) || (defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_NACL))
#include <signal.h>

void SetupCrashHandler() {
    static const int kSignals[] = {
        SIGABRT,
        SIGBUS,
        SIGFPE,
        SIGILL,
        SIGSEGV,
    };

    for (size_t i = 0; i < sizeof(kSignals) / sizeof(kSignals[0]); i++) {
        // Register our signal handler unless something's already done so (e.g. catchsegv).
        void (*prev)(int) = signal(kSignals[i], handler);
        if (prev != SIG_DFL) {
            signal(kSignals[i], prev);
        }
    }
}

#elif defined(SK_BUILD_FOR_WIN)

#include <DbgHelp.h>

static const struct {
    const char* name;
    int code;
} kExceptions[] = {
#define _(E) {#E, E}
    _(EXCEPTION_ACCESS_VIOLATION),
    _(EXCEPTION_BREAKPOINT),
    _(EXCEPTION_INT_DIVIDE_BY_ZERO),
    _(EXCEPTION_STACK_OVERFLOW),
    // TODO: more?
#undef _
};

static LONG WINAPI handler(EXCEPTION_POINTERS* e) {
    const DWORD code = e->ExceptionRecord->ExceptionCode;
    SkDebugf("\nCaught exception %u", code);
    for (size_t i = 0; i < SK_ARRAY_COUNT(kExceptions); i++) {
        if (kExceptions[i].code == code) {
            SkDebugf(" %s", kExceptions[i].name);
        }
    }
    SkDebugf("\n");

    // We need to run SymInitialize before doing any of the stack walking below.
    HANDLE hProcess = GetCurrentProcess();
    SymInitialize(hProcess, 0, true);

    STACKFRAME64 frame;
    sk_bzero(&frame, sizeof(frame));
    // Start frame off from the frame that triggered the exception.
    CONTEXT* c = e->ContextRecord;
    frame.AddrPC.Mode      = AddrModeFlat;
    frame.AddrStack.Mode   = AddrModeFlat;
    frame.AddrFrame.Mode   = AddrModeFlat;
#if defined(_X86_)
    frame.AddrPC.Offset    = c->Eip;
    frame.AddrStack.Offset = c->Esp;
    frame.AddrFrame.Offset = c->Ebp;
    const DWORD machineType = IMAGE_FILE_MACHINE_I386;
#elif defined(_AMD64_)
    frame.AddrPC.Offset    = c->Rip;
    frame.AddrStack.Offset = c->Rsp;
    frame.AddrFrame.Offset = c->Rbp;
    const DWORD machineType = IMAGE_FILE_MACHINE_AMD64;
#endif

    while (StackWalk64(machineType,
                       GetCurrentProcess(),
                       GetCurrentThread(),
                       &frame,
                       c,
                       NULL,
                       SymFunctionTableAccess64,
                       SymGetModuleBase64,
                       NULL)) {
        // Buffer to store symbol name in.
        static const int kMaxNameLength = 1024;
        uint8_t buffer[sizeof(IMAGEHLP_SYMBOL64) + kMaxNameLength];
        sk_bzero(buffer, sizeof(buffer));

        // We have to place IMAGEHLP_SYMBOL64 at the front, and fill in how much space it can use.
        IMAGEHLP_SYMBOL64* symbol = reinterpret_cast<IMAGEHLP_SYMBOL64*>(&buffer);
        symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
        symbol->MaxNameLength = kMaxNameLength - 1;

        // Translate the current PC into a symbol and byte offset from the symbol.
        DWORD64 offset;
        SymGetSymFromAddr64(hProcess, frame.AddrPC.Offset, &offset, symbol);

        SkDebugf("%s +%x\n", symbol->Name, offset);
    }

    // Exit NOW.  Don't notify other threads, don't call anything registered with atexit().
    _exit(1);

    // The compiler wants us to return something.  This is what we'd do if we didn't _exit().
    return EXCEPTION_EXECUTE_HANDLER;
}

void SetupCrashHandler() {
    SetUnhandledExceptionFilter(handler);
}

#else

void SetupCrashHandler() { }

#endif
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "s60devicerunconfigurationwidget.h"
#include "s60devicerunconfiguration.h"
#include "s60manager.h"
#include "launcher.h"
#include "serialdevicelister.h"

#include <utils/detailswidget.h>
#include <utils/qtcassert.h>
#include <utils/pathchooser.h>

#include <QtCore/QTimer>
#include <QtGui/QRadioButton>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QComboBox>
#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QFormLayout>
#include <QtGui/QToolButton>
#include <QtGui/QStyle>
#include <QtGui/QApplication>
#include <QtGui/QSpacerItem>

namespace Qt4ProjectManager {
namespace Internal {

S60DeviceRunConfigurationWidget::S60DeviceRunConfigurationWidget(
            S60DeviceRunConfiguration *runConfiguration,
            QWidget *parent)
    : QWidget(parent),
    m_runConfiguration(runConfiguration),
    m_detailsWidget(new Utils::DetailsWidget),
    m_serialPortsCombo(new QComboBox),
    m_nameLineEdit(new QLineEdit(m_runConfiguration->name())),
    m_sisxFileLabel(new QLabel(m_runConfiguration->basePackageFilePath() + QLatin1String(".sisx"))),
    m_deviceInfoButton(new QToolButton),
    m_deviceInfoDescriptionLabel(new QLabel(tr("Device:"))),
    m_deviceInfoLabel(new QLabel),
    m_infoTimeOutTimer(0)
{
    QVBoxLayout *mainBoxLayout = new QVBoxLayout();
    mainBoxLayout->setMargin(0);
    setLayout(mainBoxLayout);
    mainBoxLayout->addWidget(m_detailsWidget);
    QWidget *detailsContainer = new QWidget;
    m_detailsWidget->setWidget(detailsContainer);

    QVBoxLayout *detailsBoxLayout = new QVBoxLayout();
    detailsBoxLayout->setMargin(0);
    detailsContainer->setLayout(detailsBoxLayout);

    QFormLayout *formLayout = new QFormLayout();
    formLayout->setMargin(0);
    detailsBoxLayout->addLayout(formLayout);
    // Name control
    QLabel *nameLabel = new QLabel(tr("Name:"));
    nameLabel->setBuddy(m_nameLineEdit);
    formLayout->addRow(nameLabel, m_nameLineEdit);
    formLayout->addRow(tr("Install File:"), m_sisxFileLabel);

    updateSerialDevices();
    connect(S60Manager::instance()->serialDeviceLister(), SIGNAL(updated()),
            this, SLOT(updateSerialDevices()));
    // Serial devices control
    connect(m_serialPortsCombo, SIGNAL(activated(int)), this, SLOT(setSerialPort(int)));
    QHBoxLayout *serialPortHBoxLayout = new QHBoxLayout;
    serialPortHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
    serialPortHBoxLayout->addWidget(m_serialPortsCombo);

    formLayout->addRow(tr("Device on Serial Port:"), serialPortHBoxLayout);

    // Device Info with button. Widgets are enabled in above call to updateSerialDevices()
    QHBoxLayout *infoHBoxLayout = new QHBoxLayout;
    m_deviceInfoLabel->setWordWrap(true);
    infoHBoxLayout->addWidget(m_deviceInfoLabel);
    infoHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
    infoHBoxLayout->addWidget(m_deviceInfoButton);
    m_deviceInfoButton->setIcon(qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation));
    m_deviceInfoButton->setToolTip(tr("Queries the device for information"));
    connect(m_deviceInfoButton, SIGNAL(clicked()), this, SLOT(updateDeviceInfo()));
    formLayout->addRow(m_deviceInfoDescriptionLabel, infoHBoxLayout);

    // Signature/certificate stuff.
    QWidget *signatureWidget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout();
    signatureWidget->setLayout(layout);
    detailsBoxLayout->addWidget(signatureWidget);
    QRadioButton *selfSign = new QRadioButton(tr("Self-signed certificate"));
    QHBoxLayout *customHBox = new QHBoxLayout();
    customHBox->setMargin(0);
    QVBoxLayout *radioLayout = new QVBoxLayout();
    QRadioButton *customSignature = new QRadioButton();
    radioLayout->addWidget(customSignature);
    radioLayout->addStretch(10);
    customHBox->addLayout(radioLayout);
    QFormLayout *customLayout = new QFormLayout();
    customLayout->setMargin(0);
    customLayout->setLabelAlignment(Qt::AlignRight);
    Utils::PathChooser *signaturePath = new Utils::PathChooser();
    signaturePath->setExpectedKind(Utils::PathChooser::File);
    signaturePath->setPromptDialogTitle(tr("Choose certificate file (.cer)"));
    customLayout->addRow(new QLabel(tr("Custom certificate:")), signaturePath);
    Utils::PathChooser *keyPath = new Utils::PathChooser();
    keyPath->setExpectedKind(Utils::PathChooser::File);
    keyPath->setPromptDialogTitle(tr("Choose key file (.key / .pem)"));
    customLayout->addRow(new QLabel(tr("Key file:")), keyPath);
    customHBox->addLayout(customLayout);
    customHBox->addStretch(10);
    layout->addWidget(selfSign);
    layout->addLayout(customHBox);
    layout->addStretch(10);

    switch (m_runConfiguration->signingMode()) {
    case S60DeviceRunConfiguration::SignSelf:
        selfSign->setChecked(true);
        break;
    case S60DeviceRunConfiguration::SignCustom:
        customSignature->setChecked(true);
        break;
    }

    signaturePath->setPath(m_runConfiguration->customSignaturePath());
    keyPath->setPath(m_runConfiguration->customKeyPath());

    connect(m_nameLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(nameEdited(QString)));
    connect(m_runConfiguration, SIGNAL(targetInformationChanged()),
            this, SLOT(updateTargetInformation()));
    connect(selfSign, SIGNAL(toggled(bool)), this, SLOT(selfSignToggled(bool)));
    connect(customSignature, SIGNAL(toggled(bool)), this, SLOT(customSignatureToggled(bool)));
    connect(signaturePath, SIGNAL(changed(QString)), this, SLOT(signaturePathChanged(QString)));
    connect(keyPath, SIGNAL(changed(QString)), this, SLOT(keyPathChanged(QString)));
    updateSummary();
}

void S60DeviceRunConfigurationWidget::updateSerialDevices()
{
    m_serialPortsCombo->clear();
    clearDeviceInfo();
    const QString previousRunConfigurationPortName = m_runConfiguration->serialPortName();
    const QList<SerialDeviceLister::SerialDevice> serialDevices = S60Manager::instance()->serialDeviceLister()->serialDevices();
    int newIndex = -1;
    for (int i = 0; i < serialDevices.size(); ++i) {
        const SerialDeviceLister::SerialDevice &device = serialDevices.at(i);
        m_serialPortsCombo->addItem(device.friendlyName, device.portName);
        if (device.portName == previousRunConfigurationPortName)
            newIndex = i;
    }
    // Set new index: prefer to keep old or set to 0, if available.
    if (newIndex == -1 && !serialDevices.empty())
        newIndex = 0;
    m_serialPortsCombo->setCurrentIndex(newIndex);
    if (newIndex == -1) {
        m_deviceInfoButton->setEnabled(false);
        m_runConfiguration->setSerialPortName(QString());
    } else {
        m_deviceInfoButton->setEnabled(true);
        const QString newPortName = portName(newIndex);
        if (newPortName != previousRunConfigurationPortName)
            m_runConfiguration->setSerialPortName(newPortName);
    }
}

QString S60DeviceRunConfigurationWidget::portName(int index) const
{
    return index >= 0 ? m_serialPortsCombo->itemData(index).toString() : QString();
}

QString S60DeviceRunConfigurationWidget::currentPortName() const
{
    return portName(m_serialPortsCombo->currentIndex());
}

void S60DeviceRunConfigurationWidget::nameEdited(const QString &text)
{
    m_runConfiguration->setName(text);
}

void S60DeviceRunConfigurationWidget::updateTargetInformation()
{
    m_sisxFileLabel->setText(m_runConfiguration->basePackageFilePath() + QLatin1String(".sisx"));
}

void S60DeviceRunConfigurationWidget::setSerialPort(int index)
{
    m_runConfiguration->setSerialPortName(portName(index));
    m_deviceInfoButton->setEnabled(index >= 0);
    clearDeviceInfo();
    updateSummary();
}

void S60DeviceRunConfigurationWidget::selfSignToggled(bool toggle)
{
    if (toggle)
        m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignSelf);
    updateSummary();
}

void S60DeviceRunConfigurationWidget::customSignatureToggled(bool toggle)
{
    if (toggle)
        m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignCustom);
    updateSummary();
}

void S60DeviceRunConfigurationWidget::signaturePathChanged(const QString &path)
{
    m_runConfiguration->setCustomSignaturePath(path);
    updateSummary();
}

void S60DeviceRunConfigurationWidget::keyPathChanged(const QString &path)
{
    m_runConfiguration->setCustomKeyPath(path);
    updateSummary();
}

void S60DeviceRunConfigurationWidget::updateSummary()
{
    //: Summary text of S60 device run configuration
    const QString device = m_serialPortsCombo->currentIndex() != -1 ?
                           m_serialPortsCombo->currentText() :
                           tr("<No Device>");
    const QString signature = m_runConfiguration->signingMode() == S60DeviceRunConfiguration::SignCustom ?
                              tr("(custom certificate)") :
                              tr("(self-signed certificate)");
    m_detailsWidget->setSummaryText(tr("Summary: Run on '%1' %2").arg(device, signature));
}

void S60DeviceRunConfigurationWidget::clearDeviceInfo()
{
    // Restore text & color
    m_deviceInfoLabel->clear();
    m_deviceInfoLabel->setStyleSheet(QString());
}

void S60DeviceRunConfigurationWidget::setDeviceInfoLabel(const QString &message, bool isError)
{
    m_deviceInfoLabel->setStyleSheet(isError ?
                                     QString(QLatin1String("background-color: red;")) :
                                     QString());
    m_deviceInfoLabel->setText(message);
}

void S60DeviceRunConfigurationWidget::updateDeviceInfo()
{
    QString message;
    setDeviceInfoLabel(tr("Connecting..."));
    const bool ok = getDeviceInfo(&message);
    setDeviceInfoLabel(message, !ok);
}

bool S60DeviceRunConfigurationWidget::getDeviceInfo(QString *message)
{
    // Do a launcher run with the ping protocol. Instantiate launcher on heap
    // as not to introduce delays when destructing a device with timeout
    trk::Launcher *launcher = new trk::Launcher(trk::Launcher::ActionPingOnly, this);
    launcher->setTrkServerName(currentPortName());
    if (!launcher->startServer(message)) {
        launcher->deleteLater();
        return false;
    }
    // Set up event loop in the foreground with a timer to quit in case of  timeout.
    QEventLoop eventLoop;
    if (!m_infoTimeOutTimer) {
        m_infoTimeOutTimer = new QTimer(this);
        m_infoTimeOutTimer->setInterval(3000);
        m_infoTimeOutTimer->setSingleShot(true);
    }
    connect(m_infoTimeOutTimer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
    connect(launcher, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    // Go!
    QApplication::setOverrideCursor(Qt::BusyCursor);
    m_infoTimeOutTimer->start();
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
    m_infoTimeOutTimer->disconnect();
    QApplication::restoreOverrideCursor();
    // Anything received?
    *message = launcher->deviceDescription();
    launcher->deleteLater();
    if (message->isEmpty()) {
        *message = tr("A timeout occurred while querying the device. Check whether Trk is running");
        return false;
    }
    return true;
}

} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>S60: Swap spacers in device run config widget.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "s60devicerunconfigurationwidget.h"
#include "s60devicerunconfiguration.h"
#include "s60manager.h"
#include "launcher.h"
#include "serialdevicelister.h"

#include <utils/detailswidget.h>
#include <utils/qtcassert.h>
#include <utils/pathchooser.h>

#include <QtCore/QTimer>
#include <QtGui/QRadioButton>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QComboBox>
#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QFormLayout>
#include <QtGui/QToolButton>
#include <QtGui/QStyle>
#include <QtGui/QApplication>
#include <QtGui/QSpacerItem>

namespace Qt4ProjectManager {
namespace Internal {

S60DeviceRunConfigurationWidget::S60DeviceRunConfigurationWidget(
            S60DeviceRunConfiguration *runConfiguration,
            QWidget *parent)
    : QWidget(parent),
    m_runConfiguration(runConfiguration),
    m_detailsWidget(new Utils::DetailsWidget),
    m_serialPortsCombo(new QComboBox),
    m_nameLineEdit(new QLineEdit(m_runConfiguration->name())),
    m_sisxFileLabel(new QLabel(m_runConfiguration->basePackageFilePath() + QLatin1String(".sisx"))),
    m_deviceInfoButton(new QToolButton),
    m_deviceInfoDescriptionLabel(new QLabel(tr("Device:"))),
    m_deviceInfoLabel(new QLabel),
    m_infoTimeOutTimer(0)
{
    QVBoxLayout *mainBoxLayout = new QVBoxLayout();
    mainBoxLayout->setMargin(0);
    setLayout(mainBoxLayout);
    mainBoxLayout->addWidget(m_detailsWidget);
    QWidget *detailsContainer = new QWidget;
    m_detailsWidget->setWidget(detailsContainer);

    QVBoxLayout *detailsBoxLayout = new QVBoxLayout();
    detailsBoxLayout->setMargin(0);
    detailsContainer->setLayout(detailsBoxLayout);

    QFormLayout *formLayout = new QFormLayout();
    formLayout->setMargin(0);
    detailsBoxLayout->addLayout(formLayout);
    // Name control
    QLabel *nameLabel = new QLabel(tr("Name:"));
    nameLabel->setBuddy(m_nameLineEdit);
    formLayout->addRow(nameLabel, m_nameLineEdit);
    formLayout->addRow(tr("Install File:"), m_sisxFileLabel);

    updateSerialDevices();
    connect(S60Manager::instance()->serialDeviceLister(), SIGNAL(updated()),
            this, SLOT(updateSerialDevices()));
    // Serial devices control
    connect(m_serialPortsCombo, SIGNAL(activated(int)), this, SLOT(setSerialPort(int)));
    QHBoxLayout *serialPortHBoxLayout = new QHBoxLayout;
    serialPortHBoxLayout->addWidget(m_serialPortsCombo);
    serialPortHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));

    formLayout->addRow(tr("Device on Serial Port:"), serialPortHBoxLayout);

    // Device Info with button. Widgets are enabled in above call to updateSerialDevices()
    QHBoxLayout *infoHBoxLayout = new QHBoxLayout;
    m_deviceInfoLabel->setWordWrap(true);
    infoHBoxLayout->addWidget(m_deviceInfoLabel);
    infoHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
    infoHBoxLayout->addWidget(m_deviceInfoButton);
    m_deviceInfoButton->setIcon(qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation));
    m_deviceInfoButton->setToolTip(tr("Queries the device for information"));
    connect(m_deviceInfoButton, SIGNAL(clicked()), this, SLOT(updateDeviceInfo()));
    formLayout->addRow(m_deviceInfoDescriptionLabel, infoHBoxLayout);

    // Signature/certificate stuff.
    QWidget *signatureWidget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout();
    signatureWidget->setLayout(layout);
    detailsBoxLayout->addWidget(signatureWidget);
    QRadioButton *selfSign = new QRadioButton(tr("Self-signed certificate"));
    QHBoxLayout *customHBox = new QHBoxLayout();
    customHBox->setMargin(0);
    QVBoxLayout *radioLayout = new QVBoxLayout();
    QRadioButton *customSignature = new QRadioButton();
    radioLayout->addWidget(customSignature);
    radioLayout->addStretch(10);
    customHBox->addLayout(radioLayout);
    QFormLayout *customLayout = new QFormLayout();
    customLayout->setMargin(0);
    customLayout->setLabelAlignment(Qt::AlignRight);
    Utils::PathChooser *signaturePath = new Utils::PathChooser();
    signaturePath->setExpectedKind(Utils::PathChooser::File);
    signaturePath->setPromptDialogTitle(tr("Choose certificate file (.cer)"));
    customLayout->addRow(new QLabel(tr("Custom certificate:")), signaturePath);
    Utils::PathChooser *keyPath = new Utils::PathChooser();
    keyPath->setExpectedKind(Utils::PathChooser::File);
    keyPath->setPromptDialogTitle(tr("Choose key file (.key / .pem)"));
    customLayout->addRow(new QLabel(tr("Key file:")), keyPath);
    customHBox->addLayout(customLayout);
    customHBox->addStretch(10);
    layout->addWidget(selfSign);
    layout->addLayout(customHBox);
    layout->addStretch(10);

    switch (m_runConfiguration->signingMode()) {
    case S60DeviceRunConfiguration::SignSelf:
        selfSign->setChecked(true);
        break;
    case S60DeviceRunConfiguration::SignCustom:
        customSignature->setChecked(true);
        break;
    }

    signaturePath->setPath(m_runConfiguration->customSignaturePath());
    keyPath->setPath(m_runConfiguration->customKeyPath());

    connect(m_nameLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(nameEdited(QString)));
    connect(m_runConfiguration, SIGNAL(targetInformationChanged()),
            this, SLOT(updateTargetInformation()));
    connect(selfSign, SIGNAL(toggled(bool)), this, SLOT(selfSignToggled(bool)));
    connect(customSignature, SIGNAL(toggled(bool)), this, SLOT(customSignatureToggled(bool)));
    connect(signaturePath, SIGNAL(changed(QString)), this, SLOT(signaturePathChanged(QString)));
    connect(keyPath, SIGNAL(changed(QString)), this, SLOT(keyPathChanged(QString)));
    updateSummary();
}

void S60DeviceRunConfigurationWidget::updateSerialDevices()
{
    m_serialPortsCombo->clear();
    clearDeviceInfo();
    const QString previousRunConfigurationPortName = m_runConfiguration->serialPortName();
    const QList<SerialDeviceLister::SerialDevice> serialDevices = S60Manager::instance()->serialDeviceLister()->serialDevices();
    int newIndex = -1;
    for (int i = 0; i < serialDevices.size(); ++i) {
        const SerialDeviceLister::SerialDevice &device = serialDevices.at(i);
        m_serialPortsCombo->addItem(device.friendlyName, device.portName);
        if (device.portName == previousRunConfigurationPortName)
            newIndex = i;
    }
    // Set new index: prefer to keep old or set to 0, if available.
    if (newIndex == -1 && !serialDevices.empty())
        newIndex = 0;
    m_serialPortsCombo->setCurrentIndex(newIndex);
    if (newIndex == -1) {
        m_deviceInfoButton->setEnabled(false);
        m_runConfiguration->setSerialPortName(QString());
    } else {
        m_deviceInfoButton->setEnabled(true);
        const QString newPortName = portName(newIndex);
        if (newPortName != previousRunConfigurationPortName)
            m_runConfiguration->setSerialPortName(newPortName);
    }
}

QString S60DeviceRunConfigurationWidget::portName(int index) const
{
    return index >= 0 ? m_serialPortsCombo->itemData(index).toString() : QString();
}

QString S60DeviceRunConfigurationWidget::currentPortName() const
{
    return portName(m_serialPortsCombo->currentIndex());
}

void S60DeviceRunConfigurationWidget::nameEdited(const QString &text)
{
    m_runConfiguration->setName(text);
}

void S60DeviceRunConfigurationWidget::updateTargetInformation()
{
    m_sisxFileLabel->setText(m_runConfiguration->basePackageFilePath() + QLatin1String(".sisx"));
}

void S60DeviceRunConfigurationWidget::setSerialPort(int index)
{
    m_runConfiguration->setSerialPortName(portName(index));
    m_deviceInfoButton->setEnabled(index >= 0);
    clearDeviceInfo();
    updateSummary();
}

void S60DeviceRunConfigurationWidget::selfSignToggled(bool toggle)
{
    if (toggle)
        m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignSelf);
    updateSummary();
}

void S60DeviceRunConfigurationWidget::customSignatureToggled(bool toggle)
{
    if (toggle)
        m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignCustom);
    updateSummary();
}

void S60DeviceRunConfigurationWidget::signaturePathChanged(const QString &path)
{
    m_runConfiguration->setCustomSignaturePath(path);
    updateSummary();
}

void S60DeviceRunConfigurationWidget::keyPathChanged(const QString &path)
{
    m_runConfiguration->setCustomKeyPath(path);
    updateSummary();
}

void S60DeviceRunConfigurationWidget::updateSummary()
{
    //: Summary text of S60 device run configuration
    const QString device = m_serialPortsCombo->currentIndex() != -1 ?
                           m_serialPortsCombo->currentText() :
                           tr("<No Device>");
    const QString signature = m_runConfiguration->signingMode() == S60DeviceRunConfiguration::SignCustom ?
                              tr("(custom certificate)") :
                              tr("(self-signed certificate)");
    m_detailsWidget->setSummaryText(tr("Summary: Run on '%1' %2").arg(device, signature));
}

void S60DeviceRunConfigurationWidget::clearDeviceInfo()
{
    // Restore text & color
    m_deviceInfoLabel->clear();
    m_deviceInfoLabel->setStyleSheet(QString());
}

void S60DeviceRunConfigurationWidget::setDeviceInfoLabel(const QString &message, bool isError)
{
    m_deviceInfoLabel->setStyleSheet(isError ?
                                     QString(QLatin1String("background-color: red;")) :
                                     QString());
    m_deviceInfoLabel->setText(message);
}

void S60DeviceRunConfigurationWidget::updateDeviceInfo()
{
    QString message;
    setDeviceInfoLabel(tr("Connecting..."));
    const bool ok = getDeviceInfo(&message);
    setDeviceInfoLabel(message, !ok);
}

bool S60DeviceRunConfigurationWidget::getDeviceInfo(QString *message)
{
    // Do a launcher run with the ping protocol. Instantiate launcher on heap
    // as not to introduce delays when destructing a device with timeout
    trk::Launcher *launcher = new trk::Launcher(trk::Launcher::ActionPingOnly, this);
    launcher->setTrkServerName(currentPortName());
    if (!launcher->startServer(message)) {
        launcher->deleteLater();
        return false;
    }
    // Set up event loop in the foreground with a timer to quit in case of  timeout.
    QEventLoop eventLoop;
    if (!m_infoTimeOutTimer) {
        m_infoTimeOutTimer = new QTimer(this);
        m_infoTimeOutTimer->setInterval(3000);
        m_infoTimeOutTimer->setSingleShot(true);
    }
    connect(m_infoTimeOutTimer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
    connect(launcher, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    // Go!
    QApplication::setOverrideCursor(Qt::BusyCursor);
    m_infoTimeOutTimer->start();
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
    m_infoTimeOutTimer->disconnect();
    QApplication::restoreOverrideCursor();
    // Anything received?
    *message = launcher->deviceDescription();
    launcher->deleteLater();
    if (message->isEmpty()) {
        *message = tr("A timeout occurred while querying the device. Check whether Trk is running");
        return false;
    }
    return true;
}

} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|>


<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

#ifndef IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP
#define IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP

#include "iceoryx_hoofs/cxx/optional.hpp"
#include "iceoryx_hoofs/cxx/vector.hpp"

#include <cassert>
#include <iostream>
#include <limits>

namespace iox
{
namespace rp
{
constexpr uint64_t MAX_POINTER_REPO_CAPACITY{10000U};

/// @brief Allows registration of memory segments with their start pointers and size.
/// This class is used to resolve relative pointers in the corresponding address space of the application.
/// Up to CAPACITY segments can be registered with MIN_ID = 1 to MAX_ID = CAPACITY - 1
/// id 0 is reserved and allows relative pointers to behave like normal pointers
/// (which is equivalent to measure the offset relative to 0).
template <typename id_t, typename ptr_t, uint64_t CAPACITY = MAX_POINTER_REPO_CAPACITY>
class PointerRepository
{
  private:
    struct Info
    {
        ptr_t basePtr{nullptr};
        ptr_t endPtr{nullptr};
    };

    static constexpr id_t MIN_ID{1U};
    static constexpr id_t MAX_ID{CAPACITY - 1U};

    static_assert(MAX_ID >= MIN_ID, "MAX_ID must be greater or equal than MIN_ID!");
    static_assert(CAPACITY >= 2, "CAPACITY must be at least 2!");

  public:
    /// @note 0 is a special purpose id and reserved
    /// id 0 is reserved to interpret the offset just as a raw pointer,
    /// i.e. its corresponding base ptr is 0
    static constexpr id_t RAW_POINTER_BEHAVIOUR{0};

    /// @brief default constructor
    PointerRepository() noexcept;

    PointerRepository(const PointerRepository&) = delete;
    PointerRepository(PointerRepository&&) = delete;
    PointerRepository& operator=(const PointerRepository&) = delete;
    PointerRepository& operator=(PointerRepository&&) = delete;

    /// @brief registers the start pointer of the segment in another application with a specific id
    /// @param[in] id identifies the segment which the pointer should be added to
    /// @param[in] ptr is the start pointer of the segment
    /// @param[in] size is the size of the segment
    /// @return true if the registration was successful, otherwise false
    bool registerPtrWithId(id_t id, ptr_t ptr, uint64_t size) noexcept;

    /// @brief registers the start pointer of a segment with a specific size
    /// @param[in] ptr is the start pointer of the segment
    /// @param[in] size is the size of the segment
    /// @return the segment id wrapped in an cxx::optional to which the pointer was added, cxx::nullopt if pointer was
    /// not added
    cxx::optional<id_t> registerPtr(const ptr_t ptr, uint64_t size = 0U) noexcept;

    /// @brief unregisters the id
    /// @param[in] id is the id to be unregistered
    /// @return true if successful, otherwise false
    /// @attention the relative pointers corresponding to this id become unsafe to use
    bool unregisterPtr(id_t id) noexcept;

    /// @brief unregisters all ids
    /// @attention the relative pointers corresponding to this id become unsafe to use
    void unregisterAll() noexcept;

    /// @brief gets the base pointer, i.e. the starting address, associated with id
    /// @param[in] id is the segment id
    /// @return the base pointer associated with the id
    ptr_t getBasePtr(id_t id) const noexcept;

    /// @brief returns the id for a given pointer ptr
    /// @param[in] ptr is the pointer whose corresponding id is searched for
    /// @return the id the pointer was registered to
    id_t searchId(ptr_t ptr) const noexcept;

  private:
    /// @todo: if required protect vector against concurrent modification
    /// whether this is required depends on the use case, we currently do not need it
    /// we control the ids, so if they are consecutive we only need a vector/array to get the address
    /// this variable exists once per application using relative pointers,
    /// and each needs to initialize it via register calls above

    iox::cxx::vector<Info, CAPACITY> m_info;
    uint64_t m_maxRegistered{0U};
};
} // namespace rp
} // namespace iox

#include "iceoryx_hoofs/internal/relocatable_pointer/pointer_repository.inl"

#endif // IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP
<commit_msg>iox-#605 Fix clang-tidy warning by adding d'tor to PointerRepository<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

#ifndef IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP
#define IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP

#include "iceoryx_hoofs/cxx/optional.hpp"
#include "iceoryx_hoofs/cxx/vector.hpp"

#include <cassert>
#include <iostream>
#include <limits>

namespace iox
{
namespace rp
{
constexpr uint64_t MAX_POINTER_REPO_CAPACITY{10000U};

/// @brief Allows registration of memory segments with their start pointers and size.
/// This class is used to resolve relative pointers in the corresponding address space of the application.
/// Up to CAPACITY segments can be registered with MIN_ID = 1 to MAX_ID = CAPACITY - 1
/// id 0 is reserved and allows relative pointers to behave like normal pointers
/// (which is equivalent to measure the offset relative to 0).
template <typename id_t, typename ptr_t, uint64_t CAPACITY = MAX_POINTER_REPO_CAPACITY>
class PointerRepository
{
  private:
    struct Info
    {
        ptr_t basePtr{nullptr};
        ptr_t endPtr{nullptr};
    };

    static constexpr id_t MIN_ID{1U};
    static constexpr id_t MAX_ID{CAPACITY - 1U};

    static_assert(MAX_ID >= MIN_ID, "MAX_ID must be greater or equal than MIN_ID!");
    static_assert(CAPACITY >= 2, "CAPACITY must be at least 2!");

  public:
    /// @note 0 is a special purpose id and reserved
    /// id 0 is reserved to interpret the offset just as a raw pointer,
    /// i.e. its corresponding base ptr is 0
    static constexpr id_t RAW_POINTER_BEHAVIOUR{0};

    /// @brief default constructor
    PointerRepository() noexcept;
    ~PointerRepository() noexcept = default;

    PointerRepository(const PointerRepository&) = delete;
    PointerRepository(PointerRepository&&) = delete;
    PointerRepository& operator=(const PointerRepository&) = delete;
    PointerRepository& operator=(PointerRepository&&) = delete;

    /// @brief registers the start pointer of the segment in another application with a specific id
    /// @param[in] id identifies the segment which the pointer should be added to
    /// @param[in] ptr is the start pointer of the segment
    /// @param[in] size is the size of the segment
    /// @return true if the registration was successful, otherwise false
    bool registerPtrWithId(id_t id, ptr_t ptr, uint64_t size) noexcept;

    /// @brief registers the start pointer of a segment with a specific size
    /// @param[in] ptr is the start pointer of the segment
    /// @param[in] size is the size of the segment
    /// @return the segment id wrapped in an cxx::optional to which the pointer was added, cxx::nullopt if pointer was
    /// not added
    cxx::optional<id_t> registerPtr(const ptr_t ptr, uint64_t size = 0U) noexcept;

    /// @brief unregisters the id
    /// @param[in] id is the id to be unregistered
    /// @return true if successful, otherwise false
    /// @attention the relative pointers corresponding to this id become unsafe to use
    bool unregisterPtr(id_t id) noexcept;

    /// @brief unregisters all ids
    /// @attention the relative pointers corresponding to this id become unsafe to use
    void unregisterAll() noexcept;

    /// @brief gets the base pointer, i.e. the starting address, associated with id
    /// @param[in] id is the segment id
    /// @return the base pointer associated with the id
    ptr_t getBasePtr(id_t id) const noexcept;

    /// @brief returns the id for a given pointer ptr
    /// @param[in] ptr is the pointer whose corresponding id is searched for
    /// @return the id the pointer was registered to
    id_t searchId(ptr_t ptr) const noexcept;

  private:
    /// @todo: if required protect vector against concurrent modification
    /// whether this is required depends on the use case, we currently do not need it
    /// we control the ids, so if they are consecutive we only need a vector/array to get the address
    /// this variable exists once per application using relative pointers,
    /// and each needs to initialize it via register calls above

    iox::cxx::vector<Info, CAPACITY> m_info;
    uint64_t m_maxRegistered{0U};
};
} // namespace rp
} // namespace iox

#include "iceoryx_hoofs/internal/relocatable_pointer/pointer_repository.inl"

#endif // IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP
<|endoftext|>