<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. 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 "modules/perception/obstacle/onboard/lidar_process.h"

#include <string>
#include <vector>

#include "gtest/gtest.h"
#include "pcl/io/pcd_io.h"

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/pcl_util/pcl_types.h"
#include "modules/perception/obstacle/lidar/dummy/dummy_algorithms.h"

namespace apollo {
namespace perception {

using std::vector;
using pcl_util::Point;
using pcl_util::PointCloud;
using pcl_util::PointCloudPtr;
using Eigen::Matrix4d;

class LidarProcessTest : public testing::Test {
 protected:
  LidarProcessTest() {
    common::adapter::AdapterManagerConfig config;
    config.set_is_ros(false);
    {
      auto *sub_config = config.add_config();
      sub_config->set_mode(common::adapter::AdapterConfig::PUBLISH_ONLY);
      sub_config->set_type(
          common::adapter::AdapterConfig::PERCEPTION_OBSTACLES);
    }

    common::adapter::AdapterManager::Init(config);
  }
  virtual ~LidarProcessTest() {}

  LidarProcess lidar_process_;
};

TEST_F(LidarProcessTest, test_Init) {
  lidar_process_.inited_ = true;
  EXPECT_TRUE(lidar_process_.Init());
  lidar_process_.inited_ = false;

  FLAGS_work_root = "modules/perception/data";
  FLAGS_enable_hdmap_input = false;
  EXPECT_FALSE(lidar_process_.InitFrameDependence());
  EXPECT_FALSE(lidar_process_.Init());
  FLAGS_config_manager_path = "./config_manager_test/config_manager.config";
  FLAGS_enable_hdmap_input = false;
  EXPECT_TRUE(lidar_process_.InitFrameDependence());

  FLAGS_onboard_roi_filter = "not_exit_algo";
  FLAGS_onboard_segmentor = "not_exit_algo";
  FLAGS_onboard_object_builder = "not_exit_algo";
  FLAGS_onboard_tracker = "not_exit_algo";
  EXPECT_FALSE(lidar_process_.InitAlgorithmPlugin());
  FLAGS_onboard_roi_filter = "DummyROIFilter";
  EXPECT_FALSE(lidar_process_.InitAlgorithmPlugin());

  FLAGS_onboard_segmentor = "DummySegmentation";
  EXPECT_FALSE(lidar_process_.InitAlgorithmPlugin());

  FLAGS_onboard_object_builder = "DummyObjectBuilder";
  EXPECT_FALSE(lidar_process_.InitAlgorithmPlugin());
  EXPECT_FALSE(lidar_process_.Init());

  FLAGS_onboard_tracker = "DummyTracker";
  EXPECT_TRUE(lidar_process_.InitAlgorithmPlugin());

  EXPECT_TRUE(lidar_process_.Init());
  EXPECT_TRUE(lidar_process_.inited_);
}

TEST_F(LidarProcessTest, test_Process) {
  std::string pcd_file =
      "modules/perception/data/hm_tracker_test/"
      "QN68P2_12_1476265365_1476265665_2.pcd";
  PointCloudPtr point_cloud(new PointCloud);
  pcl::PointCloud<pcl_util::PointXYZIT>::Ptr org_cloud(
      new pcl::PointCloud<pcl_util::PointXYZIT>);
  pcl::io::loadPCDFile(pcd_file, *org_cloud);
  point_cloud->points.reserve(org_cloud->points.size());
  for (size_t i = 0; i < org_cloud->points.size(); ++i) {
    Point pt;
    pt.x = org_cloud->points[i].x;
    pt.y = org_cloud->points[i].y;
    pt.z = org_cloud->points[i].z;
    pt.intensity = org_cloud->points[i].intensity;
    if (isnan(org_cloud->points[i].x)) continue;
    point_cloud->push_back(pt);
  }
  std::shared_ptr<Matrix4d> velodyne_trans = std::make_shared<Matrix4d>();
  (*velodyne_trans) << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;
  lidar_process_.hdmap_input_ = HDMapInput::instance();
  EXPECT_TRUE(lidar_process_.Process(123.0, point_cloud, velodyne_trans));
}

TEST_F(LidarProcessTest, test_GeneratePbMsg) {
  double timestamp = 1234.567;
  lidar_process_.timestamp_ = timestamp;
  vector<ObjectPtr> objs;
  ObjectPtr obj1 = std::make_shared<Object>();
  obj1->type = VEHICLE;
  objs.push_back(obj1);
  ObjectPtr obj2 = std::make_shared<Object>();
  obj2->type = PEDESTRIAN;
  objs.push_back(obj2);
  lidar_process_.objects_ = objs;

  PerceptionObstacles obstacles;
  EXPECT_TRUE(lidar_process_.GeneratePbMsg(&obstacles));
  EXPECT_EQ(obstacles.perception_obstacle_size(), 2);
  EXPECT_EQ(obstacles.perception_obstacle(0).type(),
            PerceptionObstacle::VEHICLE);
  EXPECT_EQ(obstacles.perception_obstacle(1).type(),
            PerceptionObstacle::PEDESTRIAN);
}

}  // namespace perception
}  // namespace apollo
<commit_msg>Perception: fixed namespace (#1141)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. 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 "modules/perception/obstacle/onboard/lidar_process.h"

#include <string>
#include <vector>

#include "gtest/gtest.h"
#include "pcl/io/pcd_io.h"

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/common/log.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/pcl_util/pcl_types.h"
#include "modules/perception/obstacle/lidar/dummy/dummy_algorithms.h"

namespace apollo {
namespace perception {

using Eigen::Matrix4d;
using pcl_util::Point;
using pcl_util::PointCloud;
using pcl_util::PointCloudPtr;
using std::vector;

class LidarProcessTest : public testing::Test {
 protected:
  LidarProcessTest() {
    common::adapter::AdapterManagerConfig config;
    config.set_is_ros(false);
    {
      auto *sub_config = config.add_config();
      sub_config->set_mode(common::adapter::AdapterConfig::PUBLISH_ONLY);
      sub_config->set_type(
          common::adapter::AdapterConfig::PERCEPTION_OBSTACLES);
    }

    common::adapter::AdapterManager::Init(config);
  }
  virtual ~LidarProcessTest() {}

  LidarProcess lidar_process_;
};

TEST_F(LidarProcessTest, test_Init) {
  lidar_process_.inited_ = true;
  EXPECT_TRUE(lidar_process_.Init());
  lidar_process_.inited_ = false;

  FLAGS_work_root = "modules/perception/data";
  FLAGS_enable_hdmap_input = false;
  EXPECT_FALSE(lidar_process_.InitFrameDependence());
  EXPECT_FALSE(lidar_process_.Init());
  FLAGS_config_manager_path = "./config_manager_test/config_manager.config";
  FLAGS_enable_hdmap_input = false;
  EXPECT_TRUE(lidar_process_.InitFrameDependence());

  FLAGS_onboard_roi_filter = "not_exit_algo";
  FLAGS_onboard_segmentor = "not_exit_algo";
  FLAGS_onboard_object_builder = "not_exit_algo";
  FLAGS_onboard_tracker = "not_exit_algo";
  EXPECT_FALSE(lidar_process_.InitAlgorithmPlugin());
  FLAGS_onboard_roi_filter = "DummyROIFilter";
  EXPECT_FALSE(lidar_process_.InitAlgorithmPlugin());

  FLAGS_onboard_segmentor = "DummySegmentation";
  EXPECT_FALSE(lidar_process_.InitAlgorithmPlugin());

  FLAGS_onboard_object_builder = "DummyObjectBuilder";
  EXPECT_FALSE(lidar_process_.InitAlgorithmPlugin());
  EXPECT_FALSE(lidar_process_.Init());

  FLAGS_onboard_tracker = "DummyTracker";
  EXPECT_TRUE(lidar_process_.InitAlgorithmPlugin());

  EXPECT_TRUE(lidar_process_.Init());
  EXPECT_TRUE(lidar_process_.inited_);
}

TEST_F(LidarProcessTest, test_Process) {
  std::string pcd_file =
      "modules/perception/data/hm_tracker_test/"
      "QN68P2_12_1476265365_1476265665_2.pcd";
  PointCloudPtr point_cloud(new PointCloud);
  pcl::PointCloud<pcl_util::PointXYZIT>::Ptr org_cloud(
      new pcl::PointCloud<pcl_util::PointXYZIT>);
  pcl::io::loadPCDFile(pcd_file, *org_cloud);
  point_cloud->points.reserve(org_cloud->points.size());
  for (size_t i = 0; i < org_cloud->points.size(); ++i) {
    pcl_util::Point pt;
    pt.x = org_cloud->points[i].x;
    pt.y = org_cloud->points[i].y;
    pt.z = org_cloud->points[i].z;
    pt.intensity = org_cloud->points[i].intensity;
    if (isnan(org_cloud->points[i].x)) continue;
    point_cloud->push_back(pt);
  }
  std::shared_ptr<Matrix4d> velodyne_trans = std::make_shared<Matrix4d>();
  (*velodyne_trans) << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;
  lidar_process_.hdmap_input_ = HDMapInput::instance();
  EXPECT_TRUE(lidar_process_.Process(123.0, point_cloud, velodyne_trans));
}

TEST_F(LidarProcessTest, test_GeneratePbMsg) {
  double timestamp = 1234.567;
  lidar_process_.timestamp_ = timestamp;
  vector<ObjectPtr> objs;
  ObjectPtr obj1 = std::make_shared<Object>();
  obj1->type = VEHICLE;
  objs.push_back(obj1);
  ObjectPtr obj2 = std::make_shared<Object>();
  obj2->type = PEDESTRIAN;
  objs.push_back(obj2);
  lidar_process_.objects_ = objs;

  PerceptionObstacles obstacles;
  EXPECT_TRUE(lidar_process_.GeneratePbMsg(&obstacles));
  EXPECT_EQ(obstacles.perception_obstacle_size(), 2);
  EXPECT_EQ(obstacles.perception_obstacle(0).type(),
            PerceptionObstacle::VEHICLE);
  EXPECT_EQ(obstacles.perception_obstacle(1).type(),
            PerceptionObstacle::PEDESTRIAN);
}

}  // namespace perception
}  // namespace apollo
<|endoftext|>


<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/
#include "ElasticEnergyMaterial.h"
#include "RankTwoTensor.h"
#include "ElasticityTensorR4.h"

template<>
InputParameters validParams<ElasticEnergyMaterial>()
{
  InputParameters params = validParams<DerivativeFunctionMaterialBase>();
  params.addClassDescription("Free energy material for the elastic energy contributions.");
  params.addParam<std::string>("base_name", "Material property base name");
  params.addRequiredCoupledVar("args", "Arguments of F() - use vector coupling");
  return params;
}

ElasticEnergyMaterial::ElasticEnergyMaterial(const InputParameters & parameters) :
    DerivativeFunctionMaterialBase(parameters),
    _base_name(isParamValid("base_name") ? getParam<std::string>("base_name") + "_" : "" ),
    _stress(getMaterialPropertyByName<RankTwoTensor>(_base_name + "stress")),
    _elasticity_tensor(getMaterialPropertyByName<ElasticityTensorR4>(_base_name + "elasticity_tensor")),
    _strain(getMaterialPropertyByName<RankTwoTensor>(_base_name + "elastic_strain"))
{
  _dstrain.resize(_nargs);
  _d2strain.resize(_nargs);
  _delasticity_tensor.resize(_nargs);
  _d2elasticity_tensor.resize(_nargs);

  // fetch stress and elasticity tensor derivatives (in simple eigenstrain models this is is only w.r.t. 'c')
  for (unsigned int i = 0; i < _nargs; ++i)
  {
    _dstrain[i]            = &getMaterialPropertyDerivativeByName<RankTwoTensor>(_base_name + "elastic_strain", _arg_names[i]);
    _delasticity_tensor[i] = &getMaterialPropertyDerivativeByName<ElasticityTensorR4>(_base_name + "elasticity_tensor", _arg_names[i]);

    _d2strain[i].resize(_nargs);
    _d2elasticity_tensor[i].resize(_nargs);

    for (unsigned int j = 0; j < _nargs; ++j)
    {
      _d2strain[i][j]            = &getMaterialPropertyDerivativeByName<RankTwoTensor>(_base_name + "elastic_strain", _arg_names[i], _arg_names[j]);
      _d2elasticity_tensor[i][j] = &getMaterialPropertyDerivativeByName<ElasticityTensorR4>(_base_name + "elasticity_tensor", _arg_names[i], _arg_names[j]);
    }
  }
}

Real
ElasticEnergyMaterial::computeF()
{
  return 0.5 * _stress[_qp].doubleContraction(_strain[_qp]);
}

Real
ElasticEnergyMaterial::computeDF(unsigned int i_var)
{
  unsigned int i = argIndex(i_var);

  // product rule d/di computeF
  return 0.5 * (
    ( // dstress/di
        (*_delasticity_tensor[i])[_qp] * _strain[_qp]
      + _elasticity_tensor[_qp] * (*_dstrain[i])[_qp]
    ).doubleContraction(_strain[_qp])

    + _stress[_qp].doubleContraction((*_dstrain[i])[_qp])
  );
}

Real
ElasticEnergyMaterial::computeD2F(unsigned int i_var, unsigned int j_var)
{
  unsigned int i = argIndex(i_var);
  unsigned int j = argIndex(j_var);

  // product rule d/dj computeDF
  return 0.5 * (
    (
        (*_d2elasticity_tensor[i][j])[_qp] * _strain[_qp]
      + (*_delasticity_tensor[i])[_qp] * (*_dstrain[j])[_qp]
      + (*_delasticity_tensor[j])[_qp] * (*_dstrain[i])[_qp]
      + _elasticity_tensor[_qp] * (*_d2strain[i][j])[_qp]
    ).doubleContraction(_strain[_qp])
    + (
        (*_delasticity_tensor[i])[_qp] * _strain[_qp]
      + _elasticity_tensor[_qp] * (*_dstrain[i])[_qp]
    ).doubleContraction((*_dstrain[j])[_qp])

    + ( // dstress/dj
          (*_delasticity_tensor[j])[_qp] * _strain[_qp]
        + _elasticity_tensor[_qp] * (*_dstrain[j])[_qp]
      ).doubleContraction((*_dstrain[i])[_qp])
    + _stress[_qp].doubleContraction((*_d2strain[i][j])[_qp])
  );
}

<commit_msg>Simplify first derivative of elastic free energy (#5631)<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/
#include "ElasticEnergyMaterial.h"
#include "RankTwoTensor.h"
#include "ElasticityTensorR4.h"

template<>
InputParameters validParams<ElasticEnergyMaterial>()
{
  InputParameters params = validParams<DerivativeFunctionMaterialBase>();
  params.addClassDescription("Free energy material for the elastic energy contributions.");
  params.addParam<std::string>("base_name", "Material property base name");
  params.addRequiredCoupledVar("args", "Arguments of F() - use vector coupling");
  return params;
}

ElasticEnergyMaterial::ElasticEnergyMaterial(const InputParameters & parameters) :
    DerivativeFunctionMaterialBase(parameters),
    _base_name(isParamValid("base_name") ? getParam<std::string>("base_name") + "_" : "" ),
    _stress(getMaterialPropertyByName<RankTwoTensor>(_base_name + "stress")),
    _elasticity_tensor(getMaterialPropertyByName<ElasticityTensorR4>(_base_name + "elasticity_tensor")),
    _strain(getMaterialPropertyByName<RankTwoTensor>(_base_name + "elastic_strain"))
{
  _dstrain.resize(_nargs);
  _d2strain.resize(_nargs);
  _delasticity_tensor.resize(_nargs);
  _d2elasticity_tensor.resize(_nargs);

  // fetch stress and elasticity tensor derivatives (in simple eigenstrain models this is is only w.r.t. 'c')
  for (unsigned int i = 0; i < _nargs; ++i)
  {
    _dstrain[i]            = &getMaterialPropertyDerivativeByName<RankTwoTensor>(_base_name + "elastic_strain", _arg_names[i]);
    _delasticity_tensor[i] = &getMaterialPropertyDerivativeByName<ElasticityTensorR4>(_base_name + "elasticity_tensor", _arg_names[i]);

    _d2strain[i].resize(_nargs);
    _d2elasticity_tensor[i].resize(_nargs);

    for (unsigned int j = 0; j < _nargs; ++j)
    {
      _d2strain[i][j]            = &getMaterialPropertyDerivativeByName<RankTwoTensor>(_base_name + "elastic_strain", _arg_names[i], _arg_names[j]);
      _d2elasticity_tensor[i][j] = &getMaterialPropertyDerivativeByName<ElasticityTensorR4>(_base_name + "elasticity_tensor", _arg_names[i], _arg_names[j]);
    }
  }
}

Real
ElasticEnergyMaterial::computeF()
{
  return 0.5 * _stress[_qp].doubleContraction(_strain[_qp]);
}

Real
ElasticEnergyMaterial::computeDF(unsigned int i_var)
{
  unsigned int i = argIndex(i_var);

  // product rule d/di computeF (doubleContraction commutes)
  return 0.5 * ((*_delasticity_tensor[i])[_qp] * _strain[_qp]).doubleContraction(_strain[_qp]) +
         (_elasticity_tensor[_qp] * (*_dstrain[i])[_qp]).doubleContraction(_strain[_qp]);
}

Real
ElasticEnergyMaterial::computeD2F(unsigned int i_var, unsigned int j_var)
{
  unsigned int i = argIndex(i_var);
  unsigned int j = argIndex(j_var);

  // product rule d/dj computeDF
  // TODO: simplify because doubleContraction commutes
  return 0.5 * (
    (
        (*_d2elasticity_tensor[i][j])[_qp] * _strain[_qp]
      + (*_delasticity_tensor[i])[_qp] * (*_dstrain[j])[_qp]
      + (*_delasticity_tensor[j])[_qp] * (*_dstrain[i])[_qp]
      + _elasticity_tensor[_qp] * (*_d2strain[i][j])[_qp]
    ).doubleContraction(_strain[_qp])
    + (
        (*_delasticity_tensor[i])[_qp] * _strain[_qp]
      + _elasticity_tensor[_qp] * (*_dstrain[i])[_qp]
    ).doubleContraction((*_dstrain[j])[_qp])

    + ( // dstress/dj
          (*_delasticity_tensor[j])[_qp] * _strain[_qp]
        + _elasticity_tensor[_qp] * (*_dstrain[j])[_qp]
      ).doubleContraction((*_dstrain[i])[_qp])
    + _stress[_qp].doubleContraction((*_d2strain[i][j])[_qp])
  );
}
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2012-2021 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/qtwidgets/properties/boolpropertywidgetqt.h>

#include <warn/push>
#include <warn/ignore/all>
#include <QCheckBox>
#include <QLineEdit>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QHBoxLayout>
#include <warn/pop>

namespace inviwo {

BoolPropertyWidgetQt::BoolPropertyWidgetQt(BoolProperty* property)
    : PropertyWidgetQt(property)
    , property_(property)
    , checkBox_{nullptr}
    , lineEdit_{nullptr}
    , label_{new EditableLabelQt(this, property_, false)} {

    // create widget layout
    QHBoxLayout* hLayout = new QHBoxLayout();
    setSpacingAndMargins(hLayout);
    hLayout->addWidget(label_);

    if (property_->getSemantics() == PropertySemantics::Text) {
        lineEdit_ = new QLineEdit();
        // adjust size policy of line edit
        QSizePolicy sizePolicy(lineEdit_->sizePolicy());
        sizePolicy.setHorizontalStretch(3);
        sizePolicy.setVerticalPolicy(QSizePolicy::Fixed);
        lineEdit_->setSizePolicy(sizePolicy);

        lineEdit_->setEnabled(!property_->getReadOnly());
        // set up a validator accepting "true"/1 and "false"/0
        lineEdit_->setValidator(
            new QRegularExpressionValidator(QRegularExpression("true|false|1|0"), lineEdit_));

        setFocusPolicy(lineEdit_->focusPolicy());
        setFocusProxy(lineEdit_);

        auto setPropertyValueFromString = [=]() {
            QString str(lineEdit_->text());
            property_->set(str == "true" || str == "1");
        };
        connect(lineEdit_, &QLineEdit::editingFinished, setPropertyValueFromString);
        hLayout->addWidget(lineEdit_);
    } else {
        checkBox_ = new QCheckBox();
        checkBox_->setEnabled(!property_->getReadOnly());
        checkBox_->setFixedSize(QSize(15, 15));

        setFocusPolicy(checkBox_->focusPolicy());
        setFocusProxy(checkBox_);

        auto setPropertyValueFromCheckbox = [=](bool checked) { property_->set(checked); };
        connect(checkBox_, &QCheckBox::toggled, setPropertyValueFromCheckbox);
        hLayout->addWidget(checkBox_);
    }

    setLayout(hLayout);

    updateFromProperty();
}

void BoolPropertyWidgetQt::updateFromProperty() {
    if (checkBox_) checkBox_->setChecked(property_->get());
    if (lineEdit_) lineEdit_->setText(property_->get() ? "true" : "false");
}

}  // namespace inviwo
<commit_msg>QtWidgets: context fix BoolProperty<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2012-2021 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/qtwidgets/properties/boolpropertywidgetqt.h>

#include <inviwo/core/util/rendercontext.h>

#include <warn/push>
#include <warn/ignore/all>
#include <QCheckBox>
#include <QLineEdit>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QHBoxLayout>
#include <warn/pop>

namespace inviwo {

BoolPropertyWidgetQt::BoolPropertyWidgetQt(BoolProperty* property)
    : PropertyWidgetQt(property)
    , property_(property)
    , checkBox_{nullptr}
    , lineEdit_{nullptr}
    , label_{new EditableLabelQt(this, property_, false)} {

    // create widget layout
    QHBoxLayout* hLayout = new QHBoxLayout();
    setSpacingAndMargins(hLayout);
    hLayout->addWidget(label_);

    if (property_->getSemantics() == PropertySemantics::Text) {
        lineEdit_ = new QLineEdit();
        // adjust size policy of line edit
        QSizePolicy sizePolicy(lineEdit_->sizePolicy());
        sizePolicy.setHorizontalStretch(3);
        sizePolicy.setVerticalPolicy(QSizePolicy::Fixed);
        lineEdit_->setSizePolicy(sizePolicy);

        lineEdit_->setEnabled(!property_->getReadOnly());
        // set up a validator accepting "true"/1 and "false"/0
        lineEdit_->setValidator(
            new QRegularExpressionValidator(QRegularExpression("true|false|1|0"), lineEdit_));

        setFocusPolicy(lineEdit_->focusPolicy());
        setFocusProxy(lineEdit_);

        auto setPropertyValueFromString = [=]() {
            QString str(lineEdit_->text());
            RenderContext::getPtr()->activateDefaultRenderContext();
            property_->set(str == "true" || str == "1");
        };
        connect(lineEdit_, &QLineEdit::editingFinished, setPropertyValueFromString);
        hLayout->addWidget(lineEdit_);
    } else {
        checkBox_ = new QCheckBox();
        checkBox_->setEnabled(!property_->getReadOnly());
        checkBox_->setFixedSize(QSize(15, 15));

        setFocusPolicy(checkBox_->focusPolicy());
        setFocusProxy(checkBox_);

        auto setPropertyValueFromCheckbox = [=](bool checked) {
            RenderContext::getPtr()->activateDefaultRenderContext();
            property_->set(checked);
        };
        connect(checkBox_, &QCheckBox::toggled, setPropertyValueFromCheckbox);
        hLayout->addWidget(checkBox_);
    }

    setLayout(hLayout);

    updateFromProperty();
}

void BoolPropertyWidgetQt::updateFromProperty() {
    if (checkBox_) checkBox_->setChecked(property_->get());
    if (lineEdit_) lineEdit_->setText(property_->get() ? "true" : "false");
}

}  // namespace inviwo
<|endoftext|>


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

/* Author: Dan Greenwalducan */

#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/warehouse/constraints_storage.h>
#include <moveit/warehouse/state_storage.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <boost/algorithm/string/join.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <ros/ros.h>
#include <moveit_msgs/SaveRobotStateToWarehouse.h>
#include <moveit_msgs/ListRobotStatesInWarehouse.h>
#include <moveit_msgs/GetRobotStateFromWarehouse.h>
#include <moveit_msgs/CheckIfRobotStateExistsInWarehouse.h>

static const std::string ROBOT_DESCRIPTION="robot_description";

bool store_state(moveit_msgs::SaveRobotStateToWarehouse::Request&  request,
                 moveit_msgs::SaveRobotStateToWarehouse::Response& response,
                 moveit_warehouse::RobotStateStorage* rs)
{
  const moveit_msgs::RobotState& state = request.state;
  if ("" == request.name)
  {
    ROS_ERROR("You must specify a name to store a state");
    return response.success = false;
  }
  rs->addRobotState(request.state, request.name, request.robot);
  return response.success = true;
}

bool list_states(moveit_msgs::ListRobotStatesInWarehouse::Request&  request,
                  moveit_msgs::ListRobotStatesInWarehouse::Response& response,
                  moveit_warehouse::RobotStateStorage* rs)
{
  if ("" == request.regex)
  {
    rs->getKnownRobotStates(response.states, request.robot);
  }
  else
  {
    rs->getKnownRobotStates(request.regex, response.states, request.robot);
  }
  return true;
}

bool has_state(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request&  request,
               moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response,
               moveit_warehouse::RobotStateStorage* rs)
{
  response.exists = rs->hasRobotState(request.name, request.robot);
  return true;
}

bool get_state(moveit_msgs::GetRobotStateFromWarehouse::Request&  request,
               moveit_msgs::GetRobotStateFromWarehouse::Response& response,
               moveit_warehouse::RobotStateStorage* rs)
{
  moveit_warehouse::RobotStateWithMetadata state_buffer;
  rs->getRobotState(state_buffer, request.name, request.robot);
  response.state = static_cast<const moveit_msgs::RobotState&>(*state_buffer);
  return true;
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "moveit_warehouse_services");

  boost::program_options::options_description desc;
  desc.add_options()
    ("help", "Show help message")
    ("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
    ("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.");

  boost::program_options::variables_map vm;
  boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
  boost::program_options::notify(vm);

  if (vm.count("help"))
  {
    std::cout << desc << std::endl;
    return 1;
  }

  //  TODO(dg-shadow) check that host + port available. check db is working

  ros::AsyncSpinner spinner(1);
  spinner.start();

  moveit_warehouse::RobotStateStorage rs(vm.count("host") ? vm["host"].as<std::string>() : "",
                                         vm.count("port") ? vm["port"].as<std::size_t>() : 0);
  std::vector<std::string> names;
  rs.getKnownRobotStates(names);
  if (names.empty())
    ROS_INFO("There are no previously stored robot states");
  else
  {
    ROS_INFO("Previously stored robot states:");
    for (std::size_t i = 0 ; i < names.size() ; ++i)
      ROS_INFO(" * %s", names[i].c_str());
  }

  boost::function<bool(moveit_msgs::SaveRobotStateToWarehouse::Request&  request,
                       moveit_msgs::SaveRobotStateToWarehouse::Response& response)>
    save_cb = boost::bind(&store_state, _1, _2, &rs);

  boost::function<bool(moveit_msgs::ListRobotStatesInWarehouse::Request&  request,
                       moveit_msgs::ListRobotStatesInWarehouse::Response& response)>
    list_cb = boost::bind(&list_states, _1, _2, &rs);

  boost::function<bool(moveit_msgs::GetRobotStateFromWarehouse::Request&  request,
                       moveit_msgs::GetRobotStateFromWarehouse::Response& response)>
    get_cb = boost::bind(&get_state, _1, _2, &rs);

  boost::function<bool(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request&  request,
                       moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response)>
    has_cb = boost::bind(&has_state, _1, _2, &rs);

  ros::NodeHandle node("~");
  ros::ServiceServer save_state_server  = node.advertiseService("save_robot_state",  save_cb);
  ros::ServiceServer list_states_server = node.advertiseService("list_robot_states", list_cb);
  ros::ServiceServer get_state_server   = node.advertiseService("get_robot_state",   get_cb);
  ros::ServiceServer has_state_server   = node.advertiseService("has_robot_state",   has_cb);

//  ros::Subscriber state_sub = nh.subscribe("robot_state", 100, save_cb);
/*
  std::vector<std::string> topics; psm.getMonitoredTopics(topics);
  ROS_INFO_STREAM("Listening for scene updates on topics " <<
  boost::algorithm::join(topics, ", ")); ROS_INFO_STREAM("Listening
  for planning requests on topic " << mplan_req_sub.getTopic());
  ROS_INFO_STREAM("Listening for named constraints on topic " <<
  constr_sub.getTopic()); ROS_INFO_STREAM("Listening for states on
  topic " << state_sub.getTopic());

*/
  ros::waitForShutdown();
  return 0;
}
<commit_msg>checks db connection is good<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author: Dan Greenwalducan */

#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/warehouse/constraints_storage.h>
#include <moveit/warehouse/state_storage.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <boost/algorithm/string/join.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <ros/ros.h>
#include <moveit_msgs/SaveRobotStateToWarehouse.h>
#include <moveit_msgs/ListRobotStatesInWarehouse.h>
#include <moveit_msgs/GetRobotStateFromWarehouse.h>
#include <moveit_msgs/CheckIfRobotStateExistsInWarehouse.h>

static const std::string ROBOT_DESCRIPTION="robot_description";

bool store_state(moveit_msgs::SaveRobotStateToWarehouse::Request&  request,
                 moveit_msgs::SaveRobotStateToWarehouse::Response& response,
                 moveit_warehouse::RobotStateStorage* rs)
{
  const moveit_msgs::RobotState& state = request.state;
  if ("" == request.name)
  {
    ROS_ERROR("You must specify a name to store a state");
    return response.success = false;
  }
  rs->addRobotState(request.state, request.name, request.robot);
  return response.success = true;
}

bool list_states(moveit_msgs::ListRobotStatesInWarehouse::Request&  request,
                  moveit_msgs::ListRobotStatesInWarehouse::Response& response,
                  moveit_warehouse::RobotStateStorage* rs)
{
  if ("" == request.regex)
  {
    rs->getKnownRobotStates(response.states, request.robot);
  }
  else
  {
    rs->getKnownRobotStates(request.regex, response.states, request.robot);
  }
  return true;
}

bool has_state(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request&  request,
               moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response,
               moveit_warehouse::RobotStateStorage* rs)
{
  response.exists = rs->hasRobotState(request.name, request.robot);
  return true;
}

bool get_state(moveit_msgs::GetRobotStateFromWarehouse::Request&  request,
               moveit_msgs::GetRobotStateFromWarehouse::Response& response,
               moveit_warehouse::RobotStateStorage* rs)
{
  moveit_warehouse::RobotStateWithMetadata state_buffer;
  rs->getRobotState(state_buffer, request.name, request.robot);
  response.state = static_cast<const moveit_msgs::RobotState&>(*state_buffer);
  return true;
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "moveit_warehouse_services");

  boost::program_options::options_description desc;
  desc.add_options()
    ("help", "Show help message")
    ("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
    ("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.");

  boost::program_options::variables_map vm;
  boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
  boost::program_options::notify(vm);

  if (vm.count("help"))
  {
    std::cout << desc << std::endl;
    return 1;
  }

  ros::AsyncSpinner spinner(1);
  spinner.start();

  moveit_warehouse::RobotStateStorage rs;

  std::string host = vm.count("host") ? vm["host"].as<std::string>() : "";
  std::size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0;

  try
  {
    rs = moveit_warehouse::RobotStateStorage(host, port);
  }
  catch (...)
  {
    ROS_FATAL_STREAM("Couldn't connect to MongoDB on " << host << ":" <<  port);
    return -1;
  }

  std::vector<std::string> names;
  rs.getKnownRobotStates(names);
  if (names.empty())
    ROS_INFO("There are no previously stored robot states");
  else
  {
    ROS_INFO("Previously stored robot states:");
    for (std::size_t i = 0 ; i < names.size() ; ++i)
      ROS_INFO(" * %s", names[i].c_str());
  }

  boost::function<bool(moveit_msgs::SaveRobotStateToWarehouse::Request&  request,
                       moveit_msgs::SaveRobotStateToWarehouse::Response& response)>
    save_cb = boost::bind(&store_state, _1, _2, &rs);

  boost::function<bool(moveit_msgs::ListRobotStatesInWarehouse::Request&  request,
                       moveit_msgs::ListRobotStatesInWarehouse::Response& response)>
    list_cb = boost::bind(&list_states, _1, _2, &rs);

  boost::function<bool(moveit_msgs::GetRobotStateFromWarehouse::Request&  request,
                       moveit_msgs::GetRobotStateFromWarehouse::Response& response)>
    get_cb = boost::bind(&get_state, _1, _2, &rs);

  boost::function<bool(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request&  request,
                       moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response)>
    has_cb = boost::bind(&has_state, _1, _2, &rs);

  ros::NodeHandle node("~");
  ros::ServiceServer save_state_server  = node.advertiseService("save_robot_state",  save_cb);
  ros::ServiceServer list_states_server = node.advertiseService("list_robot_states", list_cb);
  ros::ServiceServer get_state_server   = node.advertiseService("get_robot_state",   get_cb);
  ros::ServiceServer has_state_server   = node.advertiseService("has_robot_state",   has_cb);

//  ros::Subscriber state_sub = nh.subscribe("robot_state", 100, save_cb);
/*
  std::vector<std::string> topics; psm.getMonitoredTopics(topics);
  ROS_INFO_STREAM("Listening for scene updates on topics " <<
  boost::algorithm::join(topics, ", ")); ROS_INFO_STREAM("Listening
  for planning requests on topic " << mplan_req_sub.getTopic());
  ROS_INFO_STREAM("Listening for named constraints on topic " <<
  constr_sub.getTopic()); ROS_INFO_STREAM("Listening for states on
  topic " << state_sub.getTopic());

*/
  ros::waitForShutdown();
  return 0;
}
<|endoftext|>


<commit_before>//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DebugMap.h"
#include "BinaryHolder.h"
#include "DebugMap.h"
#include "dsymutil.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
#include "llvm/Object/MachO.h"
#include <string>

namespace llvm {
namespace dsymutil {

namespace {

/// \brief Stores all information relating to a compile unit, be it in
/// its original instance in the object file to its brand new cloned
/// and linked DIE tree.
class CompileUnit {
public:
  /// \brief Information gathered about a DIE in the object file.
  struct DIEInfo {
    uint32_t ParentIdx;
  };

  CompileUnit(DWARFUnit &OrigUnit) : OrigUnit(OrigUnit) {
    Info.resize(OrigUnit.getNumDIEs());
  }

  DWARFUnit &getOrigUnit() const { return OrigUnit; }

  DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
  const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }

private:
  DWARFUnit &OrigUnit;
  std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
};

/// \brief The core of the Dwarf linking logic.
///
/// The link of the dwarf information from the object files will be
/// driven by the selection of 'root DIEs', which are DIEs that
/// describe variables or functions that are present in the linked
/// binary (and thus have entries in the debug map). All the debug
/// information that will be linked (the DIEs, but also the line
/// tables, ranges, ...) is derived from that set of root DIEs.
///
/// The root DIEs are identified because they contain relocations that
/// correspond to a debug map entry at specific places (the low_pc for
/// a function, the location for a variable). These relocations are
/// called ValidRelocs in the DwarfLinker and are gathered as a very
/// first step when we start processing a DebugMapObject.
class DwarfLinker {
public:
  DwarfLinker(StringRef OutputFilename, bool Verbose)
      : OutputFilename(OutputFilename), Verbose(Verbose), BinHolder(Verbose) {}

  /// \brief Link the contents of the DebugMap.
  bool link(const DebugMap &);

private:
  /// \brief Called at the start of a debug object link.
  void startDebugObject(DWARFContext &);

  /// \brief Called at the end of a debug object link.
  void endDebugObject();

  /// \defgroup FindValidRelocations Translate debug map into a list
  /// of relevant relocations
  ///
  /// @{
  struct ValidReloc {
    uint32_t Offset;
    uint32_t Size;
    uint64_t Addend;
    const DebugMapObject::DebugMapEntry *Mapping;

    ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
               const DebugMapObject::DebugMapEntry *Mapping)
        : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}

    bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
  };

  /// \brief The valid relocations for the current DebugMapObject.
  /// This vector is sorted by relocation offset.
  std::vector<ValidReloc> ValidRelocs;

  /// \brief Index into ValidRelocs of the next relocation to
  /// consider. As we walk the DIEs in acsending file offset and as
  /// ValidRelocs is sorted by file offset, keeping this index
  /// uptodate is all we have to do to have a cheap lookup during the
  /// root DIE selection.
  unsigned NextValidReloc;

  bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
                                  const DebugMapObject &DMO);

  bool findValidRelocs(const object::SectionRef &Section,
                       const object::ObjectFile &Obj,
                       const DebugMapObject &DMO);

  void findValidRelocsMachO(const object::SectionRef &Section,
                            const object::MachOObjectFile &Obj,
                            const DebugMapObject &DMO);
  /// @}
private:
  std::string OutputFilename;
  bool Verbose;
  BinaryHolder BinHolder;

  /// The units of the current debug map object.
  std::vector<CompileUnit> Units;
};

/// \brief Recursive helper to gather the child->parent relationships in the
/// original compile unit.
void GatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE, unsigned ParentIdx,
                      CompileUnit &CU) {
  unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
  CU.getInfo(MyIdx).ParentIdx = ParentIdx;

  if (DIE->hasChildren())
    for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
         Child = Child->getSibling())
      GatherDIEParents(Child, MyIdx, CU);
}

