<commit_before>  /*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include <fstream>
#include <Core/Algorithms/Math/ParallelAlgebra/ParallelLinearAlgebra.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/DenseColumnMatrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Datatypes/MatrixComparison.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Core/Datatypes/MatrixIO.h>
#include <Testing/Utils/MatrixTestUtilities.h>
#include <boost/thread/thread.hpp>

using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms::Math;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::TestUtils;
using namespace SCIRun;
using namespace ::testing;

namespace
{
  const int size = 1000;
  SparseRowMatrixHandle matrix1()
  {
    SparseRowMatrixHandle m(new SparseRowMatrix(size,size));
    m->insert(0,0) = 1;
    m->insert(1,2) = -1;
    m->insert(size-1,size-1) = 2;
    return m;
  }

  SparseRowMatrix matrix2()
  {
    SparseRowMatrix m(size,size);
    m.insert(0,1) = -2;
    m.insert(1,1) = 0.5;
    m.insert(size-1,size-1) = 4;
    return m;
  }

  SparseRowMatrix matrix3()
  {
    SparseRowMatrix m(size,size);
    m.insert(0,0) = -1;
    m.insert(1,2) = 1;
    m.insert(size-1,size-1) = -2;
    return m;
  }

  DenseColumnMatrixHandle vector1()
  {
    DenseColumnMatrixHandle v(new DenseColumnMatrix(size));
    v->setZero();
    *v << 1, 2, 4;
    (*v)[size-1] = -1;
    return v;
  }

  DenseColumnMatrixHandle vector2()
  {
    DenseColumnMatrixHandle v(new DenseColumnMatrix(size));
    v->setZero();
    *v << -1, -2, -4;
    (*v)[size-1] = 1;
    return v;
  }

  DenseColumnMatrixHandle vector3()
  {
    DenseColumnMatrixHandle v(new DenseColumnMatrix(size));
    v->setZero();
    *v << 0, 1, 0;
    (*v)[size-1] = -7;
    return v;
  }

  unsigned int numProcs()
  {
    return boost::thread::hardware_concurrency();
  }

  SolverInputs getDummySystem()
  {
    SolverInputs system;
    system.A = matrix1();
    system.b = vector1();
    system.x = vector2();
    system.x0 = vector3();
    return system;
  }
}

TEST(ParallelLinearAlgebraTests, CanCreateEmptyParallelVector)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);
  ParallelLinearAlgebra pla(data, 0);

  ParallelLinearAlgebra::ParallelVector v;
  EXPECT_TRUE(pla.new_vector(v));

  EXPECT_EQ(size, v.size_);
}

TEST(ParallelLinearAlgebraTests, CanCreateParallelVectorFromVectorAsShallowReference)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);
  ParallelLinearAlgebra pla(data, 0);

  ParallelLinearAlgebra::ParallelVector v;
  auto v1 = vector1();
  EXPECT_TRUE(pla.add_vector(v1, v));

  EXPECT_EQ(v1->nrows(), v.size_);
  for (size_t i = 0; i < size; ++i)
    EXPECT_EQ((*v1)[i], v.data_[i]);

  EXPECT_EQ(0, (*v1)[100]);
  v.data_[100]++;
  EXPECT_EQ(1, (*v1)[100]);
}

TEST(ParallelLinearAlgebraTests, CanCopyParallelSparseMatrixAsShallowReference)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);
  ParallelLinearAlgebra pla(data, 0);

  ParallelLinearAlgebra::ParallelMatrix m;
  auto m1 = matrix1();
  EXPECT_TRUE(pla.add_matrix(m1, m));

  EXPECT_EQ(m1->nrows(), m.m_);
  EXPECT_EQ(m1->ncols(), m.n_);
  EXPECT_EQ(m1->nonZeros(), m.nnz_);
  EXPECT_EQ(m1->coeff(1,2), m.data_[1]);

  EXPECT_EQ(1, m1->coeff(0,0));
  m.data_[0]++;
  EXPECT_EQ(2, m1->coeff(0,0));
}

TEST(ParallelLinearAlgebraTests, CanCopyContentsOfVector)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);
  ParallelLinearAlgebra pla(data, 0);

  ParallelLinearAlgebra::ParallelVector v1;
  pla.new_vector(v1);

  ParallelLinearAlgebra::ParallelVector v2;
  auto vec2 = vector2();
  pla.add_vector(vec2, v2);

  pla.copy(v2, v1);

  EXPECT_EQ(v1.size_, v2.size_);
  for (size_t i = 0; i < size; ++i)
  {
    EXPECT_EQ(v2.data_[i], v1.data_[i]);
  }
  v1.data_[7]++;
  EXPECT_NE(v1.data_[7], v2.data_[7]);
}

struct Copy
{
  Copy(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelVector& v1, ParallelLinearAlgebra::ParallelVector& v2, int proc, DenseColumnMatrixHandle vec2copy) :
    data_(data), v1_(v1), v2_(v2), proc_(proc), vec2copy_(vec2copy) {}

  ParallelLinearAlgebraSharedData& data_;
  int proc_;
  ParallelLinearAlgebra::ParallelVector& v1_;
  ParallelLinearAlgebra::ParallelVector& v2_;
  DenseColumnMatrixHandle vec2copy_;

  void operator()()
  {
    std::cout << proc_ << " starting" << std::endl;
    ParallelLinearAlgebra pla(data_, proc_);

    pla.new_vector(v1_);
    std::cout << "pla" << proc_ << " new vector" << std::endl;

    pla.add_vector(vec2copy_, v2_);
    std::cout << "pla" << proc_ << " add vector" << std::endl;

    pla.copy(v2_, v1_);
    std::cout << "pla" << proc_ << "  copy" << std::endl;
  }
};

TEST(ParallelLinearAlgebraTests, CanCopyContentsOfVectorMulti)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 2);

  ParallelLinearAlgebra::ParallelVector v1, v2;

  auto vec2copy = vector2();
  Copy c0(data, v1, v2, 0, vec2copy);
  Copy c1(data, v1, v2, 1, vec2copy);

  boost::thread t1 = boost::thread(boost::ref(c0));
  boost::thread t2 = boost::thread(boost::ref(c1));
  t1.join();
  t2.join();

  EXPECT_EQ(v1.size_, v2.size_);
  for (size_t i = 0; i < size; ++i)
  {
    EXPECT_EQ(v2.data_[i], v1.data_[i]);
  }
  v1.data_[7]++;
  EXPECT_NE(v1.data_[7], v2.data_[7]);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanTakeAbsoluteValueOfDiagonal)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanTakeAbsoluteValueOfDiagonalMulti)
{
  EXPECT_TRUE(false);
}

TEST(ParallelArithmeticTests, CanComputeMaxOfVector)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);
  ParallelLinearAlgebra pla(data, 0);

  ParallelLinearAlgebra::ParallelVector v1;
  auto vec1 = vector1();
  pla.add_vector(vec1, v1);
  double max1 = pla.max(v1);
  ParallelLinearAlgebra::ParallelVector v2;
  auto vec2 = vector2();
  pla.add_vector(vec2, v2);
  double max2 = pla.max(v2);

  EXPECT_EQ(4, max1);
  EXPECT_EQ(1, max2);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanComputeMaxOfVectorMulti)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 4);
  ParallelLinearAlgebra pla(data, 1);

  //pla.max()

  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanInvertElementsOfVectorWithAbsoluteValueThreshold)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanInvertElementsOfVectorWithAbsoluteValueThresholdMulti)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelLinearAlgebraTests, CanFillVectorWithOnes)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanMultiplyMatrixByVector)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanMultiplyMatrixByVectorMulti)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanSubtractVectors)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanCompute2Norm)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanMultiplyVectorsComponentWise)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanComputeDotProduct)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanSubtractVectorsMulti)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanCompute2NormMulti)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanMultiplyVectorsComponentWiseMulti)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanComputeDotProductMulti)
{
  EXPECT_TRUE(false);
}
<commit_msg>Macro out TODO unit tests for @ajwaller.<commit_after>  /*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include <fstream>
#include <Core/Algorithms/Math/ParallelAlgebra/ParallelLinearAlgebra.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/DenseColumnMatrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Datatypes/MatrixComparison.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Core/Datatypes/MatrixIO.h>
#include <Testing/Utils/MatrixTestUtilities.h>
#include <boost/thread/thread.hpp>

using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms::Math;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::TestUtils;
using namespace SCIRun;
using namespace ::testing;

namespace
{
  const int size = 1000;
  SparseRowMatrixHandle matrix1()
  {
    SparseRowMatrixHandle m(new SparseRowMatrix(size,size));
    m->insert(0,0) = 1;
    m->insert(1,2) = -1;
    m->insert(size-1,size-1) = 2;
    return m;
  }

  SparseRowMatrix matrix2()
  {
    SparseRowMatrix m(size,size);
    m.insert(0,1) = -2;
    m.insert(1,1) = 0.5;
    m.insert(size-1,size-1) = 4;
    return m;
  }

  SparseRowMatrix matrix3()
  {
    SparseRowMatrix m(size,size);
    m.insert(0,0) = -1;
    m.insert(1,2) = 1;
    m.insert(size-1,size-1) = -2;
    return m;
  }

  DenseColumnMatrixHandle vector1()
  {
    DenseColumnMatrixHandle v(new DenseColumnMatrix(size));
    v->setZero();
    *v << 1, 2, 4;
    (*v)[size-1] = -1;
    return v;
  }

  DenseColumnMatrixHandle vector2()
  {
    DenseColumnMatrixHandle v(new DenseColumnMatrix(size));
    v->setZero();
    *v << -1, -2, -4;
    (*v)[size-1] = 1;
    return v;
  }

  DenseColumnMatrixHandle vector3()
  {
    DenseColumnMatrixHandle v(new DenseColumnMatrix(size));
    v->setZero();
    *v << 0, 1, 0;
    (*v)[size-1] = -7;
    return v;
  }

  unsigned int numProcs()
  {
    return boost::thread::hardware_concurrency();
  }

  SolverInputs getDummySystem()
  {
    SolverInputs system;
    system.A = matrix1();
    system.b = vector1();
    system.x = vector2();
    system.x0 = vector3();
    return system;
  }
}

TEST(ParallelLinearAlgebraTests, CanCreateEmptyParallelVector)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);
  ParallelLinearAlgebra pla(data, 0);

  ParallelLinearAlgebra::ParallelVector v;
  EXPECT_TRUE(pla.new_vector(v));

  EXPECT_EQ(size, v.size_);
}

TEST(ParallelLinearAlgebraTests, CanCreateParallelVectorFromVectorAsShallowReference)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);
  ParallelLinearAlgebra pla(data, 0);

  ParallelLinearAlgebra::ParallelVector v;
  auto v1 = vector1();
  EXPECT_TRUE(pla.add_vector(v1, v));

  EXPECT_EQ(v1->nrows(), v.size_);
  for (size_t i = 0; i < size; ++i)
    EXPECT_EQ((*v1)[i], v.data_[i]);

  EXPECT_EQ(0, (*v1)[100]);
  v.data_[100]++;
  EXPECT_EQ(1, (*v1)[100]);
}

TEST(ParallelLinearAlgebraTests, CanCopyParallelSparseMatrixAsShallowReference)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);
  ParallelLinearAlgebra pla(data, 0);

  ParallelLinearAlgebra::ParallelMatrix m;
  auto m1 = matrix1();
  EXPECT_TRUE(pla.add_matrix(m1, m));

  EXPECT_EQ(m1->nrows(), m.m_);
  EXPECT_EQ(m1->ncols(), m.n_);
  EXPECT_EQ(m1->nonZeros(), m.nnz_);
  EXPECT_EQ(m1->coeff(1,2), m.data_[1]);

  EXPECT_EQ(1, m1->coeff(0,0));
  m.data_[0]++;
  EXPECT_EQ(2, m1->coeff(0,0));
}

TEST(ParallelLinearAlgebraTests, CanCopyContentsOfVector)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);
  ParallelLinearAlgebra pla(data, 0);

  ParallelLinearAlgebra::ParallelVector v1;
  pla.new_vector(v1);

  ParallelLinearAlgebra::ParallelVector v2;
  auto vec2 = vector2();
  pla.add_vector(vec2, v2);

  pla.copy(v2, v1);

  EXPECT_EQ(v1.size_, v2.size_);
  for (size_t i = 0; i < size; ++i)
  {
    EXPECT_EQ(v2.data_[i], v1.data_[i]);
  }
  v1.data_[7]++;
  EXPECT_NE(v1.data_[7], v2.data_[7]);
}

struct Copy
{
  Copy(ParallelLinearAlgebraSharedData& data, ParallelLinearAlgebra::ParallelVector& v1, ParallelLinearAlgebra::ParallelVector& v2, int proc, DenseColumnMatrixHandle vec2copy) :
    data_(data), v1_(v1), v2_(v2), proc_(proc), vec2copy_(vec2copy) {}

  ParallelLinearAlgebraSharedData& data_;
  int proc_;
  ParallelLinearAlgebra::ParallelVector& v1_;
  ParallelLinearAlgebra::ParallelVector& v2_;
  DenseColumnMatrixHandle vec2copy_;

  void operator()()
  {
    std::cout << proc_ << " starting" << std::endl;
    ParallelLinearAlgebra pla(data_, proc_);

    pla.new_vector(v1_);
    std::cout << "pla" << proc_ << " new vector" << std::endl;

    pla.add_vector(vec2copy_, v2_);
    std::cout << "pla" << proc_ << " add vector" << std::endl;

    pla.copy(v2_, v1_);
    std::cout << "pla" << proc_ << "  copy" << std::endl;
  }
};

TEST(ParallelLinearAlgebraTests, CanCopyContentsOfVectorMulti)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 2);

  ParallelLinearAlgebra::ParallelVector v1, v2;

  auto vec2copy = vector2();
  Copy c0(data, v1, v2, 0, vec2copy);
  Copy c1(data, v1, v2, 1, vec2copy);

  boost::thread t1 = boost::thread(boost::ref(c0));
  boost::thread t2 = boost::thread(boost::ref(c1));
  t1.join();
  t2.join();

  EXPECT_EQ(v1.size_, v2.size_);
  for (size_t i = 0; i < size; ++i)
  {
    EXPECT_EQ(v2.data_[i], v1.data_[i]);
  }
  v1.data_[7]++;
  EXPECT_NE(v1.data_[7], v2.data_[7]);
}

TEST(ParallelArithmeticTests, CanComputeMaxOfVector)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 1);
  ParallelLinearAlgebra pla(data, 0);

  ParallelLinearAlgebra::ParallelVector v1;
  auto vec1 = vector1();
  pla.add_vector(vec1, v1);
  double max1 = pla.max(v1);
  ParallelLinearAlgebra::ParallelVector v2;
  auto vec2 = vector2();
  pla.add_vector(vec2, v2);
  double max2 = pla.max(v2);

  EXPECT_EQ(4, max1);
  EXPECT_EQ(1, max2);
}

//TODO FIX_UNIT_TESTS
#if 0
//TODO: by intern
TEST(ParallelArithmeticTests, CanTakeAbsoluteValueOfDiagonal)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanTakeAbsoluteValueOfDiagonalMulti)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanComputeMaxOfVectorMulti)
{
  ParallelLinearAlgebraSharedData data(getDummySystem(), 4);
  ParallelLinearAlgebra pla(data, 1);

  //pla.max()

  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanInvertElementsOfVectorWithAbsoluteValueThreshold)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanInvertElementsOfVectorWithAbsoluteValueThresholdMulti)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelLinearAlgebraTests, CanFillVectorWithOnes)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanMultiplyMatrixByVector)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanMultiplyMatrixByVectorMulti)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanSubtractVectors)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanCompute2Norm)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanMultiplyVectorsComponentWise)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanComputeDotProduct)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanSubtractVectorsMulti)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanCompute2NormMulti)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanMultiplyVectorsComponentWiseMulti)
{
  EXPECT_TRUE(false);
}

//TODO: by intern
TEST(ParallelArithmeticTests, CanComputeDotProductMulti)
{
  EXPECT_TRUE(false);
}
#endif
<|endoftext|>


<commit_before>#include "dobby_internal.h"
#include "core/arch/Cpu.h"
#include "PlatformUnifiedInterface/ExecMemory/ClearCacheTool.h"
#include "UnifiedInterface/platform.h"

#include <unistd.h>

#ifdef __APPLE__
#include <mach-o/dyld.h>
#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>
#include "UserMode/UnifiedInterface/platform-darwin/mach_vm.h"
#endif

#if defined(__APPLE__)
#include <dlfcn.h>
#include <mach/vm_statistics.h>
#endif

#include "logging/check_logging.h"

#include "platform_macro.h"
#if defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64)
#include <mach/mach.h>
#include "bootstrap.h"
#include "ExecMemory/substrated/mach_interface_support/substrated_client.h"

#define KERN_ERROR_RETURN(err, failure)                                                                                \
  do {                                                                                \
    if (err != KERN_SUCCESS) {                                                                                \
      return failure;                                                                                \
    }                                                                                \
  } while (0);

static mach_port_t substrated_server_port = MACH_PORT_NULL;

mach_port_t connect_mach_service(const char *name) {
  mach_port_t port = MACH_PORT_NULL;
  kern_return_t kr;

  kr = task_get_special_port(mach_task_self(), TASK_BOOTSTRAP_PORT, &bootstrap_port);
  KERN_ERROR_RETURN(kr, MACH_PORT_NULL)

  kr = bootstrap_look_up(bootstrap_port, (char *)name, &port);
  KERN_ERROR_RETURN(kr, MACH_PORT_NULL);

  substrated_server_port = port;

  return port;
}

int code_remap_with_substrated(uint8_t *buffer, uint32_t buffer_size, addr_t address) {
  if (!MACH_PORT_VALID(substrated_server_port)) {
    substrated_server_port = connect_mach_service("cy:com.saurik.substrated");
  }
  if (!MACH_PORT_VALID(substrated_server_port))
    return -1;

  kern_return_t kr;
  kr = substrated_mark(substrated_server_port, mach_task_self(), (mach_vm_address_t)buffer, buffer_size,
                       (mach_vm_address_t *)&address);
  if (kr != KERN_SUCCESS) {
    return RT_FAILED;
  }
  return RT_SUCCESS;
}
#endif

PUBLIC MemoryOperationError CodePatch(void *address, uint8_t *buffer, uint32_t buffer_size) {
  kern_return_t kr;

  int page_size = (int)sysconf(_SC_PAGESIZE);
  addr_t page_aligned_address = ALIGN_FLOOR(address, page_size);
  int offset = (int)((addr_t)address - page_aligned_address);

  static mach_port_t self_port = mach_task_self();
#ifdef __APPLE__

#if 0 // REMOVE
  vm_prot_t prot;
  vm_inherit_t inherit;
  mach_port_t task_self = mach_task_self();
  vm_address_t region   = (vm_address_t)page_aligned_address;
  vm_size_t region_size = 0;
  struct vm_region_submap_short_info_64 info;
  mach_msg_type_number_t info_count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64;
  natural_t max_depth               = -1;
  kr = vm_region_recurse_64(task_self, &region, &region_size, &max_depth, (vm_region_recurse_info_t)&info, &info_count);
  if (kr != KERN_SUCCESS) {
    return kMemoryOperationError;
  }
  prot    = info.protection;
  inherit = info.inheritance;
#endif

  // try modify with substrated (steal from frida-gum)
  addr_t remap_dummy_page =
      (addr_t)mmap(0, page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, VM_MAKE_TAG(255), 0);
  if ((void *)remap_dummy_page == MAP_FAILED)
    return kMemoryOperationError;

  // copy original page
  memcpy((void *)remap_dummy_page, (void *)page_aligned_address, page_size);

  // patch buffer
  memcpy((void *)(remap_dummy_page + offset), buffer, buffer_size);

  // change permission
  mprotect((void *)remap_dummy_page, page_size, PROT_READ | PROT_WRITE);

  int ret = RT_FAILED;
#if defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64)
  ret = code_remap_with_substrated((uint8_t *)remap_dummy_page, (uint32_t)page_size, (addr_t)page_aligned_address);
  if (0 && ret == RT_FAILED)
    DLOG(0, "substrated failed, use vm_remap");
#endif
  if (ret == RT_FAILED) {
    mprotect((void *)remap_dummy_page, page_size, PROT_READ | PROT_EXEC);
    mach_vm_address_t remap_dest_page = (mach_vm_address_t)page_aligned_address;
    vm_prot_t curr_protection, max_protection;
    kr = mach_vm_remap(self_port, (mach_vm_address_t *)&remap_dest_page, page_size, 0,
                       VM_FLAGS_OVERWRITE | VM_FLAGS_FIXED, self_port, (mach_vm_address_t)remap_dummy_page, TRUE,
                       &curr_protection, &max_protection, VM_INHERIT_COPY);
    if (kr != KERN_SUCCESS) {
      return kMemoryOperationError;
    }
  }

  // unmap the origin page
  int err = munmap((void *)remap_dummy_page, (mach_vm_address_t)page_size);
  if (err == -1) {
    return kMemoryOperationError;
  }

#endif

  addr_t clear_start = (addr_t)page_aligned_address + offset;
  DCHECK_EQ(clear_start, (addr_t)address);

  ClearCache((void *)address, (void *)((addr_t)address + buffer_size));
  return kMemoryOperationSuccess;
}
<commit_msg>Disable code patch with substrated at iOS 14.5 temporarily<commit_after>#include "dobby_internal.h"
#include "core/arch/Cpu.h"
#include "PlatformUnifiedInterface/ExecMemory/ClearCacheTool.h"
#include "UnifiedInterface/platform.h"

#include <unistd.h>

#ifdef __APPLE__
#include <mach-o/dyld.h>
#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>
#include "UserMode/UnifiedInterface/platform-darwin/mach_vm.h"
#endif

#if defined(__APPLE__)
#include <dlfcn.h>
#include <mach/vm_statistics.h>
#endif

#include "logging/check_logging.h"

#include "platform_macro.h"

#if defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64)
#include <mach/mach.h>
#include "bootstrap.h"
#include "ExecMemory/substrated/mach_interface_support/substrated_client.h"

#define KERN_ERROR_RETURN(err, failure)                                                                                \
  do {                                                                                \
    if (err != KERN_SUCCESS) {                                                                                \
      return failure;                                                                                \
    }                                                                                \
  } while (0);

static mach_port_t substrated_server_port = MACH_PORT_NULL;

static mach_port_t connect_mach_service(const char *name) {
  mach_port_t port = MACH_PORT_NULL;
  kern_return_t kr;

#if 0
  kr = task_get_special_port(mach_task_self(), TASK_BOOTSTRAP_PORT, &bootstrap_port);
  KERN_ERROR_RETURN(kr, MACH_PORT_NULL)
#endif

  kr = bootstrap_look_up(bootstrap_port, (char *)name, &port);
  KERN_ERROR_RETURN(kr, MACH_PORT_NULL);

  substrated_server_port = port;

  return port;
}

int code_remap_with_substrated(uint8_t *buffer, uint32_t buffer_size, addr_t address) {
  if (!MACH_PORT_VALID(substrated_server_port)) {
    substrated_server_port = connect_mach_service("cy:com.saurik.substrated");
  }
  if (!MACH_PORT_VALID(substrated_server_port))
    return -1;

  kern_return_t kr;
  kr = substrated_mark(substrated_server_port, mach_task_self(), (mach_vm_address_t)buffer, buffer_size,
                       (mach_vm_address_t *)&address);
  if (kr != KERN_SUCCESS) {
    return RT_FAILED;
  }
  return RT_SUCCESS;
}
#endif

PUBLIC MemoryOperationError CodePatch(void *address, uint8_t *buffer, uint32_t buffer_size) {
  kern_return_t kr;

  int page_size = (int)sysconf(_SC_PAGESIZE);
  addr_t page_aligned_address = ALIGN_FLOOR(address, page_size);
  int offset = (int)((addr_t)address - page_aligned_address);

  static mach_port_t self_port = mach_task_self();
#ifdef __APPLE__
  // try modify with substrated (steal from frida-gum)
  addr_t remap_dummy_page =
      (addr_t)mmap(0, page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, VM_MAKE_TAG(255), 0);
  if ((void *)remap_dummy_page == MAP_FAILED)
    return kMemoryOperationError;

  // copy original page
  memcpy((void *)remap_dummy_page, (void *)page_aligned_address, page_size);

  // patch buffer
  memcpy((void *)(remap_dummy_page + offset), buffer, buffer_size);

  // change permission
  mprotect((void *)remap_dummy_page, page_size, PROT_READ | PROT_WRITE);

  int ret = RT_FAILED;
#if 0 && defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64)
  ret = code_remap_with_substrated((uint8_t *)remap_dummy_page, (uint32_t)page_size, (addr_t)page_aligned_address);
  if (0 && ret == RT_FAILED)
    DLOG(0, "substrated failed, use vm_remap");
#endif
  if (ret == RT_FAILED) {
    mprotect((void *)remap_dummy_page, page_size, PROT_READ | PROT_EXEC);
    mach_vm_address_t remap_dest_page = (mach_vm_address_t)page_aligned_address;
    vm_prot_t curr_protection, max_protection;
    kr = mach_vm_remap(self_port, (mach_vm_address_t *)&remap_dest_page, page_size, 0,
                       VM_FLAGS_OVERWRITE | VM_FLAGS_FIXED, self_port, (mach_vm_address_t)remap_dummy_page, TRUE,
                       &curr_protection, &max_protection, VM_INHERIT_COPY);
    if (kr != KERN_SUCCESS) {
      return kMemoryOperationError;
    }
  }

  // unmap the origin page
  int err = munmap((void *)remap_dummy_page, (mach_vm_address_t)page_size);
  if (err == -1) {
    return kMemoryOperationError;
  }

#endif

  addr_t clear_start = (addr_t)page_aligned_address + offset;
  DCHECK_EQ(clear_start, (addr_t)address);

  ClearCache((void *)address, (void *)((addr_t)address + buffer_size));
  return kMemoryOperationSuccess;
}
<|endoftext|>


<commit_before>
#include <QFile>
#include <QString>
#include <QByteArray>
#include <QDomElement>
#include <QDomNodeList>
#include <QDomNode>
#include <QDomNamedNodeMap>

#include <core/logger/Logging.h>

#include "../generic_config/ops/ConfigParser.h"
#include "../generic_config/model/Config.h"
#include "Template.h"
#include "TemplateContainerParser.h"

namespace Quartz {

TemplateContainerParser::TemplateContainerParser()
{

}

TemplateContainerParser::~TemplateContainerParser()
{

}

QVector<std::shared_ptr<Template>> TemplateContainerParser::parse(
        const QString &content)
{
    QVector<std::shared_ptr<Template>> tmpls;
    if (content.isNull()) {
        QZ_ERROR("Qz:Cmn:Tmpl")
                << "Invalid content given to general param parser";
        return tmpls;
    }
    QDomDocument doc;
    QString errorMsg("");
    int errorLine = 0;
    if (doc.setContent(content, false, &errorMsg, &errorLine)) {
        auto root = doc.documentElement();
        if (root.tagName() == "templates") {
            auto tmplLists = root.elementsByTagName("template");
            for (auto i = 0; i < tmplLists.size(); ++ i) {
                auto tmplNode = tmplLists.at(i);
                auto tmpl = parse(tmplNode.toElement());
                if (tmpl != nullptr) {
                    std::shared_ptr<Template> cp = std::move(tmpl);
                    tmpls.append(cp);
                }
                else {
                    QZ_ERROR("Qz:Cmn:Tmpl")
                            << "Could not parse one of the 'template' tags";
                }
            }
            if (tmplLists.isEmpty()) {
                QZ_ERROR("Qz:Cmn:Tmpl")
                        << "Could not find 'template' tags inside 'templates'";
            }
        }
        else {
            QZ_ERROR("Qz:Cmn:Tmpl")
                    << "Could not find root 'templates' tag";
        }
    }
    else {
        QZ_ERROR("Qz:Cmn:Tmpl")
                << "Failed to read config XML content at " << errorLine
                << " Msg: " << errorMsg;

    }
    return tmpls;
}

std::unique_ptr<Config> parseConfig(const QDomElement &root) {
    std::unique_ptr<Config> config;
    auto configNodeList = root.elementsByTagName("config");
    if (configNodeList.size() == 1) {
        auto configNode = configNodeList.at(0);
        ConfigParser configParser;
        config = configParser.parse(configNode.toElement());
        if (config == nullptr) {
            QZ_ERROR("Qz:Cmn:Tmpl")
                    << "Failed to parse template parameters";
        }
    } else {
        auto msg = configNodeList.isEmpty() ? "Could not find config tag"
                                            : "Too many config tags found";
        QZ_ERROR("Qz:Cmn:Tmpl") << msg;
    }
    return config;
}

int readContent(Template *tmpl, const QDomElement &root)
{
    QString content;
    auto count = 0;
    auto cntNodeList = root.elementsByTagName("content");
    for (auto i = 0; i < cntNodeList.size(); ++ i) {
        auto contentNode = cntNodeList.at(i);
        auto name = contentNode.toElement().attribute("name");
        auto children = contentNode.toElement().childNodes();
        auto content = QStringLiteral("");
        for (auto i = 0; i < children.size(); ++ i) {
            auto child = children.at(i);
            if (child.isCDATASection()) {
                auto cdata = child.toCDATASection();
                content = cdata.data();
                break;
            } else if (child.nodeName() == "file") {
                auto path = child.toElement().attribute("path");
                QFile file(path);
                if (file.open(QFile::ReadOnly)) {
                    content = file.readAll();
                    break;
                }
                else {
                    QZ_ERROR("Qz:Cmn:Tmpl")
                            << "Failed to open template file at '"
                            << path << "'";
                }
            }
        }
        if (content.size() != 0) {
            count = count + content.size();
            tmpl->addContent({name, content});
        }
    }
    return count;
}

std::unique_ptr<Template> TemplateContainerParser::parse(
        const QDomElement &root)
{
    std::unique_ptr<Template> tmpl;
    auto name = root.attribute("name");
    if (! name.isEmpty()) {
        auto config = parseConfig(root);
        if (config != nullptr) {
            tmpl = std::make_unique<Template>(name);
            tmpl->setConfig(std::move(config));
            auto count = readContent(tmpl.get(), root);
            if (count == 0) {
                QZ_ERROR("Qz:Cmn:Tmpl")
                        << "Found empty template content";
            }
        }
        else {
            QZ_ERROR("Qz::Cmn:Tmpl")
                    << "Could not find valid config in tempalte container";
        }
    } else {
        QZ_ERROR("Qz:Cmn:Tmpl")
                << "Could not read the template name attribute";
    }
    return tmpl;
}

}
<commit_msg>Formatting changes<commit_after>
#include <QFile>
#include <QString>
#include <QByteArray>
#include <QDomElement>
#include <QDomNodeList>
#include <QDomNode>
#include <QDomNamedNodeMap>

#include <core/logger/Logging.h>

#include "../generic_config/ops/ConfigParser.h"
#include "../generic_config/model/Config.h"
#include "Template.h"
#include "TemplateContainerParser.h"

namespace Quartz {

TemplateContainerParser::TemplateContainerParser()
{

}

TemplateContainerParser::~TemplateContainerParser()
{

}

QVector<std::shared_ptr<Template>> TemplateContainerParser::parse(
        const QString &content)
{
    QVector<std::shared_ptr<Template>> tmpls;
    if (content.isNull()) {
        QZ_ERROR("Qz:Cmn:Tmpl")
                << "Invalid content given to general param parser";
        return tmpls;
    }
    QDomDocument doc;
    QString errorMsg("");
    int errorLine = 0;
    if (doc.setContent(content, false, &errorMsg, &errorLine)) {
        auto root = doc.documentElement();
        if (root.tagName() == "templates") {
            auto tmplLists = root.elementsByTagName("template");
            for (auto i = 0; i < tmplLists.size(); ++ i) {
                auto tmplNode = tmplLists.at(i);
                auto tmpl = parse(tmplNode.toElement());
                if (tmpl != nullptr) {
                    std::shared_ptr<Template> cp = std::move(tmpl);
                    tmpls.append(cp);
                }
                else {
                    QZ_ERROR("Qz:Cmn:Tmpl")
                            << "Could not parse one of the 'template' tags";
                }
            }
            if (tmplLists.isEmpty()) {
                QZ_ERROR("Qz:Cmn:Tmpl")
                        << "Could not find 'template' tags inside 'templates'";
            }
        } else {
            QZ_ERROR("Qz:Cmn:Tmpl")
                    << "Could not find root 'templates' tag";
        }
    } else {
        QZ_ERROR("Qz:Cmn:Tmpl")
                << "Failed to read config XML content at " << errorLine
                << " Msg: " << errorMsg;

    }
    return tmpls;
}

std::unique_ptr<Config> parseConfig(const QDomElement &root) {
    std::unique_ptr<Config> config;
    auto configNodeList = root.elementsByTagName("config");
    if (configNodeList.size() == 1) {
        auto configNode = configNodeList.at(0);
        ConfigParser configParser;
        config = configParser.parse(configNode.toElement());
        if (config == nullptr) {
            QZ_ERROR("Qz:Cmn:Tmpl")
                    << "Failed to parse template parameters";
        }
    } else {
        auto msg = configNodeList.isEmpty() ? "Could not find config tag"
                                            : "Too many config tags found";
        QZ_ERROR("Qz:Cmn:Tmpl") << msg;
    }
    return config;
}

int readContent(Template *tmpl, const QDomElement &root)
{
    QString content;
    auto count = 0;
    auto cntNodeList = root.elementsByTagName("content");
    for (auto i = 0; i < cntNodeList.size(); ++ i) {
        auto contentNode = cntNodeList.at(i);
        auto name = contentNode.toElement().attribute("name");
        auto children = contentNode.toElement().childNodes();
        auto content = QStringLiteral("");
        for (auto i = 0; i < children.size(); ++ i) {
            auto child = children.at(i);
            if (child.isCDATASection()) {
                auto cdata = child.toCDATASection();
                content = cdata.data();
                break;
            } else if (child.nodeName() == "file") {
                auto path = child.toElement().attribute("path");
                QFile file(path);
                if (file.open(QFile::ReadOnly)) {
                    content = file.readAll();
                    break;
                }
                else {
                    QZ_ERROR("Qz:Cmn:Tmpl")
                            << "Failed to open template file at '"
                            << path << "'";
                }
            }
        }
        if (content.size() != 0) {
            count = count + content.size();
            tmpl->addContent({name, content});
        }
    }
    return count;
}

std::unique_ptr<Template> TemplateContainerParser::parse(
        const QDomElement &root)
{
    std::unique_ptr<Template> tmpl;
    auto name = root.attribute("name");
    if (! name.isEmpty()) {
        auto config = parseConfig(root);
        if (config != nullptr) {
            tmpl = std::make_unique<Template>(name);
            tmpl->setConfig(std::move(config));
            auto count = readContent(tmpl.get(), root);
            if (count == 0) {
                QZ_ERROR("Qz:Cmn:Tmpl")
                        << "Found empty template content";
            }
        }
        else {
            QZ_ERROR("Qz::Cmn:Tmpl")
                    << "Could not find valid config in tempalte container";
        }
    } else {
        QZ_ERROR("Qz:Cmn:Tmpl")
                << "Could not read the template name attribute";
    }
    return tmpl;
}

}
<|endoftext|>


<commit_before>//******************************************************************************
// FILE : function_finite_element.hpp
//
// LAST MODIFIED : 13 January 2005
//
// DESCRIPTION :
//==============================================================================
#if !defined (__FUNCTION_FINITE_ELEMENT_HPP__)
#define __FUNCTION_FINITE_ELEMENT_HPP__

#include <list>
#include <utility>

extern "C"
{
#include "finite_element/finite_element.h"
#include "region/cmiss_region.h"
}
#include "computed_variable/function.hpp"
#include "computed_variable/function_variable.hpp"

class Function_element : public Function
//******************************************************************************
// LAST MODIFIED : 13 January 2005
//
// DESCRIPTION :
// An identity function whose input/output is and element.
//==============================================================================
{
	template<class Value_type_1,class Value_type_2>
		friend bool equivalent(boost::intrusive_ptr<Value_type_1> const &,
		boost::intrusive_ptr<Value_type_2> const &);
	public:
		// constructor
		Function_element(struct FE_element *element);
		// destructor
		~Function_element();
	// inherited
	public:
		string_handle get_string_representation();
		Function_variable_handle input();
		Function_variable_handle output();
	// additional
	public:
		// return the dimension of the element
		Function_size_type dimension();
		// return the element.  NB.  The calling program should use
		//   ACCESS(FE_element) and DEACCESS(FE_element) to manage the lifetime of
		//   the returned element
		struct FE_element* element_value();
	private:
#if defined (EVALUATE_RETURNS_VALUE)
		Function_handle evaluate(Function_variable_handle atomic_variable);
#else // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate(Function_variable_handle atomic_variable);
#endif // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate_derivative(Scalar& derivative,
			Function_variable_handle atomic_variable,
			std::list<Function_variable_handle>& atomic_independent_variables);
		bool set_value(Function_variable_handle atomic_variable,
			Function_variable_handle atomic_value);
		Function_handle get_value(Function_variable_handle atomic_variable);
	private:
		// copy constructor
		Function_element(const Function_element&);
		// assignment
		Function_element& operator=(const Function_element&);
		// equality
		bool operator==(const Function&) const;
	private:
		struct FE_element *element_private;
};

typedef boost::intrusive_ptr<Function_element> Function_element_handle;

class Function_element_xi : public Function
//******************************************************************************
// LAST MODIFIED : 13 January 2005
//
// DESCRIPTION :
// An identity function whose input/output is element/xi.
//==============================================================================
{
	friend class Function_finite_element;
	template<class Value_type_1,class Value_type_2>
		friend bool equivalent(boost::intrusive_ptr<Value_type_1> const &,
		boost::intrusive_ptr<Value_type_2> const &);
	public:
		// constructor
		Function_element_xi(struct FE_element *element,const Vector& xi);
		// destructor
		~Function_element_xi();
	// inherited
	public:
		string_handle get_string_representation();
		Function_variable_handle input();
		Function_variable_handle output();
	// additional
	public:
		// variables
		Function_variable_handle
			element(),
			element_xi(),
			xi(),
			xi(Function_size_type);
		// return the dimension of the element and the number of xi
		Function_size_type number_of_xi();
		// return the element.  NB.  The calling program should use
		//   ACCESS(FE_element) and DEACCESS(FE_element) to manage the lifetime of
		//   the returned element
		struct FE_element* element_value();
		// return the xi value 1<=index<=number_of_xi
		Scalar xi_value(Function_size_type index);
	private:
#if defined (EVALUATE_RETURNS_VALUE)
		Function_handle evaluate(Function_variable_handle atomic_variable);
#else // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate(Function_variable_handle atomic_variable);
#endif // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate_derivative(Scalar& derivative,
			Function_variable_handle atomic_variable,
			std::list<Function_variable_handle>& atomic_independent_variables);
		bool set_value(Function_variable_handle atomic_variable,
			Function_variable_handle atomic_value);
		Function_handle get_value(Function_variable_handle atomic_variable);
	private:
		// copy constructor
		Function_element_xi(const Function_element_xi&);
		// assignment
		Function_element_xi& operator=(const Function_element_xi&);
		// equality
		bool operator==(const Function&) const;
	private:
		struct FE_element *element_private;
		Vector xi_private;
};

typedef boost::intrusive_ptr<Function_element_xi> Function_element_xi_handle;

class Function_finite_element;
typedef boost::intrusive_ptr<Function_finite_element>
	Function_finite_element_handle;

class Function_finite_element : public Function
//******************************************************************************
// LAST MODIFIED : 13 January 2005
//
// DESCRIPTION :
// A function for a finite element interpolation field.
//
//???DB.  Make element_private and xi_private a Function_element_xi for
//  evaluate, evaluate_derivative and set_value?
//==============================================================================
{
	friend class Function_variable_matrix_components;
	friend class Function_variable_matrix_nodal_values;
	public:
		// constructor
		Function_finite_element(struct FE_field *field);
		// destructor
		~Function_finite_element();
	// inherited
	public:
		string_handle get_string_representation();
		Function_variable_handle input();
		Function_variable_handle output();
	// additional
	public:
		// variables
		Function_variable_handle
			component(std::string component_name),
			component(Function_size_type component_number),
				// component_number 1 is the first component
			element(),
			element_xi(),
			nodal_values(),
			nodal_values(std::string component_name,struct FE_node *node,
				enum FE_nodal_value_type value_type,Function_size_type version,
				struct FE_time_sequence *time_sequence),
			nodal_values(Function_size_type component_number,struct FE_node *node,
				enum FE_nodal_value_type value_type,Function_size_type version,
				struct FE_time_sequence *time_sequence),
			// use nodal_values_component instead of overloading nodal_values to
			//   prevent same argument signature as for version
			nodal_values_component(std::string component_name),
			nodal_values_component(Function_size_type component_number),
			nodal_values(struct FE_node *node),
			nodal_values(enum FE_nodal_value_type value_type),
			nodal_values(Function_size_type version),
			time(),
			xi(),
			xi(Function_size_type);
		// return the number of components
		Function_size_type number_of_components() const;
		// return the region that the field is defined for
		// NB.  The calling program should use ACCESS(Cmiss_region) and
		//   DEACCESS(Cmiss_region) to manage the lifetime of the returned region
		struct Cmiss_region *region() const;
		// return the number of versions for the component at the node
		Function_size_type number_of_versions(
			Function_size_type component_number,struct FE_node *node) const;
		// return the number of derivatives for the component at the node
		Function_size_type number_of_derivatives(
			Function_size_type component_number,struct FE_node *node) const;
	   // Return the time sequence at the node.
	   struct FE_time_sequence *time_sequence(struct FE_node *node) const;
		// return the (1+number_of_derivatives) nodal value types for the component
		// at the node
		// NB.  The calling program should DEALLOCATE the returned array when it is
		//   no longer needed
		enum FE_nodal_value_type *nodal_value_types(
			Function_size_type component_number,struct FE_node *node) const;
		// return true and get the value if exactly one nodal value is specified,
		//   otherwise return false
		bool get_nodal_value(Function_size_type component_number,
			struct FE_node *node,enum FE_nodal_value_type value_type,
			Function_size_type version,Scalar time,Scalar& value);
		// return true and set the value if exactly one nodal value is specified,
		//   otherwise return false
		bool set_nodal_value(Function_size_type component_number,
			struct FE_node *node,enum FE_nodal_value_type value_type,
			Function_size_type version,Scalar time,Scalar value);
		// return the dimension of the element and the number of xi
		Function_size_type number_of_xi() const;
		// return the element.  NB.  The calling program should use
		//   ACCESS(FE_element) and DEACCESS(FE_element) to manage the lifetime of
		//   the returned element
		struct FE_element* element_value() const;
		// return the time value
		Scalar time_value() const;
		// return the xi value 1<=index<=number_of_xi
		Scalar xi_value(Function_size_type index) const;
		// get the component value 1<=number<=number_of_components
		bool component_value(Function_size_type number,Scalar& value) const;
	   // define the field represented by this function on the given node
	   int define_on_Cmiss_node(struct FE_node *node,
		   struct FE_time_sequence *fe_time_sequence,
	      struct FE_node_field_creator *fe_node_field_creator);
 	   // defines a tensor product basis on element for the field represented by
	   // this function.
	   int define_tensor_product_basis_on_element(
			struct FE_element *element, int dimension, enum FE_basis_type basis_type);
	private:
#if defined (EVALUATE_RETURNS_VALUE)
		Function_handle evaluate(Function_variable_handle atomic_variable);
#else // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate(Function_variable_handle atomic_variable);
#endif // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate_derivative(Scalar& derivative,
			Function_variable_handle atomic_variable,
			std::list<Function_variable_handle>& atomic_independent_variables);
		bool set_value(Function_variable_handle atomic_variable,
			Function_variable_handle atomic_value);
		Function_handle get_value(Function_variable_handle atomic_variable);
	private:
		// copy constructor
		Function_finite_element(const Function_finite_element&);
		// assignment
		Function_finite_element& operator=(const Function_finite_element&);
		// equality
		bool operator==(const Function&) const;
	private:
		Scalar time_private;
		struct FE_element *element_private;
		struct FE_field *field_private;
		struct FE_node *node_private;
		Vector components_private,xi_private;
};

#endif /* !defined (__FUNCTION_FINITE_ELEMENT_HPP__) */
<commit_msg>Added conctruction exception for Function_element_xi.  Added USE_Function_derivatnew_finite_element option<commit_after>//******************************************************************************
// FILE : function_finite_element.hpp
//
// LAST MODIFIED : 8 March 2005
//
// DESCRIPTION :
//==============================================================================
#if !defined (__FUNCTION_FINITE_ELEMENT_HPP__)
#define __FUNCTION_FINITE_ELEMENT_HPP__