void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
  Units.reserve(Dwarf.getNumCompileUnits());
  NextValidReloc = 0;
}

void DwarfLinker::endDebugObject() {
  Units.clear();
  ValidRelocs.clear();
}

/// \brief Iterate over the relocations of the given \p Section and
/// store the ones that correspond to debug map entries into the
/// ValidRelocs array.
void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
                                       const object::MachOObjectFile &Obj,
                                       const DebugMapObject &DMO) {
  StringRef Contents;
  Section.getContents(Contents);
  DataExtractor Data(Contents, Obj.isLittleEndian(), 0);

  for (const object::RelocationRef &Reloc : Section.relocations()) {
    object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
    MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
    unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
    uint64_t Offset64;
    if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
      errs() << "warning: unsupported relocation in debug_info section.\n";
      continue;
    }
    uint32_t Offset = Offset64;
    // Mach-o uses REL relocations, the addend is at the relocation offset.
    uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);

    auto Sym = Reloc.getSymbol();
    if (Sym != Obj.symbol_end()) {
      StringRef SymbolName;
      if (Sym->getName(SymbolName)) {
        errs() << "warning: error getting relocation symbol name.\n";
        continue;
      }
      if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
        ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
    } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
      // Do not store the addend. The addend was the address of the
      // symbol in the object file, the address in the binary that is
      // stored in the debug map doesn't need to be offseted.
      ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
    }
  }
}

/// \brief Dispatch the valid relocation finding logic to the
/// appropriate handler depending on the object file format.
bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
                                  const object::ObjectFile &Obj,
                                  const DebugMapObject &DMO) {
  // Dispatch to the right handler depending on the file type.
  if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
    findValidRelocsMachO(Section, *MachOObj, DMO);
  else
    errs() << "warning: unsupported object file type: " << Obj.getFileName()
           << '\n';

  if (ValidRelocs.empty())
    return false;

  // Sort the relocations by offset. We will walk the DIEs linearly in
  // the file, this allows us to just keep an index in the relocation
  // array that we advance during our walk, rather than resorting to
  // some associative container. See DwarfLinker::NextValidReloc.
  std::sort(ValidRelocs.begin(), ValidRelocs.end());
  return true;
}

/// \brief Look for relocations in the debug_info section that match
/// entries in the debug map. These relocations will drive the Dwarf
/// link by indicating which DIEs refer to symbols present in the
/// linked binary.
/// \returns wether there are any valid relocations in the debug info.
bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
                                             const DebugMapObject &DMO) {
  // Find the debug_info section.
  for (const object::SectionRef &Section : Obj.sections()) {
    StringRef SectionName;
    Section.getName(SectionName);
    SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
    if (SectionName != "debug_info")
      continue;
    return findValidRelocs(Section, Obj, DMO);
  }
  return false;
}