#include <list>
#include <utility>

extern "C"
{
#include "finite_element/finite_element.h"
#include "region/cmiss_region.h"
}
#include "computed_variable/function.hpp"
#include "computed_variable/function_variable.hpp"

//???DB.  Testing.
//???DB.  Function_derivatnew_finite_element doesn't currently handle
//  composite independent variables.  Would have to fall back to
//  Function_derivatnew.  End up slower?
//#define USE_Function_derivatnew_finite_element

class Function_element : public Function
//******************************************************************************
// LAST MODIFIED : 13 January 2005
//
// DESCRIPTION :
// An identity function whose input/output is and element.
//==============================================================================
{
	template<class Value_type_1,class Value_type_2>
		friend bool equivalent(boost::intrusive_ptr<Value_type_1> const &,
		boost::intrusive_ptr<Value_type_2> const &);
	public:
		// constructor
		Function_element(struct FE_element *element);
		// destructor
		~Function_element();
	// inherited
	public:
		string_handle get_string_representation();
		Function_variable_handle input();
		Function_variable_handle output();
	// additional
	public:
		// return the dimension of the element
		Function_size_type dimension();
		// return the element.  NB.  The calling program should use
		//   ACCESS(FE_element) and DEACCESS(FE_element) to manage the lifetime of
		//   the returned element
		struct FE_element* element_value();
	private:
#if defined (EVALUATE_RETURNS_VALUE)
		Function_handle evaluate(Function_variable_handle atomic_variable);
#else // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate(Function_variable_handle atomic_variable);
#endif // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate_derivative(Scalar& derivative,
			Function_variable_handle atomic_variable,
			std::list<Function_variable_handle>& atomic_independent_variables);
		bool set_value(Function_variable_handle atomic_variable,
			Function_variable_handle atomic_value);
		Function_handle get_value(Function_variable_handle atomic_variable);
	private:
		// copy constructor
		Function_element(const Function_element&);
		// assignment
		Function_element& operator=(const Function_element&);
		// equality
		bool operator==(const Function&) const;
	private:
		struct FE_element *element_private;
};