bool DwarfLinker::link(const DebugMap &Map) {

  if (Map.begin() == Map.end()) {
    errs() << "Empty debug map.\n";
    return false;
  }

  for (const auto &Obj : Map.objects()) {
    if (Verbose)
      outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
    auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
    if (std::error_code EC = ErrOrObj.getError()) {
      errs() << Obj->getObjectFilename() << ": " << EC.message() << "\n";
      continue;
    }

    // Look for relocations that correspond to debug map entries.
    if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
      if (Verbose)
        outs() << "No valid relocations found. Skipping.\n";
      continue;
    }

    // Setup access to the debug info.
    DWARFContextInMemory DwarfContext(*ErrOrObj);
    startDebugObject(DwarfContext);

    // In a first phase, just read in the debug info and store the DIE
    // parent links that we will use during the next phase.
    for (const auto &CU : DwarfContext.compile_units()) {
      auto *CUDie = CU->getCompileUnitDIE(false);
      if (Verbose) {
        outs() << "Input compilation unit:";
        CUDie->dump(outs(), CU.get(), 0);
      }
      Units.emplace_back(*CU);
      GatherDIEParents(CUDie, 0, Units.back());
    }

    // Clean-up before starting working on the next object.
    endDebugObject();
  }

  return true;
}
}