typedef boost::intrusive_ptr<Function_element> Function_element_handle;

class Function_element_xi : public Function
//******************************************************************************
// LAST MODIFIED : 8 March 2005
//
// DESCRIPTION :
// An identity function whose input/output is element/xi.
//==============================================================================
{
	friend class Function_finite_element;
	template<class Value_type_1,class Value_type_2>
		friend bool equivalent(boost::intrusive_ptr<Value_type_1> const &,
		boost::intrusive_ptr<Value_type_2> const &);
	public:
		// for construction exception
		class Invalid_element_xi {};
		// constructor
		Function_element_xi(struct FE_element *element,const Vector& xi);
		// destructor
		~Function_element_xi();
	// inherited
	public:
		string_handle get_string_representation();
		Function_variable_handle input();
		Function_variable_handle output();
	// additional
	public:
		// variables
		Function_variable_handle
			element(),
			element_xi(),
			xi(),
			xi(Function_size_type);
		// return the dimension of the element and the number of xi
		Function_size_type number_of_xi();
		// return the element.  NB.  The calling program should use
		//   ACCESS(FE_element) and DEACCESS(FE_element) to manage the lifetime of
		//   the returned element
		struct FE_element* element_value();
		// return the xi value 1<=index<=number_of_xi
		Scalar xi_value(Function_size_type index);
	private:
#if defined (EVALUATE_RETURNS_VALUE)
		Function_handle evaluate(Function_variable_handle atomic_variable);
#else // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate(Function_variable_handle atomic_variable);
#endif // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate_derivative(Scalar& derivative,
			Function_variable_handle atomic_variable,
			std::list<Function_variable_handle>& atomic_independent_variables);
		bool set_value(Function_variable_handle atomic_variable,
			Function_variable_handle atomic_value);
		Function_handle get_value(Function_variable_handle atomic_variable);
	private:
		// copy constructor
		Function_element_xi(const Function_element_xi&);
		// assignment
		Function_element_xi& operator=(const Function_element_xi&);
		// equality
		bool operator==(const Function&) const;
	private:
		struct FE_element *element_private;
		Vector xi_private;
};

typedef boost::intrusive_ptr<Function_element_xi> Function_element_xi_handle;

class Function_finite_element;
typedef boost::intrusive_ptr<Function_finite_element>
	Function_finite_element_handle;

class Function_finite_element : public Function
//******************************************************************************
// LAST MODIFIED : 17 February 2005
//
// DESCRIPTION :
// A function for a finite element interpolation field.
//
//???DB.  Make element_private and xi_private a Function_element_xi for
//  evaluate, evaluate_derivative and set_value?
//==============================================================================
{
	friend class Function_variable_matrix_components;
	friend class Function_variable_matrix_nodal_values;
#if defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
#else // defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
	friend class Function_derivatnew_finite_element;
#endif // defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
	public:
		// constructor
		Function_finite_element(struct FE_field *field);
		// destructor
		~Function_finite_element();
	// inherited
	public:
		string_handle get_string_representation();
		Function_variable_handle input();
		Function_variable_handle output();
	// additional
	public:
		// variables
		Function_variable_handle
			component(std::string component_name),
			component(Function_size_type component_number),
				// component_number 1 is the first component
			element(),
			element_xi(),
			nodal_values(),
			nodal_values(std::string component_name,struct FE_node *node,
				enum FE_nodal_value_type value_type,Function_size_type version,
				struct FE_time_sequence *time_sequence),
			nodal_values(Function_size_type component_number,struct FE_node *node,
				enum FE_nodal_value_type value_type,Function_size_type version,
				struct FE_time_sequence *time_sequence),
			// use nodal_values_component instead of overloading nodal_values to
			//   prevent same argument signature as for version
			nodal_values_component(std::string component_name),
			nodal_values_component(Function_size_type component_number),
			nodal_values(struct FE_node *node),
			nodal_values(enum FE_nodal_value_type value_type),
			nodal_values(Function_size_type version),
			time(),
			xi(),
			xi(Function_size_type);
		// return the number of components
		Function_size_type number_of_components() const;
		// return the region that the field is defined for
		// NB.  The calling program should use ACCESS(Cmiss_region) and
		//   DEACCESS(Cmiss_region) to manage the lifetime of the returned region
		struct Cmiss_region *region() const;
		// return the number of versions for the component at the node
		Function_size_type number_of_versions(
			Function_size_type component_number,struct FE_node *node) const;
		// return the number of derivatives for the component at the node
		Function_size_type number_of_derivatives(
			Function_size_type component_number,struct FE_node *node) const;
	   // Return the time sequence at the node.
	   struct FE_time_sequence *time_sequence(struct FE_node *node) const;
		// return the (1+number_of_derivatives) nodal value types for the component
		// at the node
		// NB.  The calling program should DEALLOCATE the returned array when it is
		//   no longer needed
		enum FE_nodal_value_type *nodal_value_types(
			Function_size_type component_number,struct FE_node *node) const;
		// return true and get the value if exactly one nodal value is specified,
		//   otherwise return false
		bool get_nodal_value(Function_size_type component_number,
			struct FE_node *node,enum FE_nodal_value_type value_type,
			Function_size_type version,Scalar time,Scalar& value);
		// return true and set the value if exactly one nodal value is specified,
		//   otherwise return false
		bool set_nodal_value(Function_size_type component_number,
			struct FE_node *node,enum FE_nodal_value_type value_type,
			Function_size_type version,Scalar time,Scalar value);
		// return the dimension of the element and the number of xi
		Function_size_type number_of_xi() const;
		// return the element.  NB.  The calling program should use
		//   ACCESS(FE_element) and DEACCESS(FE_element) to manage the lifetime of
		//   the returned element
		struct FE_element* element_value() const;
		// return the time value
		Scalar time_value() const;
		// return the xi value 1<=index<=number_of_xi
		Scalar xi_value(Function_size_type index) const;
		// get the component value 1<=number<=number_of_components
		bool component_value(Function_size_type number,Scalar& value) const;
	   // define the field represented by this function on the given node
	   int define_on_Cmiss_node(struct FE_node *node,
		   struct FE_time_sequence *fe_time_sequence,
	      struct FE_node_field_creator *fe_node_field_creator);
 	   // defines a tensor product basis on element for the field represented by
	   // this function.
	   int define_tensor_product_basis_on_element(
			struct FE_element *element, int dimension, enum FE_basis_type basis_type);
	private:
#if defined (EVALUATE_RETURNS_VALUE)
		Function_handle evaluate(Function_variable_handle atomic_variable);
#else // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate(Function_variable_handle atomic_variable);
#endif // defined (EVALUATE_RETURNS_VALUE)
		bool evaluate_derivative(Scalar& derivative,
			Function_variable_handle atomic_variable,
			std::list<Function_variable_handle>& atomic_independent_variables);
#if defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
#else // defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
#if defined (USE_Function_derivatnew_finite_element)
		bool evaluate_derivative_matrix(Function_size_type component_number,
			std::list<Function_variable_handle>& independent_variables,
			Matrix& matrix);
#endif // defined (USE_Function_derivatnew_finite_element)
#endif // defined (USE_FUNCTION_VARIABLE__EVALUATE_DERIVATIVE)
		bool set_value(Function_variable_handle atomic_variable,
			Function_variable_handle atomic_value);
		Function_handle get_value(Function_variable_handle atomic_variable);
	private:
		// copy constructor
		Function_finite_element(const Function_finite_element&);
		// assignment
		Function_finite_element& operator=(const Function_finite_element&);
		// equality
		bool operator==(const Function&) const;
	private:
		Scalar time_private;
		struct FE_element *element_private;
		struct FE_field *field_private;
		struct FE_node *node_private;
		Vector components_private,xi_private;
};