bool linkDwarf(StringRef OutputFilename, const DebugMap &DM, bool Verbose) {
  DwarfLinker Linker(OutputFilename, Verbose);
  return Linker.link(DM);
}
}
}
<commit_msg>[dsymutil] Add a few generic helper methods.<commit_after>//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DebugMap.h"
#include "BinaryHolder.h"
#include "DebugMap.h"
#include "dsymutil.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
#include "llvm/Object/MachO.h"
#include <string>

namespace llvm {
namespace dsymutil {

namespace {

/// \brief Stores all information relating to a compile unit, be it in
/// its original instance in the object file to its brand new cloned
/// and linked DIE tree.
class CompileUnit {
public:
  /// \brief Information gathered about a DIE in the object file.
  struct DIEInfo {
    uint32_t ParentIdx;
  };

  CompileUnit(DWARFUnit &OrigUnit) : OrigUnit(OrigUnit) {
    Info.resize(OrigUnit.getNumDIEs());
  }

  DWARFUnit &getOrigUnit() const { return OrigUnit; }

  DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
  const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }

private:
  DWARFUnit &OrigUnit;
  std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
};

/// \brief The core of the Dwarf linking logic.
///
/// The link of the dwarf information from the object files will be
/// driven by the selection of 'root DIEs', which are DIEs that
/// describe variables or functions that are present in the linked
/// binary (and thus have entries in the debug map). All the debug
/// information that will be linked (the DIEs, but also the line
/// tables, ranges, ...) is derived from that set of root DIEs.
///
/// The root DIEs are identified because they contain relocations that
/// correspond to a debug map entry at specific places (the low_pc for
/// a function, the location for a variable). These relocations are
/// called ValidRelocs in the DwarfLinker and are gathered as a very
/// first step when we start processing a DebugMapObject.
class DwarfLinker {
public:
  DwarfLinker(StringRef OutputFilename, bool Verbose)
      : OutputFilename(OutputFilename), Verbose(Verbose), BinHolder(Verbose) {}

  /// \brief Link the contents of the DebugMap.
  bool link(const DebugMap &);

private:
  /// \brief Called at the start of a debug object link.
  void startDebugObject(DWARFContext &);

  /// \brief Called at the end of a debug object link.
  void endDebugObject();

  /// \defgroup FindValidRelocations Translate debug map into a list
  /// of relevant relocations
  ///
  /// @{
  struct ValidReloc {
    uint32_t Offset;
    uint32_t Size;
    uint64_t Addend;
    const DebugMapObject::DebugMapEntry *Mapping;

    ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
               const DebugMapObject::DebugMapEntry *Mapping)
        : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}

    bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
  };

  /// \brief The valid relocations for the current DebugMapObject.
  /// This vector is sorted by relocation offset.
  std::vector<ValidReloc> ValidRelocs;

  /// \brief Index into ValidRelocs of the next relocation to
  /// consider. As we walk the DIEs in acsending file offset and as
  /// ValidRelocs is sorted by file offset, keeping this index
  /// uptodate is all we have to do to have a cheap lookup during the
  /// root DIE selection.
  unsigned NextValidReloc;

  bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
                                  const DebugMapObject &DMO);

  bool findValidRelocs(const object::SectionRef &Section,
                       const object::ObjectFile &Obj,
                       const DebugMapObject &DMO);

  void findValidRelocsMachO(const object::SectionRef &Section,
                            const object::MachOObjectFile &Obj,
                            const DebugMapObject &DMO);
  /// @}

  /// \defgroup Helpers Various helper methods.
  ///
  /// @{
  const DWARFDebugInfoEntryMinimal *
  resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
                      const DWARFDebugInfoEntryMinimal &DIE,
                      CompileUnit *&ReferencedCU);

  CompileUnit *getUnitForOffset(unsigned Offset);

  void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
                     const DWARFDebugInfoEntryMinimal *DIE = nullptr);
  /// @}

private:
  std::string OutputFilename;
  bool Verbose;
  BinaryHolder BinHolder;

  /// The units of the current debug map object.
  std::vector<CompileUnit> Units;

  /// The debug map object curently under consideration.
  DebugMapObject *CurrentDebugObject;
};

/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
/// returning our CompileUnit object instead.
CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
  auto CU =
      std::upper_bound(Units.begin(), Units.end(), Offset,
                       [](uint32_t LHS, const CompileUnit &RHS) {
                         return LHS < RHS.getOrigUnit().getNextUnitOffset();
                       });
  return CU != Units.end() ? &*CU : nullptr;
}

/// \brief Resolve the DIE attribute reference that has been
/// extracted in \p RefValue. The resulting DIE migh be in another
/// CompileUnit which is stored into \p ReferencedCU.
/// \returns null if resolving fails for any reason.
const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
    DWARFFormValue &RefValue, const DWARFUnit &Unit,
    const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
  assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
  uint64_t RefOffset = *RefValue.getAsReference(&Unit);

  if ((RefCU = getUnitForOffset(RefOffset)))
    if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
      return RefDie;

  reportWarning("could not find referenced DIE", &Unit, &DIE);
  return nullptr;
}

/// \brief Report a warning to the user, optionaly including
/// information about a specific \p DIE related to the warning.
void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
                                const DWARFDebugInfoEntryMinimal *DIE) {
  if (CurrentDebugObject)
    errs() << Twine("while processing ") +
                  CurrentDebugObject->getObjectFilename() + ":\n";
  errs() << Twine("warning: ") + Warning + "\n";

  if (!Verbose || !DIE)
    return;

  errs() << "    in DIE:\n";
  DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
            6 /* Indent */);
}

/// \brief Recursive helper to gather the child->parent relationships in the
/// original compile unit.
void GatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE, unsigned ParentIdx,
                      CompileUnit &CU) {
  unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
  CU.getInfo(MyIdx).ParentIdx = ParentIdx;

  if (DIE->hasChildren())
    for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
         Child = Child->getSibling())
      GatherDIEParents(Child, MyIdx, CU);
}

void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
  Units.reserve(Dwarf.getNumCompileUnits());
  NextValidReloc = 0;
}

void DwarfLinker::endDebugObject() {
  Units.clear();
  ValidRelocs.clear();
}