#endif /* !defined (__FUNCTION_FINITE_ELEMENT_HPP__) */
<|endoftext|>


<commit_before>/**
  @file
  @brief A plugin to print session id values.

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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 <ts/ts.h>    // for debug
#include <cstdlib>    // for abort
#include <inttypes.h> // for PRIu64
#include <unordered_set>

// plugin registration info
#define PLUGIN_NAME "session_id_verify"
static char plugin_name[]   = PLUGIN_NAME;
static char vendor_name[]   = "Apache";
static char support_email[] = "bneradt@apache.org";

int
global_handler(TSCont continuation, TSEvent event, void *data)
{
  TSHttpSsn session = static_cast<TSHttpSsn>(data);

  switch (event) {
  case TS_EVENT_HTTP_SSN_START: {
    TSDebug(PLUGIN_NAME, " -- global_handler :: TS_EVENT_HTTP_SSN_START");
    int64_t id = TSHttpSsnIdGet(session);

    static std::unordered_set<int64_t> seen_ids;
    if (seen_ids.find(id) != seen_ids.end()) {
      TSError("[%s] Plugin encountered a duplicate session id: %ld", PLUGIN_NAME, id);
    } else {
      seen_ids.insert(id);
    }
    TSDebug(PLUGIN_NAME, "session id: %ld", id);
  } break;

  default:
    return 0;
  }

  TSHttpSsnReenable(session, TS_EVENT_HTTP_CONTINUE);

  return 0;
}

void
TSPluginInit(int argc, const char *argv[])
{
  TSDebug(PLUGIN_NAME, "initializing plugin");

  TSPluginRegistrationInfo info;

  info.plugin_name   = plugin_name;
  info.vendor_name   = vendor_name;
  info.support_email = support_email;

#if (TS_VERSION_MAJOR < 3)
  if (TSPluginRegister(TS_SDK_VERSION_2_0, &info) != TS_SUCCESS) {
#elif (TS_VERSION_MAJOR < 6)
  if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
#else
  if (TSPluginRegister(&info) != TS_SUCCESS) {
#endif
    TSError("[%s] Plugin registration failed.", PLUGIN_NAME);
  }

  TSCont contp = TSContCreate(global_handler, TSMutexCreate());
  if (contp == nullptr) {
    // Continuation initialization failed. Unrecoverable, report and exit.
    TSError("[%s] could not create continuation.", PLUGIN_NAME);
    std::abort();
  } else {
    // Add all hooks.
    TSHttpHookAdd(TS_HTTP_SSN_START_HOOK, contp);
  }
}
<commit_msg>Fix format string for int64_t (#6963)<commit_after>/**
  @file
  @brief A plugin to print session id values.

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you 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 <ts/ts.h>   // for debug
#include <cstdlib>   // for abort
#include <cinttypes> // for PRId64
#include <unordered_set>

// plugin registration info
#define PLUGIN_NAME "session_id_verify"
static char plugin_name[]   = PLUGIN_NAME;
static char vendor_name[]   = "Apache";
static char support_email[] = "bneradt@apache.org";

int
global_handler(TSCont continuation, TSEvent event, void *data)
{
  TSHttpSsn session = static_cast<TSHttpSsn>(data);

  switch (event) {
  case TS_EVENT_HTTP_SSN_START: {
    TSDebug(PLUGIN_NAME, " -- global_handler :: TS_EVENT_HTTP_SSN_START");
    int64_t id = TSHttpSsnIdGet(session);

    static std::unordered_set<int64_t> seen_ids;
    if (seen_ids.find(id) != seen_ids.end()) {
      TSError("[%s] Plugin encountered a duplicate session id: %" PRId64, PLUGIN_NAME, id);
    } else {
      seen_ids.insert(id);
    }
    TSDebug(PLUGIN_NAME, "session id: %" PRId64, id);
  } break;

  default:
    return 0;
  }

  TSHttpSsnReenable(session, TS_EVENT_HTTP_CONTINUE);

  return 0;
}

void
TSPluginInit(int argc, const char *argv[])
{
  TSDebug(PLUGIN_NAME, "initializing plugin");

  TSPluginRegistrationInfo info;

  info.plugin_name   = plugin_name;
  info.vendor_name   = vendor_name;
  info.support_email = support_email;

#if (TS_VERSION_MAJOR < 3)
  if (TSPluginRegister(TS_SDK_VERSION_2_0, &info) != TS_SUCCESS) {
#elif (TS_VERSION_MAJOR < 6)
  if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
#else
  if (TSPluginRegister(&info) != TS_SUCCESS) {
#endif
    TSError("[%s] Plugin registration failed.", PLUGIN_NAME);
  }

  TSCont contp = TSContCreate(global_handler, TSMutexCreate());
  if (contp == nullptr) {
    // Continuation initialization failed. Unrecoverable, report and exit.
    TSError("[%s] could not create continuation.", PLUGIN_NAME);
    std::abort();
  } else {
    // Add all hooks.
    TSHttpHookAdd(TS_HTTP_SSN_START_HOOK, contp);
  }
}
<|endoftext|>


<commit_before>
#include <python2.7/Python.h>

#include <PythonBindings.h>
#include <SMT2Lib.h>

void initSmtAstNodeEnv(PyObject *idSmtAstNodeClassDict)
{
  PyDict_SetItemString(idSmtAstNodeClassDict, "ASSERT", PyInt_FromLong(smt2lib::ASSERT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVADD", PyInt_FromLong(smt2lib::BVADD_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVAND", PyInt_FromLong(smt2lib::BVAND_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVASHR", PyInt_FromLong(smt2lib::BVASHR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVLSHR", PyInt_FromLong(smt2lib::BVLSHR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVMUL", PyInt_FromLong(smt2lib::BVMUL_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVNAND", PyInt_FromLong(smt2lib::BVNAND_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVNEG", PyInt_FromLong(smt2lib::BVNEG_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVNOR", PyInt_FromLong(smt2lib::BVNOR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVNOT", PyInt_FromLong(smt2lib::BVNOT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVOR", PyInt_FromLong(smt2lib::BVOR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVROL", PyInt_FromLong(smt2lib::BVROL_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVROR", PyInt_FromLong(smt2lib::BVROR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSDIV", PyInt_FromLong(smt2lib::BVSDIV_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSGE", PyInt_FromLong(smt2lib::BVSGE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSGT", PyInt_FromLong(smt2lib::BVSGT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSHL", PyInt_FromLong(smt2lib::BVSHL_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSLE", PyInt_FromLong(smt2lib::BVSLE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSLT", PyInt_FromLong(smt2lib::BVSLT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSMOD", PyInt_FromLong(smt2lib::BVSMOD_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSREM", PyInt_FromLong(smt2lib::BVSREM_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSUB", PyInt_FromLong(smt2lib::BVSUB_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVUDIV", PyInt_FromLong(smt2lib::BVUDIV_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVUGE", PyInt_FromLong(smt2lib::BVUGE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVUGT", PyInt_FromLong(smt2lib::BVUGT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVULE", PyInt_FromLong(smt2lib::BVULE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVULT", PyInt_FromLong(smt2lib::BVULT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVUREM", PyInt_FromLong(smt2lib::BVUREM_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVXNOR", PyInt_FromLong(smt2lib::BVXNOR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVXOR", PyInt_FromLong(smt2lib::BVXOR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BV", PyInt_FromLong(smt2lib::BV_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "COMPOUND", PyInt_FromLong(smt2lib::COMPOUND_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "CONCAT", PyInt_FromLong(smt2lib::CONCAT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "DECIMAL", PyInt_FromLong(smt2lib::DECIMAL_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "DECLARE", PyInt_FromLong(smt2lib::DECLARE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "EQUAL", PyInt_FromLong(smt2lib::EQUAL_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "EXTRACT", PyInt_FromLong(smt2lib::EXTRACT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "ITE", PyInt_FromLong(smt2lib::ITE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "REFERENCE", PyInt_FromLong(smt2lib::REFERENCE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "STRING", PyInt_FromLong(smt2lib::STRING_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "SX", PyInt_FromLong(smt2lib::SX_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "UNDEFINED", PyInt_FromLong(smt2lib::UNDEFINED_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "ZX_NODE", PyInt_FromLong(smt2lib::ZX_NODE));
}

<commit_msg>Fix typo<commit_after>
#include <python2.7/Python.h>

#include <PythonBindings.h>
#include <SMT2Lib.h>

void initSmtAstNodeEnv(PyObject *idSmtAstNodeClassDict)
{
  PyDict_SetItemString(idSmtAstNodeClassDict, "ASSERT", PyInt_FromLong(smt2lib::ASSERT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVADD", PyInt_FromLong(smt2lib::BVADD_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVAND", PyInt_FromLong(smt2lib::BVAND_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVASHR", PyInt_FromLong(smt2lib::BVASHR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVLSHR", PyInt_FromLong(smt2lib::BVLSHR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVMUL", PyInt_FromLong(smt2lib::BVMUL_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVNAND", PyInt_FromLong(smt2lib::BVNAND_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVNEG", PyInt_FromLong(smt2lib::BVNEG_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVNOR", PyInt_FromLong(smt2lib::BVNOR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVNOT", PyInt_FromLong(smt2lib::BVNOT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVOR", PyInt_FromLong(smt2lib::BVOR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVROL", PyInt_FromLong(smt2lib::BVROL_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVROR", PyInt_FromLong(smt2lib::BVROR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSDIV", PyInt_FromLong(smt2lib::BVSDIV_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSGE", PyInt_FromLong(smt2lib::BVSGE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSGT", PyInt_FromLong(smt2lib::BVSGT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSHL", PyInt_FromLong(smt2lib::BVSHL_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSLE", PyInt_FromLong(smt2lib::BVSLE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSLT", PyInt_FromLong(smt2lib::BVSLT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSMOD", PyInt_FromLong(smt2lib::BVSMOD_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSREM", PyInt_FromLong(smt2lib::BVSREM_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVSUB", PyInt_FromLong(smt2lib::BVSUB_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVUDIV", PyInt_FromLong(smt2lib::BVUDIV_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVUGE", PyInt_FromLong(smt2lib::BVUGE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVUGT", PyInt_FromLong(smt2lib::BVUGT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVULE", PyInt_FromLong(smt2lib::BVULE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVULT", PyInt_FromLong(smt2lib::BVULT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVUREM", PyInt_FromLong(smt2lib::BVUREM_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVXNOR", PyInt_FromLong(smt2lib::BVXNOR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BVXOR", PyInt_FromLong(smt2lib::BVXOR_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "BV", PyInt_FromLong(smt2lib::BV_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "COMPOUND", PyInt_FromLong(smt2lib::COMPOUND_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "CONCAT", PyInt_FromLong(smt2lib::CONCAT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "DECIMAL", PyInt_FromLong(smt2lib::DECIMAL_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "DECLARE", PyInt_FromLong(smt2lib::DECLARE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "EQUAL", PyInt_FromLong(smt2lib::EQUAL_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "EXTRACT", PyInt_FromLong(smt2lib::EXTRACT_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "ITE", PyInt_FromLong(smt2lib::ITE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "REFERENCE", PyInt_FromLong(smt2lib::REFERENCE_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "STRING", PyInt_FromLong(smt2lib::STRING_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "SX", PyInt_FromLong(smt2lib::SX_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "UNDEFINED", PyInt_FromLong(smt2lib::UNDEFINED_NODE));
  PyDict_SetItemString(idSmtAstNodeClassDict, "ZX", PyInt_FromLong(smt2lib::ZX_NODE));
}

<|endoftext|>


<commit_before>#include "message.h"
#include "details/atom/atom.h"
#include <yuni/core/system/console/console.h>

using namespace Yuni;

#ifndef YUNI_OS_WINDOWS
#define SEP " \u205E "
#else
#define SEP " : "
#endif

namespace Nany
{
namespace Logs
{

	Message& Message::createEntry(Level level)
	{
		Message* entry = new Message{level};

		ThreadingPolicy::MutexLocker locker{*this};
		entry->origins = origins;
		entries.push_back(entry);
		return *entry;
	}

	void Message::appendEntry(const Message::Ptr& entry)
	{
		if (!!entry)
		{
			if (not (entry->entries.empty() and entry->level == Level::none))
			{
				ThreadingPolicy::MutexLocker locker{*this};
				entries.push_back(entry);
				hasErrors &= entry->hasErrors;
			}
		}
	}

	namespace // anonymous
	{

		template<bool unify>
		static void printMessage(nyconsole_t& out, const Message& message, uint32_t indent, String& xx)
		{
			Message::ThreadingPolicy::MutexLocker locker{message};

			// which output ?
			nyconsole_output_t omode = (unify or (message.level != Level::error and message.level != Level::warning))
				? nycout : nycerr;
			// function writer
			auto wrfn = (omode == nycout) ? out.write_stdout : out.write_stderr;
			// print method
			auto print = [&](const AnyString& s) { wrfn(out.internal, s.c_str(), s.size()); };

			if (message.level != Level::none)
			{
				switch (message.level)
				{
					case Level::error:
					{
						out.set_color(out.internal, omode, nyc_red);
						print("   error" SEP);
						out.set_color(out.internal, omode, nyc_none);
						break;
					}
					case Level::warning:
					{
						out.set_color(out.internal, omode, nyc_yellow);
						print(" warning" SEP);
						out.set_color(out.internal, omode, nyc_none);
						break;
					}
					case Level::info:
					{
						if (message.section.empty())
						{
							out.set_color(out.internal, omode, nyc_none);
							print("        " SEP);
						}
						else
						{
							out.set_color(out.internal, omode, nyc_lightblue);
							xx = "        ";
							xx.overwriteRight(message.section);
							xx << SEP;
							print(xx);
							out.set_color(out.internal, omode, nyc_none);
						}
						break;
					}
					case Level::hint:
					case Level::suggest:
					{
						out.set_color(out.internal, omode, nyc_none);
						print("        " SEP);
						out.set_color(out.internal, omode, nyc_none);
						break;
					}
					case Level::success:
					{
						out.set_color(out.internal, omode, nyc_green);
						#ifndef YUNI_OS_WINDOWS
						print("      \u2713 " SEP);
						#else
						print("      ok" SEP);
						#endif
						out.set_color(out.internal, omode, nyc_none);
						break;
					}
					case Level::trace:
					{
						out.set_color(out.internal, omode, nyc_purple);
						print("      ::");
						out.set_color(out.internal, omode, nyc_none);
						print(SEP);
						break;
					}
					case Level::verbose:
					{
						out.set_color(out.internal, omode, nyc_green);
						print("      ::");
						out.set_color(out.internal, omode, nyc_none);
						print(SEP);
						break;
					}
					case Level::ICE:
					{
						out.set_color(out.internal, omode, nyc_red);
						print("     ICE" SEP);
						out.set_color(out.internal, omode, nyc_none);
						break;
					}
					case Level::none:
					{
						// unreachable - cf condition above
						break;
					}
				}

				if (indent)
				{
					xx.clear();
					for (uint32_t i = indent; i--; )
						xx << "    ";
					print(xx);
				}

				if (not message.prefix.empty())
				{
					out.set_color(out.internal, omode, nyc_white);
					print(message.prefix);
					out.set_color(out.internal, omode, nyc_none);
				}

				if (message.level == Level::suggest)
				{
					out.set_color(out.internal, omode, nyc_lightblue);
					print("suggest: ");
					out.set_color(out.internal, omode, nyc_none);
				}
				else if (message.level == Level::hint)
				{
					out.set_color(out.internal, omode, nyc_lightblue);
					print("hint: ");
					out.set_color(out.internal, omode, nyc_none);
				}

				if (not message.origins.location.target.empty())
				{
					print("{");
					print(message.origins.location.target);
					print("} ");
				}

				if (not message.origins.location.filename.empty())
				{
					out.set_color(out.internal, omode, nyc_white);
					xx = message.origins.location.filename;

					if (message.origins.location.pos.line > 0)
					{
						xx << ':';
						xx << message.origins.location.pos.line;
						if (message.origins.location.pos.offset != 0)
						{
							xx << ':';
							xx << message.origins.location.pos.offset;
							if (message.origins.location.pos.offsetEnd != 0)
							{
								xx << '-';
								xx << message.origins.location.pos.offsetEnd;
							}
						}
					}
					xx << ": ";
					print(xx);
					out.set_color(out.internal, omode, nyc_none);
				}

				if (not message.message.empty())
				{
					String msg{message.message};
					msg.trimRight(" \t\r\n");
					msg.replace("\t", "    "); // tabs

					auto firstLF = msg.find('\n');
					if (not (firstLF < message.message.size()))
					{
						print(msg);
					}
					else
					{
						xx.clear() << "\n        " SEP;
						for (uint i = indent; i--; )
							xx.write("    ", 4);

						bool addLF = false;
						msg.words("\n", [&](const AnyString& word) -> bool
						{
							if (addLF)
								print(xx);
							print(word);
							addLF = true;
							return true;
						});
					}
				}

				print("\n");
				++indent;
			}

			for (auto& ptr: message.entries)
				printMessage<unify>(out, *ptr, indent, xx);
		}

	} // anonymous namespace

	void Message::print(nyconsole_t& out, bool unify)
	{
		assert(out.set_color);
		if (out.set_color and out.write_stderr and out.write_stdout)
		{
			String tmp;
			tmp.reserve(1024);
			if (unify)
				printMessage<true>(out, *this, 0, tmp);
			else
				printMessage<false>(out, *this, 0, tmp);
		}
	}

	void Message::Origin::Location::resetFromAtom(const Atom& atom)
	{
		filename = atom.origin.filename;
		pos.line = atom.origin.line;
		pos.offset = atom.origin.offset;
	}

} // namespace Logs
} // namespace Nany
<commit_msg>reporting: coding style<commit_after>#include "message.h"
#include "details/atom/atom.h"
#include <yuni/core/system/console/console.h>

using namespace Yuni;

#ifndef YUNI_OS_WINDOWS
#define SEP " \u205E "
#else
#define SEP " : "
#endif

namespace Nany
{
namespace Logs
{

	namespace {

	template<bool unify>
	void printMessageRecursive(nyconsole_t& out, const Message& message, String& xx, uint32_t indent = 0)
	{
		Message::ThreadingPolicy::MutexLocker locker{message};

		// which output ?
		nyconsole_output_t omode = (unify or (message.level != Level::error and message.level != Level::warning))
			? nycout : nycerr;
		// function writer
		auto wrfn = (omode == nycout) ? out.write_stdout : out.write_stderr;
		// print method
		auto print = [&](const AnyString& s) { wrfn(out.internal, s.c_str(), s.size()); };

		if (message.level != Level::none)
		{
			switch (message.level)
			{
				case Level::error:
				{
					out.set_color(out.internal, omode, nyc_red);
					print("   error" SEP);
					out.set_color(out.internal, omode, nyc_none);
					break;
				}
				case Level::warning:
				{
					out.set_color(out.internal, omode, nyc_yellow);
					print(" warning" SEP);
					out.set_color(out.internal, omode, nyc_none);
					break;
				}
				case Level::info:
				{
					if (message.section.empty())
					{
						out.set_color(out.internal, omode, nyc_none);
						print("        " SEP);
					}
					else
					{
						out.set_color(out.internal, omode, nyc_lightblue);
						xx = "        ";
						xx.overwriteRight(message.section);
						xx << SEP;
						print(xx);
						out.set_color(out.internal, omode, nyc_none);
					}
					break;
				}
				case Level::hint:
				case Level::suggest:
				{
					out.set_color(out.internal, omode, nyc_none);
					print("        " SEP);
					out.set_color(out.internal, omode, nyc_none);
					break;
				}
				case Level::success:
				{
					out.set_color(out.internal, omode, nyc_green);
					#ifndef YUNI_OS_WINDOWS
					print("      \u2713 " SEP);
					#else
					print("      ok" SEP);
					#endif
					out.set_color(out.internal, omode, nyc_none);
					break;
				}
				case Level::trace:
				{
					out.set_color(out.internal, omode, nyc_purple);
					print("      ::");
					out.set_color(out.internal, omode, nyc_none);
					print(SEP);
					break;
				}
				case Level::verbose:
				{
					out.set_color(out.internal, omode, nyc_green);
					print("      ::");
					out.set_color(out.internal, omode, nyc_none);
					print(SEP);
					break;
				}
				case Level::ICE:
				{
					out.set_color(out.internal, omode, nyc_red);
					print("     ICE" SEP);
					out.set_color(out.internal, omode, nyc_none);
					break;
				}
				case Level::none:
				{
					// unreachable - cf condition above
					break;
				}
			}

			if (indent)
			{
				xx.clear();
				for (uint32_t i = indent; i--; )
					xx << "    ";
				print(xx);
			}

			if (not message.prefix.empty())
			{
				out.set_color(out.internal, omode, nyc_white);
				print(message.prefix);
				out.set_color(out.internal, omode, nyc_none);
			}

			if (message.level == Level::suggest)
			{
				out.set_color(out.internal, omode, nyc_lightblue);
				print("suggest: ");
				out.set_color(out.internal, omode, nyc_none);
			}
			else if (message.level == Level::hint)
			{
				out.set_color(out.internal, omode, nyc_lightblue);
				print("hint: ");
				out.set_color(out.internal, omode, nyc_none);
			}

			if (not message.origins.location.target.empty())
			{
				print("{");
				print(message.origins.location.target);
				print("} ");
			}

			if (not message.origins.location.filename.empty())
			{
				out.set_color(out.internal, omode, nyc_white);
				xx = message.origins.location.filename;

				if (message.origins.location.pos.line > 0)
				{
					xx << ':';
					xx << message.origins.location.pos.line;
					if (message.origins.location.pos.offset != 0)
					{
						xx << ':';
						xx << message.origins.location.pos.offset;
						if (message.origins.location.pos.offsetEnd != 0)
						{
							xx << '-';
							xx << message.origins.location.pos.offsetEnd;
						}
					}
				}
				xx << ": ";
				print(xx);
				out.set_color(out.internal, omode, nyc_none);
			}

			if (not message.message.empty())
			{
				String msg{message.message};
				msg.trimRight(" \t\r\n");
				msg.replace("\t", "    "); // tabs

				auto firstLF = msg.find('\n');
				if (not (firstLF < message.message.size()))
				{
					print(msg);
				}
				else
				{
					xx.clear() << "\n        " SEP;
					for (uint i = indent; i--; )
						xx.write("    ", 4);

					bool addLF = false;
					msg.words("\n", [&](const AnyString& word) -> bool {
						if (addLF)
							print(xx);
						print(word);
						addLF = true;
						return true;
					});
				}
			}

			print("\n");
			++indent;
		}

		for (auto& ptr: message.entries)
			printMessageRecursive<unify>(out, *ptr, xx, indent);
	}

	} // anonymous namespace

	Message& Message::createEntry(Level level)
	{
		Message* entry = new Message{level};
		ThreadingPolicy::MutexLocker locker{*this};
		entry->origins = origins;
		entries.push_back(entry);
		return *entry;
	}

	void Message::appendEntry(const Message::Ptr& entry)
	{
		if (!!entry)
		{
			if (not (entry->entries.empty() and entry->level == Level::none))
			{
				ThreadingPolicy::MutexLocker locker{*this};
				entries.push_back(entry);
				hasErrors &= entry->hasErrors;
			}
		}
	}

	void Message::print(nyconsole_t& out, bool unify)
	{
		assert(out.set_color);
		if (out.set_color and out.write_stderr and out.write_stdout)
		{
			String tmp;
			tmp.reserve(1024);
			if (unify)
				printMessageRecursive<true>(out, *this, tmp);
			else
				printMessageRecursive<false>(out, *this, tmp);
		}
	}

	void Message::Origin::Location::resetFromAtom(const Atom& atom)
	{
		filename = atom.origin.filename;
		pos.line = atom.origin.line;
		pos.offset = atom.origin.offset;
	}

} // namespace Logs
} // namespace Nany
<|endoftext|>


<commit_before>#include "ovdCInputDialog.h"
#include <gdk/gdkkeysyms.h>

using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace OpenViBEDesigner;

CInputDialog::CInputDialog(const char* sGladeXML, fpButtonCB fpOKButtonCB, void* pUserData, const char* sTitle, const char* sLabel, const char* sEntry)
{
	m_fpOKButtonCB = fpOKButtonCB;
	m_pUserData = pUserData;

	//retrieve input dialog
	::GladeXML* l_pInputDialogInterface = glade_xml_new(sGladeXML, "input_dialog", NULL);
	m_pInputDialog = GTK_DIALOG(glade_xml_get_widget(l_pInputDialogInterface, "input_dialog"));
	m_pInputDialogLabel = GTK_LABEL(glade_xml_get_widget(l_pInputDialogInterface, "sLabel"));
	m_pInputDialogEntry = GTK_ENTRY(glade_xml_get_widget(l_pInputDialogInterface, "sEntry"));
	m_pInputDialogOKButton = GTK_BUTTON(glade_xml_get_widget(l_pInputDialogInterface, "button_ok"));
	m_pInputDialogCancelButton = GTK_BUTTON(glade_xml_get_widget(l_pInputDialogInterface, "button_cancel"));

	GTK_WIDGET_SET_FLAGS(GTK_WIDGET(m_pInputDialogEntry), GDK_KEY_PRESS_MASK);
	g_signal_connect(G_OBJECT(m_pInputDialogEntry), "key-press-event", G_CALLBACK(key_press_event_cb), m_pInputDialog);

	if(sLabel != NULL)
	{
		gtk_label_set(m_pInputDialogLabel, sLabel);
	}
	if(sEntry != NULL)
	{
		gtk_entry_set_text(m_pInputDialogEntry, sEntry);
	}

	g_signal_connect(G_OBJECT(m_pInputDialogOKButton), "clicked", G_CALLBACK(button_clicked_cb), this);
	g_signal_connect(G_OBJECT(m_pInputDialogCancelButton), "clicked", G_CALLBACK(button_clicked_cb), this);

	gtk_window_set_position(GTK_WINDOW(m_pInputDialog), GTK_WIN_POS_MOUSE);
	gtk_window_set_title(GTK_WINDOW(m_pInputDialog), sTitle);
}

CInputDialog::~CInputDialog()
{
	gtk_widget_destroy(GTK_WIDGET(m_pInputDialog));
}

void CInputDialog::run()
{
	gint l_iResult = gtk_dialog_run(m_pInputDialog);

	if(l_iResult == GTK_RESPONSE_ACCEPT)
	{
		if(m_fpOKButtonCB != NULL)
		{
			m_fpOKButtonCB(GTK_WIDGET(m_pInputDialogOKButton), this);
		}
	}

	gtk_widget_hide_all(GTK_WIDGET(m_pInputDialog));
}

void* CInputDialog::getUserData()
{
	return m_pUserData;
}

const char* CInputDialog::getEntry()
{
	return (const char*)gtk_entry_get_text(m_pInputDialogEntry);
}

gboolean CInputDialog::key_press_event_cb(::GtkWidget* pWidget, GdkEventKey* pEventKey, gpointer pUserData)
{
	if(pEventKey->keyval==GDK_Return || pEventKey->keyval==GDK_KP_Enter)
	{
		gtk_dialog_response(GTK_DIALOG(pUserData), GTK_RESPONSE_ACCEPT);
		return TRUE;
	}
	else if(pEventKey->keyval==GDK_Escape)
	{
		gtk_dialog_response(GTK_DIALOG(pUserData), GTK_RESPONSE_REJECT);
		return TRUE;
	}

	return FALSE;
}

void CInputDialog::button_clicked_cb(::GtkButton* pButton, gpointer pUserData)
{
	static_cast<CInputDialog*>(pUserData)->buttonClickedCB(pButton);
}

void CInputDialog::buttonClickedCB(::GtkButton* pButton)
{
	if(pButton == m_pInputDialogOKButton)
	{
		gtk_dialog_response(m_pInputDialog, GTK_RESPONSE_ACCEPT);
	}
	else
	{
		gtk_dialog_response(m_pInputDialog, GTK_RESPONSE_REJECT);
	}
}
<commit_msg>openvibe-application-designer :  * corrected bug on input dialog that caused crash<commit_after>#include "ovdCInputDialog.h"
#include <gdk/gdkkeysyms.h>

using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace OpenViBEDesigner;

CInputDialog::CInputDialog(const char* sGladeXML, fpButtonCB fpOKButtonCB, void* pUserData, const char* sTitle, const char* sLabel, const char* sEntry)
{
	m_fpOKButtonCB = fpOKButtonCB;
	m_pUserData = pUserData;

	//retrieve input dialog
	::GladeXML* l_pInputDialogInterface = glade_xml_new(sGladeXML, "input_dialog", NULL);
	m_pInputDialog = GTK_DIALOG(glade_xml_get_widget(l_pInputDialogInterface, "input_dialog"));
	m_pInputDialogLabel = GTK_LABEL(glade_xml_get_widget(l_pInputDialogInterface, "label"));
	m_pInputDialogEntry = GTK_ENTRY(glade_xml_get_widget(l_pInputDialogInterface, "entry"));
	m_pInputDialogOKButton = GTK_BUTTON(glade_xml_get_widget(l_pInputDialogInterface, "button_ok"));
	m_pInputDialogCancelButton = GTK_BUTTON(glade_xml_get_widget(l_pInputDialogInterface, "button_cancel"));

	GTK_WIDGET_SET_FLAGS(GTK_WIDGET(m_pInputDialogEntry), GDK_KEY_PRESS_MASK);
	g_signal_connect(G_OBJECT(m_pInputDialogEntry), "key-press-event", G_CALLBACK(key_press_event_cb), m_pInputDialog);

	if(sLabel != NULL)
	{
		gtk_label_set(m_pInputDialogLabel, sLabel);
	}
	if(sEntry != NULL)
	{
		gtk_entry_set_text(m_pInputDialogEntry, sEntry);
	}

	g_signal_connect(G_OBJECT(m_pInputDialogOKButton), "clicked", G_CALLBACK(button_clicked_cb), this);
	g_signal_connect(G_OBJECT(m_pInputDialogCancelButton), "clicked", G_CALLBACK(button_clicked_cb), this);

	gtk_window_set_position(GTK_WINDOW(m_pInputDialog), GTK_WIN_POS_MOUSE);
	gtk_window_set_title(GTK_WINDOW(m_pInputDialog), sTitle);
}

CInputDialog::~CInputDialog()
{
	gtk_widget_destroy(GTK_WIDGET(m_pInputDialog));
}

void CInputDialog::run()
{
	gint l_iResult = gtk_dialog_run(m_pInputDialog);

	if(l_iResult == GTK_RESPONSE_ACCEPT)
	{
		if(m_fpOKButtonCB != NULL)
		{
			m_fpOKButtonCB(GTK_WIDGET(m_pInputDialogOKButton), this);
		}
	}

	gtk_widget_hide_all(GTK_WIDGET(m_pInputDialog));
}

void* CInputDialog::getUserData()
{
	return m_pUserData;
}

const char* CInputDialog::getEntry()
{
	return (const char*)gtk_entry_get_text(m_pInputDialogEntry);
}

gboolean CInputDialog::key_press_event_cb(::GtkWidget* pWidget, GdkEventKey* pEventKey, gpointer pUserData)
{
	if(pEventKey->keyval==GDK_Return || pEventKey->keyval==GDK_KP_Enter)
	{
		gtk_dialog_response(GTK_DIALOG(pUserData), GTK_RESPONSE_ACCEPT);
		return TRUE;
	}
	else if(pEventKey->keyval==GDK_Escape)
	{
		gtk_dialog_response(GTK_DIALOG(pUserData), GTK_RESPONSE_REJECT);
		return TRUE;
	}

	return FALSE;
}

void CInputDialog::button_clicked_cb(::GtkButton* pButton, gpointer pUserData)
{
	static_cast<CInputDialog*>(pUserData)->buttonClickedCB(pButton);
}

void CInputDialog::buttonClickedCB(::GtkButton* pButton)
{
	if(pButton == m_pInputDialogOKButton)
	{
		gtk_dialog_response(m_pInputDialog, GTK_RESPONSE_ACCEPT);
	}
	else
	{
		gtk_dialog_response(m_pInputDialog, GTK_RESPONSE_REJECT);
	}
}
<|endoftext|>