/// \brief Iterate over the relocations of the given \p Section and
/// store the ones that correspond to debug map entries into the
/// ValidRelocs array.
void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
                                       const object::MachOObjectFile &Obj,
                                       const DebugMapObject &DMO) {
  StringRef Contents;
  Section.getContents(Contents);
  DataExtractor Data(Contents, Obj.isLittleEndian(), 0);

  for (const object::RelocationRef &Reloc : Section.relocations()) {
    object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
    MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
    unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
    uint64_t Offset64;
    if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
      reportWarning(" unsupported relocation in debug_info section.");
      continue;
    }
    uint32_t Offset = Offset64;
    // Mach-o uses REL relocations, the addend is at the relocation offset.
    uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);

    auto Sym = Reloc.getSymbol();
    if (Sym != Obj.symbol_end()) {
      StringRef SymbolName;
      if (Sym->getName(SymbolName)) {
        reportWarning("error getting relocation symbol name.");
        continue;
      }
      if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
        ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
    } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
      // Do not store the addend. The addend was the address of the
      // symbol in the object file, the address in the binary that is
      // stored in the debug map doesn't need to be offseted.
      ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
    }
  }
}

/// \brief Dispatch the valid relocation finding logic to the
/// appropriate handler depending on the object file format.
bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
                                  const object::ObjectFile &Obj,
                                  const DebugMapObject &DMO) {
  // Dispatch to the right handler depending on the file type.
  if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
    findValidRelocsMachO(Section, *MachOObj, DMO);
  else
    reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());

  if (ValidRelocs.empty())
    return false;

  // Sort the relocations by offset. We will walk the DIEs linearly in
  // the file, this allows us to just keep an index in the relocation
  // array that we advance during our walk, rather than resorting to
  // some associative container. See DwarfLinker::NextValidReloc.
  std::sort(ValidRelocs.begin(), ValidRelocs.end());
  return true;
}

/// \brief Look for relocations in the debug_info section that match
/// entries in the debug map. These relocations will drive the Dwarf
/// link by indicating which DIEs refer to symbols present in the
/// linked binary.
/// \returns wether there are any valid relocations in the debug info.
bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
                                             const DebugMapObject &DMO) {
  // Find the debug_info section.
  for (const object::SectionRef &Section : Obj.sections()) {
    StringRef SectionName;
    Section.getName(SectionName);
    SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
    if (SectionName != "debug_info")
      continue;
    return findValidRelocs(Section, Obj, DMO);
  }
  return false;
}

bool DwarfLinker::link(const DebugMap &Map) {

  if (Map.begin() == Map.end()) {
    errs() << "Empty debug map.\n";
    return false;
  }

  for (const auto &Obj : Map.objects()) {
    CurrentDebugObject = Obj.get();

    if (Verbose)
      outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
    auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
    if (std::error_code EC = ErrOrObj.getError()) {
      reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
      continue;
    }

    // Look for relocations that correspond to debug map entries.
    if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
      if (Verbose)
        outs() << "No valid relocations found. Skipping.\n";
      continue;
    }

    // Setup access to the debug info.
    DWARFContextInMemory DwarfContext(*ErrOrObj);
    startDebugObject(DwarfContext);

    // In a first phase, just read in the debug info and store the DIE
    // parent links that we will use during the next phase.
    for (const auto &CU : DwarfContext.compile_units()) {
      auto *CUDie = CU->getCompileUnitDIE(false);
      if (Verbose) {
        outs() << "Input compilation unit:";
        CUDie->dump(outs(), CU.get(), 0);
      }
      Units.emplace_back(*CU);
      GatherDIEParents(CUDie, 0, Units.back());
    }

    // Clean-up before starting working on the next object.
    endDebugObject();
  }

  return true;
}
}

bool linkDwarf(StringRef OutputFilename, const DebugMap &DM, bool Verbose) {
  DwarfLinker Linker(OutputFilename, Verbose);
  return Linker.link(DM);
}
}
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// File: factory.hpp
//
// Desc: Device factory - Manage IP Camera.
//
// Copyright (c) 2014-2018 opencvr.com. All rights reserved.
//------------------------------------------------------------------------------

#ifndef __VSC_FACTORY_H_
#define __VSC_FACTORY_H_
#include "confdb.hpp"
#include "device.hpp"
#include "vdb.hpp"
#include "vhdfsdb.hpp"
#include "vplay.hpp"
#include "sysdb.hpp"
#include "hdddevice.hpp"
#include <QThread>
#include <qdebug.h>
#include "Poco/Path.h"
#include "Poco/File.h"

typedef enum
{
    FACTORY_DEVICE_ADD = 1,
    FACTORY_DEVICE_DEL,
    FACTORY_DEVICE_ONLINE,
    FACTORY_DEVICE_OFFLINE,
    FACTORY_DEVICE_RECORDING_ON,
    FACTORY_DEVICE_RECORDING_OFF,
    /* The Camera group has been change */
    FACTORY_DEVICE_GROUP_CHANGE,
    FACTORY_VMS_ADD,
    FACTORY_VMS_DEL,
    FACTORY_VIPC_ADD,
    FACTORY_VIPC_DEL,
    /* Camera view add and del */
    FACTORY_VIEW_ADD,
    FACTORY_VIEW_DEL,
    /* Camera group add and del */
    FACTORY_VGROUP_ADD,
    FACTORY_VGROUP_DEL,

    /* Camera tour add and del */
    FACTORY_TOUR_ADD,
    FACTORY_TOUR_DEL,
    FACTORY_DEVICE_LAST
} FactoryDeviceChangeType;

class FactoryDeviceChangeData
{
public:
	FactoryDeviceChangeType type;
	int id;
};

typedef BOOL (*FactoryDeviceChangeNotify)(void* pParam,
		FactoryDeviceChangeData data);

typedef std::list<LPDevice> DeviceList;
typedef std::list<DeviceParam> DeviceParamList;
typedef std::map<int, LPDevice> DeviceMap;
typedef std::map<int, DeviceParam> DeviceParamMap;
typedef std::map<int, int> DeviceOnlineMap;
typedef std::map<int, VIPCDeviceParam> VIPCDeviceParamMap;
typedef std::map<void *, FactoryDeviceChangeNotify> DeviceChangeNofityMap;
#define FACTORY_DEVICE_ID_MAX 4096

class Factory;
class FactoryHddTask:public QThread
{
	Q_OBJECT
public:
	FactoryHddTask(Factory &pFactory);
	~FactoryHddTask();
public:
	void run();
private:
	Factory &m_Factory;
};

/* Fatory is Qthread for callback in Qt GUI */
class Factory: public QThread
{
    Q_OBJECT
public:
    Factory();
    ~Factory();
public:
	/* Init function */
	BOOL Init();
	s32 InitAddDevice(DeviceParam & pParam, u32 nIndex);

public:
	BOOL RegDeviceChangeNotify(void * pData, FactoryDeviceChangeNotify callback);
	BOOL CallDeviceChange(FactoryDeviceChangeData data);

public:
	BOOL GetLicense(astring &strLicense, astring &strHostId,
							int &ch, astring &type);
	BOOL SetLicense(astring &strLicense);
	BOOL InitLicense();

	BOOL GetExportPath(astring &strPath);
	BOOL SetExportPath(astring &strPath);

public:
	BOOL GetAutoLogin();
	BOOL AuthUser(astring &strUser, astring &strPasswd);
	BOOL GetUserData(VSCUserData &pData);
	BOOL SetUserData(VSCUserData &pData);

/* Emap function */
public:
	BOOL GetEmapData(VSCEmapData &pData);
	BOOL SetEmapData(VSCEmapData &pData);
	BOOL AddEmapCamera(s32 nIndex, u32 x, u32 y, u32 w, u32 h);
	BOOL DelEmapCamera(s32 nIndex);
	BOOL GetEmapCamera(s32 nIndex, u32 &x, u32 &y, u32 &w, u32 &h);

	BOOL GetEmapFile(astring &strFile);
	BOOL SetEmapFile(astring &strFile);

public:
	BOOL GetHdfsRecordConf(VSCHdfsRecordData &pData);
	BOOL SetHdfsRecordConf(VSCHdfsRecordData &pData);
	BOOL GetLang(VSCLangType &pLang);
	BOOL SetLang(VSCLangType &pLang);

	/* OpenCVR API port */
	BOOL GetOAPIPort(u16 &pPort);
	BOOL SetOAPIPort(u16 &pPort);

	/* Defualt HW HWAccel enable or disable */
	BOOL GetDefaultHWAccel(BOOL &pHWAccel);
	BOOL SetDefaultHWAccel(BOOL &pHWAccel);

	BOOL GetRTSPServer(BOOL &pAuth, astring &pMultiAddr, u16 &pPort);
	BOOL SetRTSPServer(BOOL &pAuth, astring &pMultiAddr, u16 &pPort);

	/* Defualt Mining enable or disable */
	BOOL GetDefaultMining(BOOL &pMining);
	BOOL SetDefaultMining(BOOL &pMining);

public:
	/* UI can use this for display device tree */
	BOOL GetDeviceParamMap(DeviceParamMap &pMap);
	BOOL GetDeviceOnlineMap(DeviceOnlineMap &pMap);
       BOOL GetVIPCDeviceParamMap(VIPCDeviceParamMap &pMap);
       /* Device function */
	s32 AddDevice(DeviceParam & pParam);
	s32 GetDeviceParamById(DeviceParam & pParam, s32 nIndex);
	BOOL GetDeviceRtspUrl(astring & strUrl, s32 nIndex);
	s32 GetDeviceParamByIdTryLock(DeviceParam & pParam, s32 nIndex);
	BOOL DelDevice(s32 nIndex);
	BOOL UpdateDeviceGroup(s32 nIndex, s32 nGroup);

	/* VIPC function */
	s32 AddVIPC(VIPCDeviceParam & pParam);
	s32 GetVIPCParamById(VIPCDeviceParam & pParam, s32 nIndex);
	BOOL DelVIPC(s32 nIndex);

	/* Video play function */
	BOOL AttachPlayer(s32 nIndex, HWND hWnd, int w, int h,
						DeviceDelCallbackFunctionPtr pCallback, void * pParam);
	BOOL UpdateWidget(s32 nIndex, HWND hWnd, int w, int h);
	BOOL DetachPlayer(s32 nIndex, HWND hWnd, void * pParam);
	BOOL GetStreamInfo(s32 nIndex, VideoStreamInfo &pInfo);

	BOOL EnablePtz(s32 nIndex, HWND hWnd, bool enable);
	BOOL DrawPtzDirection(s32 nIndex, HWND hWnd, int x1, int y1, int x2,  int y2);
	BOOL ClearPtzDirection(s32 nIndex, HWND hWnd);
	BOOL PtzAction(s32 nIndex, FPtzAction action, float speed);
	BOOL ShowAlarm(s32 nIndex, HWND hWnd);
public:
	/* VMS */
	BOOL GetVms(VSCVmsData &pData);
	s32 AddVms(VSCVmsDataItem &pParam);
	BOOL DelVms(s32 Id);
	BOOL GetVmsById(VSCVmsDataItem &pParam, int nId);

	/* View */
	BOOL GetView(VSCViewData &pData);
	s32 AddView(VSCViewDataItem &pParam);
	BOOL DelView(s32 Id);
	BOOL GetViewById(VSCViewDataItem &pParam, int nId);

	/* Camera group */
	BOOL GetVGroup(VSCVGroupData &pData);
	s32 AddVGroup(VSCVGroupDataItem &pParam);
	BOOL DelVGroup(s32 Id);
	BOOL GetVGroupById(VSCVGroupDataItem &pParam, int nId);

	/* Tour */
	BOOL GetTour(VSCTourData &pData);
	s32 AddTour(VSCTourDataItem &pParam);
	BOOL DelTour(s32 Id);
	BOOL GetTourById(VSCTourDataItem &pParam, int nId);

public:
	BOOL StartRecord(s32 nIndex);
	BOOL StopRecord(s32 nIndex);
	BOOL StartHdfsRecord(s32 nIndex);
	BOOL StopHdfsRecord(s32 nIndex);
	BOOL StartRecordAll();
	BOOL StopRecordAll();
	BOOL StartHdfsRecordAll();
	BOOL StopHdfsRecordAll();
public:
	BOOL GetRecordStatus(s32 nIndex, BOOL &bStatus);

public:
	/* Data */
	BOOL RegDataCallback(s32 nIndex, DeviceDataCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegDataCallback(s32 nIndex, void * pParam);
	BOOL GetInfoFrame(s32 nIndex, InfoFrame &pFrame);
	BOOL RegSubDataCallback(s32 nIndex, DeviceDataCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegSubDataCallback(s32 nIndex, void * pParam);
	BOOL GetSubInfoFrame(s32 nIndex, InfoFrame &pFrame);

	/* Raw data */
	BOOL RegRawCallback(s32 nIndex, DeviceRawCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegRawCallback(s32 nIndex, void * pParam);
	BOOL RegSubRawCallback(s32 nIndex, DeviceRawCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegSubRawCallback(s32 nIndex, void * pParam);

	/* Seq data  */
	BOOL RegSeqCallback(s32 nIndex, DeviceSeqCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegSeqCallback(s32 nIndex, void * pParam);

	BOOL RegDelCallback(s32 nIndex, DeviceDelCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegDelCallback(s32 nIndex, void * pParam);

	BOOL GetDeviceOnline(s32 nIndex, BOOL &bStatus);
	BOOL GetUrl(s32 nIndex, std::string &url);
	BOOL SetSystemPath(astring &strPath);

	/* Disk function */
	BOOL AddHdd(astring &strHdd, astring & strPath, s64 nSize);
	BOOL DelHdd(astring & strHdd);
	BOOL HddUpdateSize(astring &strHdd, s64 nSize);
	BOOL GetDiskMap(VDBDiskMap &pMap);
	BOOL GetDiskStatus(VDBDiskStatus &pStatus);
	BOOL UpdateDiskStatusMap(VDBDiskStatus &pStatus);

	/* Search function */
	BOOL SearchItems(s32 deviceId, u32 startTime, u32 endTime, u32 recordType,
					RecordItemMap &map);
	BOOL SearchHasItems(s32 deviceId, u32 startTime, u32 endTime,
					u32 recordType);
	BOOL SearchAItem(s32 deviceId, u32 Time, VdbRecordItem &pItem);
	BOOL SearchAItemNear(s32 deviceId, u32 Time, VdbRecordItem &pItem);
	BOOL SearchNextItem(s32 deviceId, s64 LastId, VdbRecordItem &pItem);
	BOOL RequestAMFRead(VdbRecordItem &pItem, astring & strPath);
	BOOL FinishedAMFRead(VdbRecordItem &pItem, astring & strPath);

	VDB & GetVdb();
public:
	void Lock(){m_Lock.lock();}
	bool TryLock(){return m_Lock.try_lock();}
	void UnLock(){m_Lock.unlock();}

public:
	/* Device */
	s32 GetDeviceID(void);
	BOOL ReleaseDeviceID(s32 nID);
	BOOL LockDeviceID(s32 nID);

	/* VIPC */
	s32 GetVIPCID(void);
	BOOL ReleaseVIPCID(s32 nID);
	BOOL LockVIPCID(s32 nID);
public:
	static void Run(void * pParam);
	void run();

private:
	DeviceMap m_DeviceMap;
	DeviceParamMap m_DeviceParamMap;
	DeviceOnlineMap m_DeviceOnlineMap;

	/* Virtual IP camera param */
	VIPCDeviceParamMap m_VIPCDeviceParamMap;
	fast_mutex m_Lock;
	tthread::thread *m_pThread;

private:
	DeviceChangeNofityMap m_DeviceChange;

private:
	VDB *m_pVdb;
	VHdfsDB *m_pVHdfsdb;
	FactoryHddTask *m_HddTask;

private:
	s8 m_strDeviceMap[FACTORY_DEVICE_ID_MAX];
	s8 m_strVIPCMap[FACTORY_DEVICE_ID_MAX];
	ConfDB m_Conf;
	SysDB m_SysPath;
private:
	//CmnHttpServer *m_pHttpServer;
};

typedef Factory* LPFactory;

#include "factoryimpl.hpp"

#endif // __VSC_FACTORY_H_
<commit_msg>add hls<commit_after>//------------------------------------------------------------------------------
// File: factory.hpp
//
// Desc: Device factory - Manage IP Camera.
//
// Copyright (c) 2014-2018 opencvr.com. All rights reserved.
//------------------------------------------------------------------------------

#ifndef __VSC_FACTORY_H_
#define __VSC_FACTORY_H_
#include "confdb.hpp"
#include "device.hpp"
#include "vdb.hpp"
#include "vhdfsdb.hpp"
#include "vplay.hpp"
#include "sysdb.hpp"
#include "hdddevice.hpp"
#include <QThread>
#include <qdebug.h>
#include "Poco/Path.h"
#include "Poco/File.h"

typedef enum
{
    FACTORY_DEVICE_ADD = 1,
    FACTORY_DEVICE_DEL,
    FACTORY_DEVICE_ONLINE,
    FACTORY_DEVICE_OFFLINE,
    FACTORY_DEVICE_RECORDING_ON,
    FACTORY_DEVICE_RECORDING_OFF,
    /* The Camera group has been change */
    FACTORY_DEVICE_GROUP_CHANGE,
    FACTORY_VMS_ADD,
    FACTORY_VMS_DEL,
    FACTORY_VIPC_ADD,
    FACTORY_VIPC_DEL,
    /* Camera view add and del */
    FACTORY_VIEW_ADD,
    FACTORY_VIEW_DEL,
    /* Camera group add and del */
    FACTORY_VGROUP_ADD,
    FACTORY_VGROUP_DEL,

    /* Camera tour add and del */
    FACTORY_TOUR_ADD,
    FACTORY_TOUR_DEL,
    FACTORY_DEVICE_LAST
} FactoryDeviceChangeType;

class FactoryDeviceChangeData
{
public:
	FactoryDeviceChangeType type;
	int id;
};

typedef BOOL (*FactoryDeviceChangeNotify)(void* pParam,
		FactoryDeviceChangeData data);

typedef std::list<LPDevice> DeviceList;
typedef std::list<DeviceParam> DeviceParamList;
typedef std::map<int, LPDevice> DeviceMap;
typedef std::map<int, DeviceParam> DeviceParamMap;
typedef std::map<int, int> DeviceOnlineMap;
typedef std::map<int, VIPCDeviceParam> VIPCDeviceParamMap;
typedef std::map<void *, FactoryDeviceChangeNotify> DeviceChangeNofityMap;
#define FACTORY_DEVICE_ID_MAX 4096

class Factory;
class FactoryHddTask:public QThread
{
	Q_OBJECT
public:
	FactoryHddTask(Factory &pFactory);
	~FactoryHddTask();
public:
	void run();
private:
	Factory &m_Factory;
};

/* Fatory is Qthread for callback in Qt GUI */
class Factory: public QThread
{
    Q_OBJECT
public:
    Factory();
    ~Factory();
public:
	/* Init function */
	BOOL Init();
	s32 InitAddDevice(DeviceParam & pParam, u32 nIndex);

public:
	BOOL RegDeviceChangeNotify(void * pData, FactoryDeviceChangeNotify callback);
	BOOL CallDeviceChange(FactoryDeviceChangeData data);

public:
	BOOL GetLicense(astring &strLicense, astring &strHostId,
							int &ch, astring &type);
	BOOL SetLicense(astring &strLicense);
	BOOL InitLicense();

	BOOL GetExportPath(astring &strPath);
	BOOL SetExportPath(astring &strPath);

public:
	BOOL GetAutoLogin();
	BOOL AuthUser(astring &strUser, astring &strPasswd);
	BOOL GetUserData(VSCUserData &pData);
	BOOL SetUserData(VSCUserData &pData);

/* Emap function */
public:
	BOOL GetEmapData(VSCEmapData &pData);
	BOOL SetEmapData(VSCEmapData &pData);
	BOOL AddEmapCamera(s32 nIndex, u32 x, u32 y, u32 w, u32 h);
	BOOL DelEmapCamera(s32 nIndex);
	BOOL GetEmapCamera(s32 nIndex, u32 &x, u32 &y, u32 &w, u32 &h);

	BOOL GetEmapFile(astring &strFile);
	BOOL SetEmapFile(astring &strFile);

public:
	BOOL GetHdfsRecordConf(VSCHdfsRecordData &pData);
	BOOL SetHdfsRecordConf(VSCHdfsRecordData &pData);
	BOOL GetLang(VSCLangType &pLang);
	BOOL SetLang(VSCLangType &pLang);

	/* OpenCVR API port */
	BOOL GetOAPIPort(u16 &pPort);
	BOOL SetOAPIPort(u16 &pPort);

	/* OpenCVR HTTP Server  port */
	BOOL GetVHTTPSPort(u16 &pPort);
	BOOL SetVHTTPSPort(u16 &pPort);

	/* OpenCVR HLS Server  port */
	BOOL GetVHLSSPort(u16 &pPort);
	BOOL SetVHLSSPort(u16 &pPort);

	/* Defualt HW HWAccel enable or disable */
	BOOL GetDefaultHWAccel(BOOL &pHWAccel);
	BOOL SetDefaultHWAccel(BOOL &pHWAccel);

	BOOL GetRTSPServer(BOOL &pAuth, astring &pMultiAddr, u16 &pPort);
	BOOL SetRTSPServer(BOOL &pAuth, astring &pMultiAddr, u16 &pPort);

	/* Defualt Mining enable or disable */
	BOOL GetDefaultMining(BOOL &pMining);
	BOOL SetDefaultMining(BOOL &pMining);

public:
	/* UI can use this for display device tree */
	BOOL GetDeviceParamMap(DeviceParamMap &pMap);
	BOOL GetDeviceOnlineMap(DeviceOnlineMap &pMap);
       BOOL GetVIPCDeviceParamMap(VIPCDeviceParamMap &pMap);
       /* Device function */
	s32 AddDevice(DeviceParam & pParam);
	s32 GetDeviceParamById(DeviceParam & pParam, s32 nIndex);
	BOOL GetDeviceRtspUrl(astring & strUrl, s32 nIndex);
	s32 GetDeviceParamByIdTryLock(DeviceParam & pParam, s32 nIndex);
	BOOL DelDevice(s32 nIndex);
	BOOL UpdateDeviceGroup(s32 nIndex, s32 nGroup);

	/* VIPC function */
	s32 AddVIPC(VIPCDeviceParam & pParam);
	s32 GetVIPCParamById(VIPCDeviceParam & pParam, s32 nIndex);
	BOOL DelVIPC(s32 nIndex);

	/* Video play function */
	BOOL AttachPlayer(s32 nIndex, HWND hWnd, int w, int h,
						DeviceDelCallbackFunctionPtr pCallback, void * pParam);
	BOOL UpdateWidget(s32 nIndex, HWND hWnd, int w, int h);
	BOOL DetachPlayer(s32 nIndex, HWND hWnd, void * pParam);
	BOOL GetStreamInfo(s32 nIndex, VideoStreamInfo &pInfo);

	BOOL EnablePtz(s32 nIndex, HWND hWnd, bool enable);
	BOOL DrawPtzDirection(s32 nIndex, HWND hWnd, int x1, int y1, int x2,  int y2);
	BOOL ClearPtzDirection(s32 nIndex, HWND hWnd);
	BOOL PtzAction(s32 nIndex, FPtzAction action, float speed);
	BOOL ShowAlarm(s32 nIndex, HWND hWnd);
public:
	/* VMS */
	BOOL GetVms(VSCVmsData &pData);
	s32 AddVms(VSCVmsDataItem &pParam);
	BOOL DelVms(s32 Id);
	BOOL GetVmsById(VSCVmsDataItem &pParam, int nId);

	/* View */
	BOOL GetView(VSCViewData &pData);
	s32 AddView(VSCViewDataItem &pParam);
	BOOL DelView(s32 Id);
	BOOL GetViewById(VSCViewDataItem &pParam, int nId);

	/* Camera group */
	BOOL GetVGroup(VSCVGroupData &pData);
	s32 AddVGroup(VSCVGroupDataItem &pParam);
	BOOL DelVGroup(s32 Id);
	BOOL GetVGroupById(VSCVGroupDataItem &pParam, int nId);

	/* Tour */
	BOOL GetTour(VSCTourData &pData);
	s32 AddTour(VSCTourDataItem &pParam);
	BOOL DelTour(s32 Id);
	BOOL GetTourById(VSCTourDataItem &pParam, int nId);

public:
	BOOL StartRecord(s32 nIndex);
	BOOL StopRecord(s32 nIndex);
	BOOL StartHdfsRecord(s32 nIndex);
	BOOL StopHdfsRecord(s32 nIndex);
	BOOL StartRecordAll();
	BOOL StopRecordAll();
	BOOL StartHdfsRecordAll();
	BOOL StopHdfsRecordAll();
public:
	BOOL GetRecordStatus(s32 nIndex, BOOL &bStatus);

public:
	/* Data */
	BOOL RegDataCallback(s32 nIndex, DeviceDataCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegDataCallback(s32 nIndex, void * pParam);
	BOOL GetInfoFrame(s32 nIndex, InfoFrame &pFrame);
	BOOL RegSubDataCallback(s32 nIndex, DeviceDataCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegSubDataCallback(s32 nIndex, void * pParam);
	BOOL GetSubInfoFrame(s32 nIndex, InfoFrame &pFrame);

	/* Raw data */
	BOOL RegRawCallback(s32 nIndex, DeviceRawCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegRawCallback(s32 nIndex, void * pParam);
	BOOL RegSubRawCallback(s32 nIndex, DeviceRawCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegSubRawCallback(s32 nIndex, void * pParam);

	/* Seq data  */
	BOOL RegSeqCallback(s32 nIndex, DeviceSeqCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegSeqCallback(s32 nIndex, void * pParam);

	BOOL RegDelCallback(s32 nIndex, DeviceDelCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegDelCallback(s32 nIndex, void * pParam);

	BOOL GetDeviceOnline(s32 nIndex, BOOL &bStatus);
	BOOL GetUrl(s32 nIndex, std::string &url);
	BOOL SetSystemPath(astring &strPath);

	/* Disk function */
	BOOL AddHdd(astring &strHdd, astring & strPath, s64 nSize);
	BOOL DelHdd(astring & strHdd);
	BOOL HddUpdateSize(astring &strHdd, s64 nSize);
	BOOL GetDiskMap(VDBDiskMap &pMap);
	BOOL GetDiskStatus(VDBDiskStatus &pStatus);
	BOOL UpdateDiskStatusMap(VDBDiskStatus &pStatus);

	/* Search function */
	BOOL SearchItems(s32 deviceId, u32 startTime, u32 endTime, u32 recordType,
					RecordItemMap &map);
	BOOL SearchHasItems(s32 deviceId, u32 startTime, u32 endTime,
					u32 recordType);
	BOOL SearchAItem(s32 deviceId, u32 Time, VdbRecordItem &pItem);
	BOOL SearchAItemNear(s32 deviceId, u32 Time, VdbRecordItem &pItem);
	BOOL SearchNextItem(s32 deviceId, s64 LastId, VdbRecordItem &pItem);
	BOOL RequestAMFRead(VdbRecordItem &pItem, astring & strPath);
	BOOL FinishedAMFRead(VdbRecordItem &pItem, astring & strPath);

	VDB & GetVdb();
public:
	void Lock(){m_Lock.lock();}
	bool TryLock(){return m_Lock.try_lock();}
	void UnLock(){m_Lock.unlock();}

public:
	/* Device */
	s32 GetDeviceID(void);
	BOOL ReleaseDeviceID(s32 nID);
	BOOL LockDeviceID(s32 nID);

	/* VIPC */
	s32 GetVIPCID(void);
	BOOL ReleaseVIPCID(s32 nID);
	BOOL LockVIPCID(s32 nID);
public:
	static void Run(void * pParam);
	void run();

private:
	DeviceMap m_DeviceMap;
	DeviceParamMap m_DeviceParamMap;
	DeviceOnlineMap m_DeviceOnlineMap;

	/* Virtual IP camera param */
	VIPCDeviceParamMap m_VIPCDeviceParamMap;
	fast_mutex m_Lock;
	tthread::thread *m_pThread;

private:
	DeviceChangeNofityMap m_DeviceChange;

private:
	VDB *m_pVdb;
	VHdfsDB *m_pVHdfsdb;
	FactoryHddTask *m_HddTask;

private:
	s8 m_strDeviceMap[FACTORY_DEVICE_ID_MAX];
	s8 m_strVIPCMap[FACTORY_DEVICE_ID_MAX];
	ConfDB m_Conf;
	SysDB m_SysPath;
private:
	//CmnHttpServer *m_pHttpServer;
};

typedef Factory* LPFactory;

#include "factoryimpl.hpp"

#endif // __VSC_FACTORY_H_
<|endoftext|>