<commit_before>#define BOOST_TEST_MODULE AdaptiveSimpsonTest
#define BOOST_TEST_MAIN
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
#include <boost/test/unit_test.hpp>
#include <boost/math/special_functions/spherical_harmonic.hpp>

#include "SpinWaveGenie/Plot/AdaptiveSimpson.h"

std::vector<double> constantFunction(std::deque<double> &x)
{
  std::vector<double> result;
  result.reserve(x.size());
  for (std::size_t i = 0; i < x.size(); i++)
  {
    result.push_back(i + 1);
  }
  return result;
};

BOOST_AUTO_TEST_CASE(ConstantFunctionTest)
{
  std::function<std::vector<double>(std::deque<double> & x)> f =
      std::bind<std::vector<double>>(constantFunction, std::placeholders::_1);
  AdaptiveSimpson test;
  test.setFunction(f);
  std::vector<double> lower_bounds = {0.0, 0.0, 0.0};
  std::vector<double> upper_bounds = {1.0, 2.0, 3.0};
  test.setInterval(lower_bounds, upper_bounds);
  auto result = test.integrate();
  BOOST_CHECK_CLOSE(result[0], 6.0, 1.0e-3);
  BOOST_CHECK_CLOSE(result[1], 12.0, 1.0e-3);
  BOOST_CHECK_CLOSE(result[2], 18.0, 1.0e-3);
}

class SphericalHarmonics
{
public:
  SphericalHarmonics(unsigned n1, unsigned n2)
  {
    m_n1 = n1;
    m_n2 = n2;
  };
  std::vector<double> getPoint(std::deque<double> &angles)
  {
    double theta = angles[0];
    double phi = angles[1];
    double tmp1 = boost::math::spherical_harmonic_r(m_n1, 0, theta, phi);
    double tmp2 = boost::math::spherical_harmonic_r(m_n2, 0, theta, phi);
    return std::vector<double>(1, tmp1 * tmp2 * sin(theta));
  };

private:
  unsigned m_n1, m_n2;
};

BOOST_AUTO_TEST_CASE(SphericalHarmonicsTest)
{
  for (unsigned n1 = 0; n1 < 4; ++n1)
  {
    for (unsigned n2 = 0; n2 < 4; ++n2)
    {
      SphericalHarmonics myClass(n1, n2);
      std::function<std::vector<double>(std::deque<double> & x)> f =
          std::bind<std::vector<double>>(&SphericalHarmonics::getPoint, &myClass, std::placeholders::_1);
      AdaptiveSimpson test;
      test.setFunction(f);
      std::vector<double> lower_bounds = {0.0, 0.0};
      std::vector<double> upper_bounds = {M_PI, 2.0 * M_PI};
      test.setInterval(lower_bounds, upper_bounds);
      auto result = test.integrate();

      if (n1 == n2)
      {
        BOOST_CHECK_CLOSE(result[0], 1.0, 1.0e-3);
      }
      else
      {
        BOOST_CHECK_SMALL(result[0], 1.0e-3);
      }
    }
  }
}

/* Simple product function */
// double f0 (unsigned dim, const double *x, void *params)
std::vector<double> productFunction(std::deque<double> &x)
{
  std::vector<double> prod(1, 1.0);
  unsigned int i;
  for (i = 0; i < x.size(); ++i)
    prod[0] *= 2.0 * x[i];
  return prod;
}

/* Gaussian centered at 1/2. */
std::vector<double> gaussianFunction(std::deque<double> &x)
{
  std::size_t dim = x.size();
  double a = 0.1;
  double sum = 0.0;
  for (unsigned int i = 0; i < dim; i++)
  {
    double dx = x[i] - 0.5;
    sum += dx * dx;
  }
  std::vector<double> result(1);
  result[0] = std::pow(M_2_SQRTPI / (2.0 * a), dim) * exp(-sum / (a * a));
  return result;
}

//also test move assignment operator.
BOOST_AUTO_TEST_CASE(GaussianFunctionTest)
{
  std::function<std::vector<double>(std::deque<double> & x)> f =
      std::bind<std::vector<double>>(gaussianFunction, std::placeholders::_1);
  AdaptiveSimpson test,moveTest;
  test.setFunction(f);
  std::vector<double> lower_bounds = {0.0, 0.0};
  std::vector<double> upper_bounds = {1.0, 1.0};
  test.setInterval(lower_bounds, upper_bounds);
  auto result = test.integrate();
  BOOST_CHECK_CLOSE(result[0], 1.0, 1.0e-3);
  moveTest = std::move(test);
  result = moveTest.integrate();
  BOOST_CHECK_CLOSE(result[0], 1.0, 1.0e-3);
}

/* double gaussian */
std::vector<double> doubleGaussianFunction(std::deque<double> &x)
{
  std::size_t dim = x.size();
  double a = 0.1;
  double sum1 = 0.0;
  double sum2 = 0.0;
  for (unsigned int i = 0; i < dim; i++)
  {
    double dx1 = x[i] - 1.0 / 3.0;
    double dx2 = x[i] - 2.0 / 3.0;
    sum1 += dx1 * dx1;
    sum2 += dx2 * dx2;
  }
  std::vector<double> result(1);
  result[0] = 0.5 * std::pow(M_2_SQRTPI / (2.0 * a), dim) * (std::exp(-sum1 / (a * a)) + std::exp(-sum2 / (a * a)));
  return result;
}

// also tests move constructor
BOOST_AUTO_TEST_CASE(DoubleGaussianFunctionTest)
{
  std::function<std::vector<double>(std::deque<double> & x)> f =
      std::bind<std::vector<double>>(doubleGaussianFunction, std::placeholders::_1);
  AdaptiveSimpson test;
  test.setFunction(f);
  std::vector<double> lower_bounds = {0.0, 0.0};
  std::vector<double> upper_bounds = {1.0, 1.0};
  test.setInterval(lower_bounds, upper_bounds);
  auto result1 = test.integrate();
  BOOST_CHECK_CLOSE(result1[0], 1.0, 1.0e-3);
  AdaptiveSimpson moveTest(std::move(test));
  auto result2 = moveTest.integrate();
  BOOST_CHECK_CLOSE(result2[0], 1.0, 1.0e-3);
}

/* Tsuda's example */
std::vector<double> tsudasFunction(std::deque<double> &x)
{
  std::size_t dim = x.size();
  double c = (1.0 + sqrt(10.0)) / 9.0;
  std::vector<double> result(1, 1.0);
  unsigned int i;
  for (i = 0; i < dim; i++)
    result[0] *= c / (c + 1) * pow((c + 1) / (c + x[i]), 2.0);
  return result;
}

// also tests copy constructor
BOOST_AUTO_TEST_CASE(TsudasFunctionTest)
{
  std::function<std::vector<double>(std::deque<double> & x)> f =
      std::bind<std::vector<double>>(tsudasFunction, std::placeholders::_1);
  AdaptiveSimpson test;
  test.setFunction(f);
  std::vector<double> lower_bounds = {0.0, 0.0};
  std::vector<double> upper_bounds = {1.0, 1.0};
  test.setInterval(lower_bounds, upper_bounds);
  auto result1 = test.integrate();
  BOOST_CHECK_CLOSE(result1[0], 1.0, 1.0e-3);
  AdaptiveSimpson copyTest(test);
  auto result2 = copyTest.integrate();
  BOOST_CHECK_CLOSE(result2[0], 1.0, 1.0e-3);
}

std::vector<double> complexFunction(std::deque<double> &x)
{
  std::size_t dim = x.size();
  double p = 1.0 / dim;
  double prod = pow(1 + p, dim);
  unsigned int i;
  for (i = 0; i < dim; i++)
    prod *= pow(x[i], p);
  return std::vector<double>(1, prod);
};

// also tests copy assignment operator
BOOST_AUTO_TEST_CASE(ComplexFunctionTest)
{
  std::function<std::vector<double>(std::deque<double> & x)> f =
      std::bind<std::vector<double>>(complexFunction, std::placeholders::_1);
  AdaptiveSimpson test,copyTest;
  test.setFunction(f);
  std::vector<double> lower_bounds = {0.0, 0.0};
  std::vector<double> upper_bounds = {1.0, 1.0};
  test.setInterval(lower_bounds, upper_bounds);
  auto result1 = test.integrate();
  BOOST_CHECK_CLOSE(result1[0], 1.0, 1.0e-3);
  copyTest = test;
  auto result2 = copyTest.integrate();
  BOOST_CHECK_CLOSE(result2[0], 1.0, 1.0e-3);
}
<commit_msg>Fix warning in AdaptiveSimpsonTest.<commit_after>#define BOOST_TEST_MODULE AdaptiveSimpsonTest
#define BOOST_TEST_MAIN
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
#include <boost/test/unit_test.hpp>
#include <boost/math/special_functions/spherical_harmonic.hpp>

#include "SpinWaveGenie/Plot/AdaptiveSimpson.h"

std::vector<double> constantFunction(std::deque<double> &x)
{
  std::vector<double> result;
  result.reserve(x.size());
  for (std::size_t i = 0; i < x.size(); i++)
  {
    result.push_back(static_cast<double>(i) + 1.0);
  }
  return result;
};

BOOST_AUTO_TEST_CASE(ConstantFunctionTest)
{
  std::function<std::vector<double>(std::deque<double> & x)> f =
      std::bind<std::vector<double>>(constantFunction, std::placeholders::_1);
  AdaptiveSimpson test;
  test.setFunction(f);
  std::vector<double> lower_bounds = {0.0, 0.0, 0.0};
  std::vector<double> upper_bounds = {1.0, 2.0, 3.0};
  test.setInterval(lower_bounds, upper_bounds);
  auto result = test.integrate();
  BOOST_CHECK_CLOSE(result[0], 6.0, 1.0e-3);
  BOOST_CHECK_CLOSE(result[1], 12.0, 1.0e-3);
  BOOST_CHECK_CLOSE(result[2], 18.0, 1.0e-3);
}

class SphericalHarmonics
{
public:
  SphericalHarmonics(unsigned n1, unsigned n2)
  {
    m_n1 = n1;
    m_n2 = n2;
  };
  std::vector<double> getPoint(std::deque<double> &angles)
  {
    double theta = angles[0];
    double phi = angles[1];
    double tmp1 = boost::math::spherical_harmonic_r(m_n1, 0, theta, phi);
    double tmp2 = boost::math::spherical_harmonic_r(m_n2, 0, theta, phi);
    return std::vector<double>(1, tmp1 * tmp2 * sin(theta));
  };

private:
  unsigned m_n1, m_n2;
};

BOOST_AUTO_TEST_CASE(SphericalHarmonicsTest)
{
  for (unsigned n1 = 0; n1 < 4; ++n1)
  {
    for (unsigned n2 = 0; n2 < 4; ++n2)
    {
      SphericalHarmonics myClass(n1, n2);
      std::function<std::vector<double>(std::deque<double> & x)> f =
          std::bind<std::vector<double>>(&SphericalHarmonics::getPoint, &myClass, std::placeholders::_1);
      AdaptiveSimpson test;
      test.setFunction(f);
      std::vector<double> lower_bounds = {0.0, 0.0};
      std::vector<double> upper_bounds = {M_PI, 2.0 * M_PI};
      test.setInterval(lower_bounds, upper_bounds);
      auto result = test.integrate();

      if (n1 == n2)
      {
        BOOST_CHECK_CLOSE(result[0], 1.0, 1.0e-3);
      }
      else
      {
        BOOST_CHECK_SMALL(result[0], 1.0e-3);
      }
    }
  }
}

/* Simple product function */
// double f0 (unsigned dim, const double *x, void *params)
std::vector<double> productFunction(std::deque<double> &x)
{
  std::vector<double> prod(1, 1.0);
  unsigned int i;
  for (i = 0; i < x.size(); ++i)
    prod[0] *= 2.0 * x[i];
  return prod;
}

/* Gaussian centered at 1/2. */
std::vector<double> gaussianFunction(std::deque<double> &x)
{
  std::size_t dim = x.size();
  double a = 0.1;
  double sum = 0.0;
  for (unsigned int i = 0; i < dim; i++)
  {
    double dx = x[i] - 0.5;
    sum += dx * dx;
  }
  std::vector<double> result(1);
  result[0] = std::pow(M_2_SQRTPI / (2.0 * a), dim) * exp(-sum / (a * a));
  return result;
}

//also test move assignment operator.
BOOST_AUTO_TEST_CASE(GaussianFunctionTest)
{
  std::function<std::vector<double>(std::deque<double> & x)> f =
      std::bind<std::vector<double>>(gaussianFunction, std::placeholders::_1);
  AdaptiveSimpson test,moveTest;
  test.setFunction(f);
  std::vector<double> lower_bounds = {0.0, 0.0};
  std::vector<double> upper_bounds = {1.0, 1.0};
  test.setInterval(lower_bounds, upper_bounds);
  auto result = test.integrate();
  BOOST_CHECK_CLOSE(result[0], 1.0, 1.0e-3);
  moveTest = std::move(test);
  result = moveTest.integrate();
  BOOST_CHECK_CLOSE(result[0], 1.0, 1.0e-3);
}

/* double gaussian */
std::vector<double> doubleGaussianFunction(std::deque<double> &x)
{
  std::size_t dim = x.size();
  double a = 0.1;
  double sum1 = 0.0;
  double sum2 = 0.0;
  for (unsigned int i = 0; i < dim; i++)
  {
    double dx1 = x[i] - 1.0 / 3.0;
    double dx2 = x[i] - 2.0 / 3.0;
    sum1 += dx1 * dx1;
    sum2 += dx2 * dx2;
  }
  std::vector<double> result(1);
  result[0] = 0.5 * std::pow(M_2_SQRTPI / (2.0 * a), dim) * (std::exp(-sum1 / (a * a)) + std::exp(-sum2 / (a * a)));
  return result;
}

// also tests move constructor
BOOST_AUTO_TEST_CASE(DoubleGaussianFunctionTest)
{
  std::function<std::vector<double>(std::deque<double> & x)> f =
      std::bind<std::vector<double>>(doubleGaussianFunction, std::placeholders::_1);
  AdaptiveSimpson test;
  test.setFunction(f);
  std::vector<double> lower_bounds = {0.0, 0.0};
  std::vector<double> upper_bounds = {1.0, 1.0};
  test.setInterval(lower_bounds, upper_bounds);
  auto result1 = test.integrate();
  BOOST_CHECK_CLOSE(result1[0], 1.0, 1.0e-3);
  AdaptiveSimpson moveTest(std::move(test));
  auto result2 = moveTest.integrate();
  BOOST_CHECK_CLOSE(result2[0], 1.0, 1.0e-3);
}

/* Tsuda's example */
std::vector<double> tsudasFunction(std::deque<double> &x)
{
  std::size_t dim = x.size();
  double c = (1.0 + sqrt(10.0)) / 9.0;
  std::vector<double> result(1, 1.0);
  unsigned int i;
  for (i = 0; i < dim; i++)
    result[0] *= c / (c + 1) * pow((c + 1) / (c + x[i]), 2.0);
  return result;
}

// also tests copy constructor
BOOST_AUTO_TEST_CASE(TsudasFunctionTest)
{
  std::function<std::vector<double>(std::deque<double> & x)> f =
      std::bind<std::vector<double>>(tsudasFunction, std::placeholders::_1);
  AdaptiveSimpson test;
  test.setFunction(f);
  std::vector<double> lower_bounds = {0.0, 0.0};
  std::vector<double> upper_bounds = {1.0, 1.0};
  test.setInterval(lower_bounds, upper_bounds);
  auto result1 = test.integrate();
  BOOST_CHECK_CLOSE(result1[0], 1.0, 1.0e-3);
  AdaptiveSimpson copyTest(test);
  auto result2 = copyTest.integrate();
  BOOST_CHECK_CLOSE(result2[0], 1.0, 1.0e-3);
}

std::vector<double> complexFunction(std::deque<double> &x)
{
  std::size_t dim = x.size();
  double p = 1.0 / dim;
  double prod = pow(1 + p, dim);
  unsigned int i;
  for (i = 0; i < dim; i++)
    prod *= pow(x[i], p);
  return std::vector<double>(1, prod);
};

// also tests copy assignment operator
BOOST_AUTO_TEST_CASE(ComplexFunctionTest)
{
  std::function<std::vector<double>(std::deque<double> & x)> f =
      std::bind<std::vector<double>>(complexFunction, std::placeholders::_1);
  AdaptiveSimpson test,copyTest;
  test.setFunction(f);
  std::vector<double> lower_bounds = {0.0, 0.0};
  std::vector<double> upper_bounds = {1.0, 1.0};
  test.setInterval(lower_bounds, upper_bounds);
  auto result1 = test.integrate();
  BOOST_CHECK_CLOSE(result1[0], 1.0, 1.0e-3);
  copyTest = test;
  auto result2 = copyTest.integrate();
  BOOST_CHECK_CLOSE(result2[0], 1.0, 1.0e-3);
}
<|endoftext|>


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

#include <gtest/gtest.h>

#include <cstring>

#include <string>

#include "rosidl_generator_cpp/msg/defaults.hpp"
#include "rosidl_generator_cpp/msg/bounded_sequences.hpp"

template<typename Callable>
struct ScopeExit
{
  explicit ScopeExit(Callable callable)
  : callable_(callable) {}
  ~ScopeExit() {callable_();}

private:
  Callable callable_;
};

template<typename Callable>
ScopeExit<Callable>
make_scope_exit(Callable callable)
{
  return ScopeExit<Callable>(callable);
}

#define DO_STRING_JOIN(arg1, arg2) arg1 ## arg2
#define STRING_JOIN(arg1, arg2) DO_STRING_JOIN(arg1, arg2)
#define SCOPE_EXIT(code) \
  auto STRING_JOIN(scope_exit_, __LINE__) = make_scope_exit([&]() {code;})

TEST(Test_msg_initialization, no_arg_constructor) {
  rosidl_generator_cpp::msg::Defaults def;
  ASSERT_TRUE(def.bool_value);
  ASSERT_EQ(50, def.byte_value);
  ASSERT_EQ(100, def.char_value);
  ASSERT_EQ(1.125f, def.float32_value);
  ASSERT_EQ(1.125, def.float64_value);
  ASSERT_EQ(-50, def.int8_value);
  ASSERT_EQ(200, def.uint8_value);
  ASSERT_EQ(-1000, def.int16_value);
  ASSERT_EQ(2000, def.uint16_value);
  ASSERT_EQ(-30000L, def.int32_value);
  ASSERT_EQ(60000UL, def.uint32_value);
  ASSERT_EQ(-40000000LL, def.int64_value);
  ASSERT_EQ(50000000ULL, def.uint64_value);

  rosidl_generator_cpp::msg::BasicTypes basic;
  ASSERT_FALSE(basic.bool_value);
  ASSERT_EQ(0, basic.byte_value);
  ASSERT_EQ(0, basic.char_value);
  ASSERT_EQ(0.0f, basic.float32_value);
  ASSERT_EQ(0.0, basic.float64_value);
  ASSERT_EQ(0, basic.int8_value);
  ASSERT_EQ(0, basic.uint8_value);
  ASSERT_EQ(0, basic.int16_value);
  ASSERT_EQ(0, basic.uint16_value);
  ASSERT_EQ(0L, basic.int32_value);
  ASSERT_EQ(0UL, basic.uint32_value);
  ASSERT_EQ(0LL, basic.int64_value);
}

TEST(Test_msg_initialization, all_constructor) {
  rosidl_generator_cpp::msg::Defaults def(
    rosidl_runtime_cpp::MessageInitialization::ALL);
  ASSERT_TRUE(def.bool_value);
  ASSERT_EQ(50, def.byte_value);
  ASSERT_EQ(100, def.char_value);
  ASSERT_EQ(1.125f, def.float32_value);
  ASSERT_EQ(1.125, def.float64_value);
  ASSERT_EQ(-50, def.int8_value);
  ASSERT_EQ(200, def.uint8_value);
  ASSERT_EQ(-1000, def.int16_value);
  ASSERT_EQ(2000, def.uint16_value);
  ASSERT_EQ(-30000L, def.int32_value);
  ASSERT_EQ(60000UL, def.uint32_value);
  ASSERT_EQ(-40000000LL, def.int64_value);
  ASSERT_EQ(50000000ULL, def.uint64_value);

  rosidl_generator_cpp::msg::BasicTypes basic;
  ASSERT_FALSE(basic.bool_value);
  ASSERT_EQ(0, basic.byte_value);
  ASSERT_EQ(0, basic.char_value);
  ASSERT_EQ(0.0f, basic.float32_value);
  ASSERT_EQ(0.0, basic.float64_value);
  ASSERT_EQ(0, basic.int8_value);
  ASSERT_EQ(0, basic.uint8_value);
  ASSERT_EQ(0, basic.int16_value);
  ASSERT_EQ(0, basic.uint16_value);
  ASSERT_EQ(0L, basic.int32_value);
  ASSERT_EQ(0UL, basic.uint32_value);
  ASSERT_EQ(0LL, basic.int64_value);
}

TEST(Test_msg_initialization, zero_constructor) {
  rosidl_generator_cpp::msg::Defaults def(
    rosidl_runtime_cpp::MessageInitialization::ZERO);
  ASSERT_FALSE(def.bool_value);
  ASSERT_EQ(0, def.byte_value);
  ASSERT_EQ(0, def.char_value);
  ASSERT_EQ(0.0f, def.float32_value);
  ASSERT_EQ(0.0, def.float64_value);
  ASSERT_EQ(0, def.int8_value);
  ASSERT_EQ(0, def.uint8_value);
  ASSERT_EQ(0, def.int16_value);
  ASSERT_EQ(0, def.uint16_value);
  ASSERT_EQ(0L, def.int32_value);
  ASSERT_EQ(0UL, def.uint32_value);
  ASSERT_EQ(0LL, def.int64_value);
  ASSERT_EQ(0ULL, def.uint64_value);

  rosidl_generator_cpp::msg::BasicTypes basic;
  ASSERT_FALSE(basic.bool_value);
  ASSERT_EQ(0, basic.byte_value);
  ASSERT_EQ(0, basic.char_value);
  ASSERT_EQ(0.0f, basic.float32_value);
  ASSERT_EQ(0.0, basic.float64_value);
  ASSERT_EQ(0, basic.int8_value);
  ASSERT_EQ(0, basic.uint8_value);
  ASSERT_EQ(0, basic.int16_value);
  ASSERT_EQ(0, basic.uint16_value);
  ASSERT_EQ(0L, basic.int32_value);
  ASSERT_EQ(0UL, basic.uint32_value);
  ASSERT_EQ(0LL, basic.int64_value);
}

TEST(Test_msg_initialization, defaults_only_constructor) {
  rosidl_generator_cpp::msg::Defaults def(
    rosidl_runtime_cpp::MessageInitialization::DEFAULTS_ONLY);
  ASSERT_TRUE(def.bool_value);
  ASSERT_EQ(50, def.byte_value);
  ASSERT_EQ(100, def.char_value);
  ASSERT_EQ(1.125f, def.float32_value);
  ASSERT_EQ(1.125, def.float64_value);
  ASSERT_EQ(-50, def.int8_value);
  ASSERT_EQ(200, def.uint8_value);
  ASSERT_EQ(-1000, def.int16_value);
  ASSERT_EQ(2000, def.uint16_value);
  ASSERT_EQ(-30000L, def.int32_value);
  ASSERT_EQ(60000UL, def.uint32_value);
  ASSERT_EQ(-40000000LL, def.int64_value);
  ASSERT_EQ(50000000ULL, def.uint64_value);

  rosidl_generator_cpp::msg::BasicTypes basic;
  ASSERT_FALSE(basic.bool_value);
  ASSERT_EQ(0, basic.byte_value);
  ASSERT_EQ(0, basic.char_value);
  ASSERT_EQ(0.0f, basic.float32_value);
  ASSERT_EQ(0.0, basic.float64_value);
  ASSERT_EQ(0, basic.int8_value);
  ASSERT_EQ(0, basic.uint8_value);
  ASSERT_EQ(0, basic.int16_value);
  ASSERT_EQ(0, basic.uint16_value);
  ASSERT_EQ(0L, basic.int32_value);
  ASSERT_EQ(0UL, basic.uint32_value);
  ASSERT_EQ(0LL, basic.int64_value);
}

// This is a test to ensure that when the user passes SKIP to the constructor,
// it does no initialization.
TEST(Test_msg_initialization, skip_constructor) {
  char * memory = new char[sizeof(rosidl_generator_cpp::msg::BoundedSequences)];
  ASSERT_NE(memory, nullptr);
  std::memset(memory, 0xfe, sizeof(rosidl_generator_cpp::msg::BoundedSequences));
  rosidl_generator_cpp::msg::BoundedSequences * bounded =
    new(memory) rosidl_generator_cpp::msg::BoundedSequences(
    rosidl_runtime_cpp::MessageInitialization::SKIP);

  // ensures that the memory gets freed even if an ASSERT is raised
  SCOPE_EXIT(bounded->~BoundedSequences_(); delete[] memory);

  #ifndef _WIN32
  #  pragma GCC diagnostic push
  #  pragma GCC diagnostic ignored "-Wstrict-aliasing"
  #endif
  ASSERT_TRUE(
    std::all_of(
      bounded->float32_values_default.begin(),
      bounded->float32_values_default.end(), [](float i) {
        uint32_t float32_bit_pattern = *reinterpret_cast<uint32_t *>(&i);
        return 0xfefefefe == float32_bit_pattern;
      }));
  ASSERT_TRUE(
    std::all_of(
      bounded->float64_values_default.begin(),
      bounded->float64_values_default.end(), [](double i) {
        uint64_t float64_bit_pattern = *reinterpret_cast<uint64_t *>(&i);
        return 0xfefefefefefefefe == float64_bit_pattern;
      }));

  #ifndef _WIN32
  #  pragma GCC diagnostic pop
  #endif
  ASSERT_EQ(0UL, bounded->float64_values_default.size());
  ASSERT_EQ(0UL, bounded->float32_values_default.size());
  ASSERT_EQ(0UL, bounded->float32_values.size());
  ASSERT_TRUE(
    std::all_of(
      bounded->string_values_default.begin(),
      bounded->string_values_default.end(), [](std::string i) {
        return "" == i;
      }));
}
<commit_msg>Use ASSERT_TRUE to check for nullptr. (#543)<commit_after>// Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <gtest/gtest.h>

#include <cstring>

#include <string>

#include "rosidl_generator_cpp/msg/defaults.hpp"
#include "rosidl_generator_cpp/msg/bounded_sequences.hpp"

template<typename Callable>
struct ScopeExit
{
  explicit ScopeExit(Callable callable)
  : callable_(callable) {}
  ~ScopeExit() {callable_();}

private:
  Callable callable_;
};

template<typename Callable>
ScopeExit<Callable>
make_scope_exit(Callable callable)
{
  return ScopeExit<Callable>(callable);
}

#define DO_STRING_JOIN(arg1, arg2) arg1 ## arg2
#define STRING_JOIN(arg1, arg2) DO_STRING_JOIN(arg1, arg2)
#define SCOPE_EXIT(code) \
  auto STRING_JOIN(scope_exit_, __LINE__) = make_scope_exit([&]() {code;})

TEST(Test_msg_initialization, no_arg_constructor) {
  rosidl_generator_cpp::msg::Defaults def;
  ASSERT_TRUE(def.bool_value);
  ASSERT_EQ(50, def.byte_value);
  ASSERT_EQ(100, def.char_value);
  ASSERT_EQ(1.125f, def.float32_value);
  ASSERT_EQ(1.125, def.float64_value);
  ASSERT_EQ(-50, def.int8_value);
  ASSERT_EQ(200, def.uint8_value);
  ASSERT_EQ(-1000, def.int16_value);
  ASSERT_EQ(2000, def.uint16_value);
  ASSERT_EQ(-30000L, def.int32_value);
  ASSERT_EQ(60000UL, def.uint32_value);
  ASSERT_EQ(-40000000LL, def.int64_value);
  ASSERT_EQ(50000000ULL, def.uint64_value);

  rosidl_generator_cpp::msg::BasicTypes basic;
  ASSERT_FALSE(basic.bool_value);
  ASSERT_EQ(0, basic.byte_value);
  ASSERT_EQ(0, basic.char_value);
  ASSERT_EQ(0.0f, basic.float32_value);
  ASSERT_EQ(0.0, basic.float64_value);
  ASSERT_EQ(0, basic.int8_value);
  ASSERT_EQ(0, basic.uint8_value);
  ASSERT_EQ(0, basic.int16_value);
  ASSERT_EQ(0, basic.uint16_value);
  ASSERT_EQ(0L, basic.int32_value);
  ASSERT_EQ(0UL, basic.uint32_value);
  ASSERT_EQ(0LL, basic.int64_value);
}

TEST(Test_msg_initialization, all_constructor) {
  rosidl_generator_cpp::msg::Defaults def(
    rosidl_runtime_cpp::MessageInitialization::ALL);
  ASSERT_TRUE(def.bool_value);
  ASSERT_EQ(50, def.byte_value);
  ASSERT_EQ(100, def.char_value);
  ASSERT_EQ(1.125f, def.float32_value);
  ASSERT_EQ(1.125, def.float64_value);
  ASSERT_EQ(-50, def.int8_value);
  ASSERT_EQ(200, def.uint8_value);
  ASSERT_EQ(-1000, def.int16_value);
  ASSERT_EQ(2000, def.uint16_value);
  ASSERT_EQ(-30000L, def.int32_value);
  ASSERT_EQ(60000UL, def.uint32_value);
  ASSERT_EQ(-40000000LL, def.int64_value);
  ASSERT_EQ(50000000ULL, def.uint64_value);

  rosidl_generator_cpp::msg::BasicTypes basic;
  ASSERT_FALSE(basic.bool_value);
  ASSERT_EQ(0, basic.byte_value);
  ASSERT_EQ(0, basic.char_value);
  ASSERT_EQ(0.0f, basic.float32_value);
  ASSERT_EQ(0.0, basic.float64_value);
  ASSERT_EQ(0, basic.int8_value);
  ASSERT_EQ(0, basic.uint8_value);
  ASSERT_EQ(0, basic.int16_value);
  ASSERT_EQ(0, basic.uint16_value);
  ASSERT_EQ(0L, basic.int32_value);
  ASSERT_EQ(0UL, basic.uint32_value);
  ASSERT_EQ(0LL, basic.int64_value);
}

TEST(Test_msg_initialization, zero_constructor) {
  rosidl_generator_cpp::msg::Defaults def(
    rosidl_runtime_cpp::MessageInitialization::ZERO);
  ASSERT_FALSE(def.bool_value);
  ASSERT_EQ(0, def.byte_value);
  ASSERT_EQ(0, def.char_value);
  ASSERT_EQ(0.0f, def.float32_value);
  ASSERT_EQ(0.0, def.float64_value);
  ASSERT_EQ(0, def.int8_value);
  ASSERT_EQ(0, def.uint8_value);
  ASSERT_EQ(0, def.int16_value);
  ASSERT_EQ(0, def.uint16_value);
  ASSERT_EQ(0L, def.int32_value);
  ASSERT_EQ(0UL, def.uint32_value);
  ASSERT_EQ(0LL, def.int64_value);
  ASSERT_EQ(0ULL, def.uint64_value);

  rosidl_generator_cpp::msg::BasicTypes basic;
  ASSERT_FALSE(basic.bool_value);
  ASSERT_EQ(0, basic.byte_value);
  ASSERT_EQ(0, basic.char_value);
  ASSERT_EQ(0.0f, basic.float32_value);
  ASSERT_EQ(0.0, basic.float64_value);
  ASSERT_EQ(0, basic.int8_value);
  ASSERT_EQ(0, basic.uint8_value);
  ASSERT_EQ(0, basic.int16_value);
  ASSERT_EQ(0, basic.uint16_value);
  ASSERT_EQ(0L, basic.int32_value);
  ASSERT_EQ(0UL, basic.uint32_value);
  ASSERT_EQ(0LL, basic.int64_value);
}

TEST(Test_msg_initialization, defaults_only_constructor) {
  rosidl_generator_cpp::msg::Defaults def(
    rosidl_runtime_cpp::MessageInitialization::DEFAULTS_ONLY);
  ASSERT_TRUE(def.bool_value);
  ASSERT_EQ(50, def.byte_value);
  ASSERT_EQ(100, def.char_value);
  ASSERT_EQ(1.125f, def.float32_value);
  ASSERT_EQ(1.125, def.float64_value);
  ASSERT_EQ(-50, def.int8_value);
  ASSERT_EQ(200, def.uint8_value);
  ASSERT_EQ(-1000, def.int16_value);
  ASSERT_EQ(2000, def.uint16_value);
  ASSERT_EQ(-30000L, def.int32_value);
  ASSERT_EQ(60000UL, def.uint32_value);
  ASSERT_EQ(-40000000LL, def.int64_value);
  ASSERT_EQ(50000000ULL, def.uint64_value);

  rosidl_generator_cpp::msg::BasicTypes basic;
  ASSERT_FALSE(basic.bool_value);
  ASSERT_EQ(0, basic.byte_value);
  ASSERT_EQ(0, basic.char_value);
  ASSERT_EQ(0.0f, basic.float32_value);
  ASSERT_EQ(0.0, basic.float64_value);
  ASSERT_EQ(0, basic.int8_value);
  ASSERT_EQ(0, basic.uint8_value);
  ASSERT_EQ(0, basic.int16_value);
  ASSERT_EQ(0, basic.uint16_value);
  ASSERT_EQ(0L, basic.int32_value);
  ASSERT_EQ(0UL, basic.uint32_value);
  ASSERT_EQ(0LL, basic.int64_value);
}

// This is a test to ensure that when the user passes SKIP to the constructor,
// it does no initialization.
TEST(Test_msg_initialization, skip_constructor) {
  char * memory = new char[sizeof(rosidl_generator_cpp::msg::BoundedSequences)];
  ASSERT_TRUE(nullptr != memory);
  std::memset(memory, 0xfe, sizeof(rosidl_generator_cpp::msg::BoundedSequences));
  rosidl_generator_cpp::msg::BoundedSequences * bounded =
    new(memory) rosidl_generator_cpp::msg::BoundedSequences(
    rosidl_runtime_cpp::MessageInitialization::SKIP);

  // ensures that the memory gets freed even if an ASSERT is raised
  SCOPE_EXIT(bounded->~BoundedSequences_(); delete[] memory);

  #ifndef _WIN32
  #  pragma GCC diagnostic push
  #  pragma GCC diagnostic ignored "-Wstrict-aliasing"
  #endif
  ASSERT_TRUE(
    std::all_of(
      bounded->float32_values_default.begin(),
      bounded->float32_values_default.end(), [](float i) {
        uint32_t float32_bit_pattern = *reinterpret_cast<uint32_t *>(&i);
        return 0xfefefefe == float32_bit_pattern;
      }));
  ASSERT_TRUE(
    std::all_of(
      bounded->float64_values_default.begin(),
      bounded->float64_values_default.end(), [](double i) {
        uint64_t float64_bit_pattern = *reinterpret_cast<uint64_t *>(&i);
        return 0xfefefefefefefefe == float64_bit_pattern;
      }));

  #ifndef _WIN32
  #  pragma GCC diagnostic pop
  #endif
  ASSERT_EQ(0UL, bounded->float64_values_default.size());
  ASSERT_EQ(0UL, bounded->float32_values_default.size());
  ASSERT_EQ(0UL, bounded->float32_values.size());
  ASSERT_TRUE(
    std::all_of(
      bounded->string_values_default.begin(),
      bounded->string_values_default.end(), [](std::string i) {
        return "" == i;
      }));
}
<|endoftext|>


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

#include "ti_chrome_window.h"
#include "ti_user_window.h"
#include "ti_utils.h"
#include "ti_menu.h"
#include "ti_app_arguments.h"
#include "Resource.h"

#include <fstream>
#include <shellapi.h>

TCHAR TiChromeWindow::defaultWindowTitle[128];
TCHAR TiChromeWindow::windowClassName[128];
TiAppConfig* TiChromeWindow::tiAppConfig = NULL;
std::vector<TiChromeWindow*> TiChromeWindow::openWindows = std::vector<TiChromeWindow*>();
bool TiChromeWindow::isInspectorOpen = false;

/*static*/
TiChromeWindow* TiChromeWindow::fromWindow(HWND hWnd) {
  return reinterpret_cast<TiChromeWindow*>(win_util::GetWindowUserData(hWnd));
}

/*static*/
TiChromeWindow* TiChromeWindow::getMainWindow() {
	TiChromeWindow *main = getWindow("main");
	if (main == NULL) {
		if (openWindows.size() > 0) {
			main = openWindows[0];
		}
	}

	return main;
}

/*static*/
TiChromeWindow* TiChromeWindow::getWindow(const char *id)
{
	for (size_t i = 0; i < openWindows.size(); i++) {
		if (openWindows[i]->getTiWindowConfig()->getId() == id) {
			return openWindows[i];
		}
	}
	return NULL;
}

/*static*/
void TiChromeWindow::initWindowClass (HINSTANCE hInstance)
{
	static bool initialized = false;
	if (! initialized) {
		LoadString(hInstance, IDS_APP_TITLE, defaultWindowTitle, 128);
		LoadString(hInstance, IDC_CHROME_SHELL3, windowClassName, 128);
		WNDCLASSEX wcex;

		wcex.cbSize = sizeof(WNDCLASSEX);

		wcex.style			= CS_HREDRAW | CS_VREDRAW;
		wcex.lpfnWndProc	= TiChromeWindow::WndProc;
		wcex.cbClsExtra		= 0;
		wcex.cbWndExtra		= 0;
		wcex.hInstance		= hInstance;
		wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CHROME_SHELL3));
		wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
		wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
		wcex.lpszMenuName	= 0;
		wcex.lpszClassName	= windowClassName;
		wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

		RegisterClassEx(&wcex);

		initialized = true;
	}
}

/*static*/
void TiChromeWindow::removeWindowClass (HINSTANCE hInstance)
{
	UnregisterClass(windowClassName, hInstance);
}

void TiChromeWindow::openInspectorWindow()
{
	isInspectorOpen = true;
	host->webview()->ShowJavaScriptConsole();
}

/*static*/
LRESULT CALLBACK TiChromeWindow::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
	int wmId, wmEvent;

	TiChromeWindow *window = TiChromeWindow::fromWindow(hWnd);

	switch (message)
	{
		case WM_COMMAND:
			wmId    = LOWORD(wParam);
			wmEvent = HIWORD(wParam);
			// Parse the menu selections:
			switch (wmId)
			{
				case IDM_ABOUT:
					//DialogBox(tiWebShell->getInstance(), MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
					break;
				case IDM_EXIT:
					DestroyWindow(hWnd);
					break;
				default:
				{
					LRESULT handled = TiMenu::handleMenuClick(hWnd, message, wParam, lParam);

					if(! handled)
					{
						return DefWindowProc(hWnd, message, wParam, lParam);
					}
				}
			}
			break;

		case WM_PAINT:
			window->getHost()->Paint();
			break;

		// forward some things onto the webview host
		case WM_MOUSEMOVE:
		case WM_MOUSELEAVE:
		case WM_LBUTTONDOWN:
		case WM_MBUTTONDOWN:
		case WM_RBUTTONDOWN:
		case WM_LBUTTONUP:
		case WM_MBUTTONUP:
		case WM_RBUTTONUP:
		case WM_LBUTTONDBLCLK:
		case WM_MBUTTONDBLCLK:
		case WM_RBUTTONDBLCLK:
		case WM_CAPTURECHANGED:
		case WM_CANCELMODE:
		case WM_KEYDOWN:
		case WM_KEYUP:
		case WM_SYSKEYDOWN:
		case WM_SYSKEYUP:
		case WM_IME_CHAR:
		case WM_SETFOCUS:
		case WM_KILLFOCUS:
		//case WM_MOUSEWHEEL:
			if (!PostMessage(window->getHost()->window_handle(), message, wParam, lParam)) {
				return DefWindowProc(hWnd, message, wParam, lParam);
			} else return 0;
		case WM_DESTROY:
			if (window == TiChromeWindow::getMainWindow()) {

			}
			return 0;
		case WM_SIZE:
			if (window != NULL)
				window->resizeHost();
			return 0;

		case TI_TRAY_CLICKED:
			{
				UINT uMouseMsg = (UINT) lParam;
				if(uMouseMsg == WM_LBUTTONDOWN)
				{
					// handle the click callback for the tray
				}
				else if (uMouseMsg == WM_RBUTTONDOWN)
				{
					TiMenu::showTrayMenu();
				}
			}
			break;
	}

	return DefWindowProc(hWnd, message, wParam, lParam);
}

TiChromeWindow::TiChromeWindow(HINSTANCE hInstance_, TiWindowConfig *windowConfig) : hWnd(NULL), hInstance(hInstance_), host(NULL)
{
	TiChromeWindow::openWindows.push_back(this);
	this->tiWindowConfig = windowConfig;

	if (windowConfig != NULL) {
		this->url = tiWindowConfig->getURL();
	}

	tiUserWindow = new TiUserWindow(this);
	createWindow();
}

TiChromeWindow::TiChromeWindow(HINSTANCE hInstance_, const char *url) : hWnd(NULL), hInstance(hInstance_), host(NULL)
{
	TiChromeWindow::openWindows.push_back(this);
	this->url = url;
	this->tiWindowConfig = new TiWindowConfig();

	tiUserWindow = new TiUserWindow(this);
	createWindow();
}

TiChromeWindow::~TiChromeWindow(void) {
	// TODO  remove tray icon if one exists .. mmm..
	//this->removeTrayIcon();
}

void TiChromeWindow::createWindow()
{
	hWnd = CreateWindowEx(WS_EX_LAYERED, windowClassName, defaultWindowTitle,
                           WS_CLIPCHILDREN,
                           0, 0, 0, 0,
                           NULL, NULL, hInstance, NULL);

	win_util::SetWindowUserData(hWnd, this);

	static WebPreferences webPrefs = ti_initWebPrefs();
	webViewDelegate = new TiWebViewDelegate(this);
	host = WebViewHost::Create(hWnd, webViewDelegate, webPrefs);
	webViewDelegate->setWebViewHost(host);

	reloadTiWindowConfig();
}

WebWidget* TiChromeWindow::createPopupWidget()
{
	popupHost = WebWidgetHost::Create(NULL, webViewDelegate);
	ShowWindow(getPopupWindowHandle(), SW_SHOW);

	return popupHost->webwidget();
}

void TiChromeWindow::closePopup()
{
	PostMessage(getPopupWindowHandle(), WM_CLOSE, 0, 0);
	getHost()->Paint();

	popupHost = NULL;
}

#define SetFlag(x,flag,b) ((b) ? x |= flag : x &= ~flag)
#define UnsetFlag(x,flag) (x &= ~flag)=

void TiChromeWindow::setTiWindowConfig(TiWindowConfig *tiWindowConfig)
{
	this->tiWindowConfig = tiWindowConfig;
	reloadTiWindowConfig();
}

void TiChromeWindow::reloadTiWindowConfig()
{

	SetWindowText(hWnd, UTF8ToWide(tiWindowConfig->getTitle()).c_str());

	long windowStyle = GetWindowLong(hWnd, GWL_STYLE);

	SetFlag(windowStyle, WS_MINIMIZEBOX, tiWindowConfig->isMinimizable());
	SetFlag(windowStyle, WS_MAXIMIZEBOX, tiWindowConfig->isMaximizable());

	SetFlag(windowStyle, WS_OVERLAPPEDWINDOW, !tiWindowConfig->isUsingChrome() && tiWindowConfig->isResizable());
	SetFlag(windowStyle, WS_CAPTION, !tiWindowConfig->isUsingChrome());

	SetWindowLong(hWnd, GWL_STYLE, windowStyle);

	UINT flags = SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED;

	sizeTo(tiWindowConfig->getX(), tiWindowConfig->getY(), tiWindowConfig->getWidth(), tiWindowConfig->getHeight(), flags);
	SetLayeredWindowAttributes(hWnd, 0, (BYTE)floor(tiWindowConfig->getTransparency()*255), LWA_ALPHA);
}

void TiChromeWindow::open() {
	if (hWnd == NULL) {
		createWindow();
	}

	if (tiWindowConfig->getURL().length() > 0) {
		maybeLoadURL(tiWindowConfig->getURL().c_str());
	}

	ShowWindow(hWnd, SW_SHOW);
	ShowWindow(host->window_handle(), SW_SHOW);
}

void TiChromeWindow::maybeLoadURL(const char* url) {
	if (currentURL != url) {
		currentURL = url;

		WebRequest *request = WebRequest::Create(GURL(url));
		WebFrame *frame = host->webview()->GetMainFrame();
		frame->LoadRequest(request);

		host->webview()->SetFocusedFrame(frame);

		SetFocus(host->window_handle());
		ShowWindow(host->window_handle(), SW_SHOW);
	}
}

void TiChromeWindow::sizeTo(int x, int y, int width, int height, UINT flags) {
	RECT rc, rw;
	GetClientRect(hWnd, &rc);
	GetWindowRect(hWnd, &rw);

	int client_width = rc.right - rc.left;
	int window_width = rw.right - rw.left;
	window_width = (window_width - client_width) + width;

	int client_height = rc.bottom - rc.top;
	int window_height = rw.bottom - rw.top;
	window_height = (window_height - client_height) + height;

	SetWindowPos(hWnd, NULL, x, y, window_width, window_height, flags);
}

void TiChromeWindow::resizeHost() {
	RECT rc;
	GetClientRect(hWnd, &rc);

	MoveWindow(host->window_handle(), 0, 0, rc.right, rc.bottom, TRUE);
}

void TiChromeWindow::include(WebFrame *frame, std::string& relativePath)
{
	std::string absolutePath;

	if (relativePath.find_first_of("://") != std::string::npos) {
		absolutePath = WideToUTF8(TiURL::getPathForURL(GURL(relativePath)));
	}
	else {
		absolutePath = WideToUTF8(tiAppConfig->getResourcePath());
		absolutePath += "\\";
		absolutePath += relativePath;
	}
	std::ifstream in(absolutePath.c_str());
	std::string s, line;
	while(getline(in, line)) {
		s += line + "\n";
	}

	frame->ExecuteJavaScript(s, absolutePath);
}

void TiChromeWindow::showWindow(int nCmdShow) {
	ShowWindow(hWnd, nCmdShow);
}

std::string TiChromeWindow::getTitle() {
	wchar_t buffer[2049];
	GetWindowText(this->hWnd, buffer, 2048);

	std::string result;
	result.assign(WideToUTF8(buffer));

	return result;
}

void TiChromeWindow::setTitle(std::string title) {
	SetWindowText(this->hWnd, UTF8ToWide(title).c_str());
}

void TiChromeWindow::close() {
	CloseWindow(hWnd);
}

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

#include "ti_chrome_window.h"
#include "ti_user_window.h"
#include "ti_utils.h"
#include "ti_menu.h"
#include "ti_app_arguments.h"
#include "Resource.h"

#include <fstream>
#include <shellapi.h>

TCHAR TiChromeWindow::defaultWindowTitle[128];
TCHAR TiChromeWindow::windowClassName[128];
TiAppConfig* TiChromeWindow::tiAppConfig = NULL;
std::vector<TiChromeWindow*> TiChromeWindow::openWindows = std::vector<TiChromeWindow*>();
bool TiChromeWindow::isInspectorOpen = false;

/*static*/
TiChromeWindow* TiChromeWindow::fromWindow(HWND hWnd) {
  return reinterpret_cast<TiChromeWindow*>(win_util::GetWindowUserData(hWnd));
}

/*static*/
TiChromeWindow* TiChromeWindow::getMainWindow() {
	TiChromeWindow *main = getWindow("main");
	if (main == NULL) {
		if (openWindows.size() > 0) {
			main = openWindows[0];
		}
	}

	return main;
}

/*static*/
TiChromeWindow* TiChromeWindow::getWindow(const char *id)
{
	for (size_t i = 0; i < openWindows.size(); i++) {
		if (openWindows[i]->getTiWindowConfig()->getId() == id) {
			return openWindows[i];
		}
	}
	return NULL;
}

/*static*/
void TiChromeWindow::initWindowClass (HINSTANCE hInstance)
{
	static bool initialized = false;
	if (! initialized) {
		LoadString(hInstance, IDS_APP_TITLE, defaultWindowTitle, 128);
		LoadString(hInstance, IDC_CHROME_SHELL3, windowClassName, 128);
		WNDCLASSEX wcex;

		wcex.cbSize = sizeof(WNDCLASSEX);

		wcex.style			= CS_HREDRAW | CS_VREDRAW;
		wcex.lpfnWndProc	= TiChromeWindow::WndProc;
		wcex.cbClsExtra		= 0;
		wcex.cbWndExtra		= 0;
		wcex.hInstance		= hInstance;
		wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CHROME_SHELL3));
		wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
		wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
		wcex.lpszMenuName	= 0;
		wcex.lpszClassName	= windowClassName;
		wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

		RegisterClassEx(&wcex);

		initialized = true;
	}
}

/*static*/
void TiChromeWindow::removeWindowClass (HINSTANCE hInstance)
{
	UnregisterClass(windowClassName, hInstance);
}

void TiChromeWindow::openInspectorWindow()
{
	isInspectorOpen = true;
	host->webview()->ShowJavaScriptConsole();
}

/*static*/
LRESULT CALLBACK TiChromeWindow::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
	int wmId, wmEvent;

	TiChromeWindow *window = TiChromeWindow::fromWindow(hWnd);

	switch (message)
	{
		case WM_COMMAND:
			wmId    = LOWORD(wParam);
			wmEvent = HIWORD(wParam);
			// Parse the menu selections:
			switch (wmId)
			{
				case IDM_ABOUT:
					//DialogBox(tiWebShell->getInstance(), MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
					break;
				case IDM_EXIT:
					DestroyWindow(hWnd);
					break;
				default:
				{
					LRESULT handled = TiMenu::handleMenuClick(hWnd, message, wParam, lParam);

					if(! handled)
					{
						return DefWindowProc(hWnd, message, wParam, lParam);
					}
				}
			}
			break;

		case WM_PAINT:
			window->getHost()->Paint();
			break;

		// forward some things onto the webview host
		case WM_MOUSEMOVE:
		case WM_MOUSELEAVE:
		case WM_LBUTTONDOWN:
		case WM_MBUTTONDOWN:
		case WM_RBUTTONDOWN:
		case WM_LBUTTONUP:
		case WM_MBUTTONUP:
		case WM_RBUTTONUP:
		case WM_LBUTTONDBLCLK:
		case WM_MBUTTONDBLCLK:
		case WM_RBUTTONDBLCLK:
		case WM_CAPTURECHANGED:
		case WM_CANCELMODE:
		case WM_KEYDOWN:
		case WM_KEYUP:
		case WM_SYSKEYDOWN:
		case WM_SYSKEYUP:
		case WM_IME_CHAR:
		case WM_SETFOCUS:
		case WM_KILLFOCUS:
		//case WM_MOUSEWHEEL:
			if (!PostMessage(window->getHost()->window_handle(), message, wParam, lParam)) {
				return DefWindowProc(hWnd, message, wParam, lParam);
			} else return 0;
		case WM_DESTROY:
			if (window == TiChromeWindow::getMainWindow()) {
				PostQuitMessage(0);
			}
			return 0;
		case WM_SIZE:
			if (window != NULL)
				window->resizeHost();
			return 0;

		case TI_TRAY_CLICKED:
			{
				UINT uMouseMsg = (UINT) lParam;
				if(uMouseMsg == WM_LBUTTONDOWN)
				{
					// handle the click callback for the tray
				}
				else if (uMouseMsg == WM_RBUTTONDOWN)
				{
					TiMenu::showTrayMenu();
				}
			}
			break;
	}

	return DefWindowProc(hWnd, message, wParam, lParam);
}

TiChromeWindow::TiChromeWindow(HINSTANCE hInstance_, TiWindowConfig *windowConfig) : hWnd(NULL), hInstance(hInstance_), host(NULL)
{
	TiChromeWindow::openWindows.push_back(this);
	this->tiWindowConfig = windowConfig;

	if (windowConfig != NULL) {
		this->url = tiWindowConfig->getURL();
	}

	tiUserWindow = new TiUserWindow(this);
	createWindow();
}

TiChromeWindow::TiChromeWindow(HINSTANCE hInstance_, const char *url) : hWnd(NULL), hInstance(hInstance_), host(NULL)
{
	TiChromeWindow::openWindows.push_back(this);
	this->url = url;
	this->tiWindowConfig = new TiWindowConfig();

	tiUserWindow = new TiUserWindow(this);
	createWindow();
}

TiChromeWindow::~TiChromeWindow(void) {
	// TODO  remove tray icon if one exists .. mmm..
	//this->removeTrayIcon();
}

void TiChromeWindow::createWindow()
{
	hWnd = CreateWindowEx(WS_EX_LAYERED, windowClassName, defaultWindowTitle,
                           WS_CLIPCHILDREN,
                           0, 0, 0, 0,
                           NULL, NULL, hInstance, NULL);

	win_util::SetWindowUserData(hWnd, this);

	static WebPreferences webPrefs = ti_initWebPrefs();
	webViewDelegate = new TiWebViewDelegate(this);
	host = WebViewHost::Create(hWnd, webViewDelegate, webPrefs);
	webViewDelegate->setWebViewHost(host);

	reloadTiWindowConfig();
}

WebWidget* TiChromeWindow::createPopupWidget()
{
	popupHost = WebWidgetHost::Create(NULL, webViewDelegate);
	ShowWindow(getPopupWindowHandle(), SW_SHOW);

	return popupHost->webwidget();
}

void TiChromeWindow::closePopup()
{
	PostMessage(getPopupWindowHandle(), WM_CLOSE, 0, 0);
	getHost()->Paint();

	popupHost = NULL;
}

#define SetFlag(x,flag,b) ((b) ? x |= flag : x &= ~flag)
#define UnsetFlag(x,flag) (x &= ~flag)=

void TiChromeWindow::setTiWindowConfig(TiWindowConfig *tiWindowConfig)
{
	this->tiWindowConfig = tiWindowConfig;
	reloadTiWindowConfig();
}

void TiChromeWindow::reloadTiWindowConfig()
{

	SetWindowText(hWnd, UTF8ToWide(tiWindowConfig->getTitle()).c_str());

	long windowStyle = GetWindowLong(hWnd, GWL_STYLE);

	SetFlag(windowStyle, WS_MINIMIZEBOX, tiWindowConfig->isMinimizable());
	SetFlag(windowStyle, WS_MAXIMIZEBOX, tiWindowConfig->isMaximizable());

	SetFlag(windowStyle, WS_OVERLAPPEDWINDOW, !tiWindowConfig->isUsingChrome() && tiWindowConfig->isResizable());
	SetFlag(windowStyle, WS_CAPTION, !tiWindowConfig->isUsingChrome());

	SetWindowLong(hWnd, GWL_STYLE, windowStyle);

	UINT flags = SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED;

	sizeTo(tiWindowConfig->getX(), tiWindowConfig->getY(), tiWindowConfig->getWidth(), tiWindowConfig->getHeight(), flags);
	SetLayeredWindowAttributes(hWnd, 0, (BYTE)floor(tiWindowConfig->getTransparency()*255), LWA_ALPHA);
}

void TiChromeWindow::open() {
	if (hWnd == NULL) {
		createWindow();
	}

	if (tiWindowConfig->getURL().length() > 0) {
		maybeLoadURL(tiWindowConfig->getURL().c_str());
	}

	ShowWindow(hWnd, SW_SHOW);
	ShowWindow(host->window_handle(), SW_SHOW);
}

void TiChromeWindow::maybeLoadURL(const char* url) {
	if (currentURL != url) {
		currentURL = url;

		WebRequest *request = WebRequest::Create(GURL(url));
		WebFrame *frame = host->webview()->GetMainFrame();
		frame->LoadRequest(request);

		host->webview()->SetFocusedFrame(frame);

		SetFocus(host->window_handle());
		ShowWindow(host->window_handle(), SW_SHOW);
	}
}

void TiChromeWindow::sizeTo(int x, int y, int width, int height, UINT flags) {
	RECT rc, rw;
	GetClientRect(hWnd, &rc);
	GetWindowRect(hWnd, &rw);

	int client_width = rc.right - rc.left;
	int window_width = rw.right - rw.left;
	window_width = (window_width - client_width) + width;

	int client_height = rc.bottom - rc.top;
	int window_height = rw.bottom - rw.top;
	window_height = (window_height - client_height) + height;

	SetWindowPos(hWnd, NULL, x, y, window_width, window_height, flags);
}

void TiChromeWindow::resizeHost() {
	RECT rc;
	GetClientRect(hWnd, &rc);

	MoveWindow(host->window_handle(), 0, 0, rc.right, rc.bottom, TRUE);
}

void TiChromeWindow::include(WebFrame *frame, std::string& relativePath)
{
	std::string absolutePath;

	if (relativePath.find_first_of("://") != std::string::npos) {
		absolutePath = WideToUTF8(TiURL::getPathForURL(GURL(relativePath)));
	}
	else {
		absolutePath = WideToUTF8(tiAppConfig->getResourcePath());
		absolutePath += "\\";
		absolutePath += relativePath;
	}
	std::ifstream in(absolutePath.c_str());
	std::string s, line;
	while(getline(in, line)) {
		s += line + "\n";
	}

	frame->ExecuteJavaScript(s, absolutePath);
}

void TiChromeWindow::showWindow(int nCmdShow) {
	ShowWindow(hWnd, nCmdShow);
}

std::string TiChromeWindow::getTitle() {
	wchar_t buffer[2049];
	GetWindowText(this->hWnd, buffer, 2048);

	std::string result;
	result.assign(WideToUTF8(buffer));

	return result;
}

void TiChromeWindow::setTitle(std::string title) {
	SetWindowText(this->hWnd, UTF8ToWide(title).c_str());
}

void TiChromeWindow::close() {
	CloseWindow(hWnd);
}

<|endoftext|>


<commit_before>// Base header file.  Must be first.
#include <Include/PlatformDefinitions.hpp>

#include <cassert>

#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream.h>
#else
#include <iostream>
#endif

#include <xercesc/dom/impl/DOMDocumentImpl.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>

#include <XalanDOM/XalanDocument.hpp>
#include <XalanDOM/XalanElement.hpp>

#include <PlatformSupport/XalanOutputStreamPrintWriter.hpp>
#include <PlatformSupport/XalanStdOutputStream.hpp>

#include <XMLSupport/FormatterToXML.hpp>

#include <XercesParserLiaison/FormatterToXercesDOM.hpp>
#include <XercesParserLiaison/XercesDOMFormatterWalker.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

XALAN_USING_STD(cerr)
XALAN_USING_STD(cout)
XALAN_USING_STD(endl)

XALAN_USING_XERCES(DOMDocument)

XALAN_USING_XALAN(XalanCompiledStylesheet)
XALAN_USING_XALAN(XalanParsedSource)
XALAN_USING_XALAN(XalanTransformer)

void
serialize(const DOMDocument&	theDocument)
{
	XALAN_USING_XALAN(XalanStdOutputStream)
	XALAN_USING_XALAN(XalanOutputStreamPrintWriter)
	XALAN_USING_XALAN(FormatterToXML)
	XALAN_USING_XALAN(XercesDOMFormatterWalker)

	// OK, we're going to serialize the nodes that were
	// found.  We should really check to make sure the
	// root (document) has not been selected, since we
	// really can't serialize a node list with the root.
	XalanStdOutputStream			theStream(cout);
	XalanOutputStreamPrintWriter	thePrintWriter(theStream);

	FormatterToXML	theFormatter(thePrintWriter);

	XercesDOMFormatterWalker	theWalker(theFormatter);

	theWalker.traverse(&theDocument);
}

int
transformAndSerialize(
			XalanTransformer&				theTransformer,
			const XalanParsedSource&		theParsedSource,
			const XalanCompiledStylesheet&	theStylesheet)
{
	XALAN_USING_XERCES(DOMDocumentImpl)
	XALAN_USING_XALAN(FormatterToXercesDOM)

	DOMDocumentImpl			theDocument;

	FormatterToXercesDOM	theFormatter(&theDocument, 0);

	int		theResult =
		theTransformer.transform(
			theParsedSource,
			&theStylesheet,
			theFormatter);

	if (theResult != 0)
	{
		cerr << "Error transforming: "
			 << theTransformer.getLastError()
			 << endl;
	}
	else
	{
		serialize(theDocument);
	}

	return theResult;
}

int
main(
			int				argc,
			const char*		argv[])
{
	int		theResult = 0;

	if (argc != 3)
	{
		cerr << "Usage: TransformToXercesDOM XMLFilePath XSLFilePath" << endl;

		theResult = -1;
	}
	else
	{
		try
		{
			XALAN_USING_XERCES(XMLPlatformUtils)

			XMLPlatformUtils::Initialize();

			XalanTransformer::initialize();

			{

				XalanTransformer	theTransformer;

				XalanParsedSource*	theParsedSource = 0;

				theResult = theTransformer.parseSource(argv[1], theParsedSource);

				if (theResult != 0)
				{
					cerr << "Error parsing source document: "
						 << theTransformer.getLastError()
						 << endl;
				}
				else
				{
					assert(theParsedSource != 0);

					XalanCompiledStylesheet*	theCompiledStylesheet = 0;

					theResult = theTransformer.compileStylesheet(argv[2], theCompiledStylesheet);

					if (theResult != 0)
					{
						cerr << "Error compiling stylesheet: "
							 << theTransformer.getLastError()
							 << endl;
					}
					else
					{
						theResult =
							transformAndSerialize(theTransformer, *theParsedSource, *theCompiledStylesheet);
					}
				}
			}

			XalanTransformer::terminate();

			XMLPlatformUtils::Terminate();
		}
		catch(...)
		{
			cerr << "Exception caught!" << endl;

			theResult = -1;
		}
	}

	return theResult;
}
<commit_msg>Added const qualifiers.<commit_after>// Base header file.  Must be first.
#include <Include/PlatformDefinitions.hpp>

#include <cassert>

#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <iostream.h>
#else
#include <iostream>
#endif

#include <xercesc/dom/impl/DOMDocumentImpl.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>

#include <XalanDOM/XalanDocument.hpp>
#include <XalanDOM/XalanElement.hpp>

#include <PlatformSupport/XalanOutputStreamPrintWriter.hpp>
#include <PlatformSupport/XalanStdOutputStream.hpp>

#include <XMLSupport/FormatterToXML.hpp>

#include <XercesParserLiaison/FormatterToXercesDOM.hpp>
#include <XercesParserLiaison/XercesDOMFormatterWalker.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

XALAN_USING_STD(cerr)
XALAN_USING_STD(cout)
XALAN_USING_STD(endl)

XALAN_USING_XERCES(DOMDocument)

XALAN_USING_XALAN(XalanCompiledStylesheet)
XALAN_USING_XALAN(XalanParsedSource)
XALAN_USING_XALAN(XalanTransformer)

void
serialize(const DOMDocument&	theDocument)
{
	XALAN_USING_XALAN(XalanStdOutputStream)
	XALAN_USING_XALAN(XalanOutputStreamPrintWriter)
	XALAN_USING_XALAN(FormatterToXML)
	XALAN_USING_XALAN(XercesDOMFormatterWalker)

	// OK, we're going to serialize the nodes that were
	// found.  We should really check to make sure the
	// root (document) has not been selected, since we
	// really can't serialize a node list with the root.
	XalanStdOutputStream			theStream(cout);
	XalanOutputStreamPrintWriter	thePrintWriter(theStream);

	FormatterToXML	theFormatter(thePrintWriter);

	XercesDOMFormatterWalker	theWalker(theFormatter);

	theWalker.traverse(&theDocument);
}

int
transformAndSerialize(
			XalanTransformer&				theTransformer,
			const XalanParsedSource&		theParsedSource,
			const XalanCompiledStylesheet&	theStylesheet)
{
	XALAN_USING_XERCES(DOMDocumentImpl)
	XALAN_USING_XALAN(FormatterToXercesDOM)

	DOMDocumentImpl			theDocument;

	FormatterToXercesDOM	theFormatter(&theDocument, 0);

	int		theResult =
		theTransformer.transform(
			theParsedSource,
			&theStylesheet,
			theFormatter);

	if (theResult != 0)
	{
		cerr << "Error transforming: "
			 << theTransformer.getLastError()
			 << endl;
	}
	else
	{
		serialize(theDocument);
	}

	return theResult;
}

int
main(
			int				argc,
			const char*		argv[])
{
	int		theResult = 0;

	if (argc != 3)
	{
		cerr << "Usage: TransformToXercesDOM XMLFilePath XSLFilePath" << endl;

		theResult = -1;
	}
	else
	{
		try
		{
			XALAN_USING_XERCES(XMLPlatformUtils)

			XMLPlatformUtils::Initialize();

			XalanTransformer::initialize();

			{

				XalanTransformer	theTransformer;

				const XalanParsedSource*	theParsedSource = 0;

				theResult = theTransformer.parseSource(argv[1], theParsedSource);

				if (theResult != 0)
				{
					cerr << "Error parsing source document: "
						 << theTransformer.getLastError()
						 << endl;
				}
				else
				{
					assert(theParsedSource != 0);

					const XalanCompiledStylesheet*	theCompiledStylesheet = 0;

					theResult = theTransformer.compileStylesheet(argv[2], theCompiledStylesheet);

					if (theResult != 0)
					{
						cerr << "Error compiling stylesheet: "
							 << theTransformer.getLastError()
							 << endl;
					}
					else
					{
						theResult =
							transformAndSerialize(theTransformer, *theParsedSource, *theCompiledStylesheet);
					}
				}
			}

			XalanTransformer::terminate();

			XMLPlatformUtils::Terminate();
		}
		catch(...)
		{
			cerr << "Exception caught!" << endl;

			theResult = -1;
		}
	}

	return theResult;
}
<|endoftext|>


<commit_before>/* win32/handle.hpp
 *
 * Copyright (C) 2007 Antonio Di Monaco
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#pragma once
#ifndef __HANDLE_HPP__
#define __HANDLE_HPP__

#include <windows.h>

#include "win32/error.hpp"

namespace Windows
{
  inline BOOL _stdcall nullCloseHandle(HANDLE) { return TRUE; }

  template< typename T = HANDLE, typename R = BOOL >
  class Handle
  {
    Handle(const Handle &o);
    Handle &operator=(const Handle &o);

    T _h;
    Error _lastError;
    R (_stdcall *_closeF)(T);

    void setLastError()
    {
      _lastError = ((_h == NULL) || (_h == INVALID_HANDLE_VALUE))? Error() : Error(ERROR_SUCCESS);
    }

  protected:
    void setHandle(T h)
    {
      _h = h;
      setLastError();
    }

    explicit Handle(T h = NULL,
                    R (_stdcall *closeF)(T) = CloseHandle) :
      _h(h),
      _closeF(closeF)
    {
      setLastError();
    }

  public:
    Handle(Handle &&o) :
      _h(o._h),
      _lastError(o._lastError)
      _closeF(o._closeF)
    {
      o._h = NULL;
      o._lastError = ERROR_SUCCESS;
    }
    ~Handle()
    {
      if (_h != NULL)
      {
        _closeF(_h);
        _h = NULL;
      }
    }

    T handle() const
    {
      return _h;
    }

    Error lastError() const
    {
      return _lastError;
    }

    Handle &operator=(Handle &&o)
    {
      _h = o._h;
      _lastError = o._lastError;
      _closeF = o._closeF;
      o._h = NULL;
      o._lastError = ERROR_SUCCESS;

      return *this;
    }
  };
}

#endif
<commit_msg>Fixing GCC build errors<commit_after>/* win32/handle.hpp
 *
 * Copyright (C) 2007 Antonio Di Monaco
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

#pragma once
#ifndef __HANDLE_HPP__
#define __HANDLE_HPP__

#include <windows.h>

#include "win32/error.hpp"

namespace Windows
{
  inline BOOL __stdcall nullCloseHandle(HANDLE) { return TRUE; }

  template< typename T = HANDLE, typename R = BOOL >
  class Handle
  {
    Handle(const Handle &o);
    Handle &operator=(const Handle &o);

    T _h;
    Error _lastError;
    R ((__stdcall *_closeF))(T);

    void setLastError()
    {
      _lastError = ((_h == NULL) || (_h == INVALID_HANDLE_VALUE))? Error() : Error(ERROR_SUCCESS);
    }

  protected:
    void setHandle(T h)
    {
      _h = h;
      setLastError();
    }

    explicit Handle(T h = NULL,
                    R ((__stdcall *closeF))(T) = CloseHandle) :
      _h(h),
      _closeF(closeF)
    {
      setLastError();
    }

  public:
    Handle(Handle &&o) :
      _h(o._h),
      _lastError(o._lastError)
      _closeF(o._closeF)
    {
      o._h = NULL;
      o._lastError = ERROR_SUCCESS;
    }
    ~Handle()
    {
      if (_h != NULL)
      {
        _closeF(_h);
        _h = NULL;
      }
    }

    T handle() const
    {
      return _h;
    }

    Error lastError() const
    {
      return _lastError;
    }

    Handle &operator=(Handle &&o)
    {
      _h = o._h;
      _lastError = o._lastError;
      _closeF = o._closeF;
      o._h = NULL;
      o._lastError = ERROR_SUCCESS;

      return *this;
    }
  };
}

#endif
<|endoftext|>


<commit_before>#include <iostream>

#include <Windows.h>
#include <tchar.h>
#include <Shlwapi.h>
#include <TlHelp32.h>

typedef HINSTANCE(*fpLoadLibrary)(char*);

int _tmain(int argc, _TCHAR* argv[])
{
	if (argc != 3)
	{
		return 1;
	}

	_TCHAR* library = argv[1];
	_TCHAR* process = argv[2];

	if (PathIsRelative(library)) {
		DWORD length = GetCurrentDirectory(0, NULL);
		library = new _TCHAR[length + _tcslen(argv[1])];
		GetCurrentDirectory(length, library);
		PathAppend(library, argv[1]);
	}

	PROCESSENTRY32 entry;
	entry.dwSize = sizeof(PROCESSENTRY32);

	HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

	DWORD pid = NULL;

	if (!Process32First(snapshot, &entry))
	{
		return 1;
	}

	do
	{
		if (_tcscmp(entry.szExeFile, process))
		{
			pid = entry.th32ProcessID;
			break;
		}
	} while (Process32Next(snapshot, &entry));

	CloseHandle(snapshot);

	HANDLE hProcess;

	HINSTANCE hDll = LoadLibraryA("KERNEL32");

	fpLoadLibrary LoadLibraryAddr = (fpLoadLibrary)GetProcAddress(hDll, "LoadLibraryA");

	hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);

	LPVOID paramAddr = VirtualAllocEx(hProcess, 0, _tcslen(library) + 1, MEM_COMMIT, PAGE_READWRITE);
	BOOL memoryWritten = WriteProcessMemory(hProcess, paramAddr, library, _tcslen(library) + 1, NULL);

	CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryAddr, paramAddr, 0, 0);

	CloseHandle(hProcess);
	delete[] library;
	return 0;
}
<commit_msg>Fixed multi-byte charset support<commit_after>#include <iostream>

#include <Windows.h>
#include <tchar.h>
#include <Shlwapi.h>
#include <TlHelp32.h>

typedef HINSTANCE(*fpLoadLibrary)(char*);

int _tmain(int argc, _TCHAR* argv[])
{
	if (argc != 3)
	{
		return 1;
	}

	_TCHAR* library = argv[1];
	_TCHAR* process = argv[2];

	if (PathIsRelative(library)) {
		DWORD length = GetCurrentDirectory(0, NULL);
		library = new _TCHAR[length + _tcslen(argv[1])];
		GetCurrentDirectory(length, library);
		PathAppend(library, argv[1]);
	}

	PROCESSENTRY32 entry;
	entry.dwSize = sizeof(PROCESSENTRY32);

	HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

	DWORD pid = NULL;

	if (!Process32First(snapshot, &entry))
	{
		return 1;
	}

	do
	{
		if (_tcscmp(entry.szExeFile, process))
		{
			pid = entry.th32ProcessID;
			break;
		}
	} while (Process32Next(snapshot, &entry));

	CloseHandle(snapshot);

	HANDLE hProcess;

	HINSTANCE hDll = LoadLibrary("KERNEL32");

	fpLoadLibrary LoadLibraryAddr = (fpLoadLibrary)GetProcAddress(hDll, "LoadLibraryA");

	hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);

	LPVOID paramAddr = VirtualAllocEx(hProcess, 0, _tcslen(library) + 1, MEM_COMMIT, PAGE_READWRITE);
	BOOL memoryWritten = WriteProcessMemory(hProcess, paramAddr, library, _tcslen(library) + 1, NULL);

	CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryAddr, paramAddr, 0, 0);

	CloseHandle(hProcess);
	delete[] library;
	return 0;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include <string.h>
#include <cstdlib>

#include "sqlite-kvstore.hh"
#include "sqlite-pst.hh"

void StrategicSqlite3::set(const Item &itm, Callback<bool> &cb) {
    PreparedStatement *ins_stmt = strategy->forKey(itm.getKey())->ins();
    ins_stmt->bind(1, itm.getKey().c_str());
    ins_stmt->bind(2, const_cast<Item&>(itm).getData(), itm.getNBytes());
    ins_stmt->bind(3, itm.getFlags());
    ins_stmt->bind(4, itm.getExptime());
    ins_stmt->bind64(5, itm.getCas());
    bool rv = ins_stmt->execute() == 1;
    cb.callback(rv);
    ins_stmt->reset();
}

// XXX:  This needs to die.  It's incorrect and not the way forward.
void StrategicSqlite3::get(const std::string &key, Callback<GetValue> &cb) {
    PreparedStatement *sel_stmt = strategy->forKey(key)->sel();
    sel_stmt->bind(1, key.c_str());

    if(sel_stmt->fetch()) {
        std::string str(sel_stmt->column(0));
        GetValue rv(new Item(key,
                             sel_stmt->column_int(1),
                             sel_stmt->column_int(2),
                             str));
        cb.callback(rv);
    } else {
        GetValue rv(false);
        cb.callback(rv);
    }
    sel_stmt->reset();
}

void StrategicSqlite3::del(const std::string &key, Callback<bool> &cb) {
    PreparedStatement *del_stmt = strategy->forKey(key)->del();
    del_stmt->bind(1, key.c_str());
    bool rv = del_stmt->execute() >= 0;
    cb.callback(rv);
    del_stmt->reset();
}

void StrategicSqlite3::dump(Callback<GetValue> &cb) {

    const std::vector<Statements*> statements = strategy->allStatements();
    std::vector<Statements*>::const_iterator it;
    for (it = statements.begin(); it != statements.end(); ++it) {
        PreparedStatement *st = (*it)->all();
        st->reset();
        while (st->fetch()) {
            std::string key(st->column(0));
            std::string value(st->column(1));
            GetValue rv(new Item(key,
                                 st->column_int(2),
                                 st->column_int(3),
                                 value,
                                 st->column_int64(4)));
            cb.callback(rv);
        }

        st->reset();
    }
}
<commit_msg>Use column_blob for pulling keys and values.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include <string.h>
#include <cstdlib>

#include "sqlite-kvstore.hh"
#include "sqlite-pst.hh"

void StrategicSqlite3::set(const Item &itm, Callback<bool> &cb) {
    PreparedStatement *ins_stmt = strategy->forKey(itm.getKey())->ins();
    ins_stmt->bind(1, itm.getKey().c_str());
    ins_stmt->bind(2, const_cast<Item&>(itm).getData(), itm.getNBytes());
    ins_stmt->bind(3, itm.getFlags());
    ins_stmt->bind(4, itm.getExptime());
    ins_stmt->bind64(5, itm.getCas());
    bool rv = ins_stmt->execute() == 1;
    cb.callback(rv);
    ins_stmt->reset();
}

// XXX:  This needs to die.  It's incorrect and not the way forward.
void StrategicSqlite3::get(const std::string &key, Callback<GetValue> &cb) {
    PreparedStatement *sel_stmt = strategy->forKey(key)->sel();
    sel_stmt->bind(1, key.c_str());

    if(sel_stmt->fetch()) {
        std::string str(sel_stmt->column(0));
        GetValue rv(new Item(key,
                             sel_stmt->column_int(1),
                             sel_stmt->column_int(2),
                             str));
        cb.callback(rv);
    } else {
        GetValue rv(false);
        cb.callback(rv);
    }
    sel_stmt->reset();
}

void StrategicSqlite3::del(const std::string &key, Callback<bool> &cb) {
    PreparedStatement *del_stmt = strategy->forKey(key)->del();
    del_stmt->bind(1, key.c_str());
    bool rv = del_stmt->execute() >= 0;
    cb.callback(rv);
    del_stmt->reset();
}

void StrategicSqlite3::dump(Callback<GetValue> &cb) {

    const std::vector<Statements*> statements = strategy->allStatements();
    std::vector<Statements*>::const_iterator it;
    for (it = statements.begin(); it != statements.end(); ++it) {
        PreparedStatement *st = (*it)->all();
        st->reset();
        while (st->fetch()) {
            GetValue rv(new Item(st->column_blob(0),
                                 st->column_bytes(0),
                                 st->column_int(2),
                                 st->column_int(3),
                                 st->column_blob(1),
                                 st->column_bytes(1)));
            cb.callback(rv);
        }

        st->reset();
    }
}
<|endoftext|>


<commit_before>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

#include "CQMoietiesTaskResult.h"

#include "copasi.h"

#include "resourcesUI/CQIconResource.h"
#include "CQPushButtonDelegate.h"
#include "CopasiFileDialog.h"
#include "CQMessageBox.h"
#include "qtUtilities.h"

#include "function/CExpression.h"
#include "model/CModel.h"
#include "moieties/CMoietiesTask.h"
#include "report/CKeyFactory.h"
#include "utilities/utility.h"
#include "report/CCopasiRootContainer.h"
#include "commandline/CLocaleString.h"

#define COL_SPECIES  0
#define COL_NUMBER   1
#define COL_AMOUNT   2
#define COL_BTN      3
#define COL_EQUATION 4

/*
 *  Constructs a CQMoietiesTaskResult which is a child of 'parent', with the
 *  name 'name'.'
 */
CQMoietiesTaskResult::CQMoietiesTaskResult(QWidget* parent, const char* name)
  : CopasiWidget(parent, name)
{
  setupUi(this);

  init();
}

/*
 *  Destroys the object and frees any allocated resources
 */
CQMoietiesTaskResult::~CQMoietiesTaskResult()
{
  // no need to delete child widgets, Qt does it all for us
}

void CQMoietiesTaskResult::init()
{
  mpMoietiesTask = NULL;

  QImage ToolBtn;

  // Initialize the moieties tab
  mpMoieties->setColumnCount(5);

  QTableWidgetItem * pItem = new QTableWidgetItem("Dependent Species");
  mpMoieties->setHorizontalHeaderItem(COL_SPECIES, pItem);
  pItem = new QTableWidgetItem("Total Particle Number");
  mpMoieties->setHorizontalHeaderItem(COL_NUMBER, pItem);
  pItem = new QTableWidgetItem("Total Amount");
  mpMoieties->setHorizontalHeaderItem(COL_AMOUNT, pItem);
  pItem = new QTableWidgetItem("");
  mpMoieties->setHorizontalHeaderItem(COL_BTN, pItem);
  pItem = new QTableWidgetItem("Expression");
  mpMoieties->setHorizontalHeaderItem(COL_EQUATION, pItem);

  CQPushButtonDelegate * pDelegate = new CQPushButtonDelegate(CQIconResource::icon(CQIconResource::tool), "",  CQPushButtonDelegate::ToolButton, this);
  mpMoieties->setItemDelegateForColumn(COL_BTN, pDelegate);

  connect(pDelegate, SIGNAL(clicked(const QModelIndex &)), this, SLOT(slotCreateGlobalQuantity(const QModelIndex &)));

  // Initialize the stoichiometry tab
  mpStoichiometry->setLegendEnabled(true);

  // Initialize the stoichiometry tab
  mpLinkMatrix->setLegendEnabled(true);

  // Initialize the stoichiometry tab
  mpReducedStoichiometry->setLegendEnabled(true);
}

bool CQMoietiesTaskResult::update(ListViews::ObjectType objectType,
                                  ListViews::Action action,
                                  const std::string & /* key */)
{
  // :TODO:
  switch (objectType)
    {
      case ListViews::MODEL:

        switch (action)
          {
            case ListViews::ADD:
              clear();
              break;

            case ListViews::CHANGE:
              break;

            default:
              break;
          }

        break;

      default:
        break;
    }

  return true;
}

void CQMoietiesTaskResult::clear()
{
  mpMoieties->setRowCount(0);
  mpStoichiometry->setArrayAnnotation(NULL);
  mpLinkMatrix->setArrayAnnotation(NULL);
  mpReducedStoichiometry->setArrayAnnotation(NULL);
}

bool CQMoietiesTaskResult::leave()
{return true;}

bool CQMoietiesTaskResult::enterProtected()
{
  mpMoietiesTask = dynamic_cast< CMoietiesTask * >(mpObject);

  load();

  return true;
}

void CQMoietiesTaskResult::load()
{
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = &CCopasiRootContainer::getDatamodelList()->operator[](0);
  assert(pDataModel != NULL);
  CModel * pModel = pDataModel->getModel();

  if (pModel == NULL) return;

  // Set the units for the amount column
  QString AmountUnits = FROM_UTF8(pModel->getQuantityUnitsDisplayString());

  if (!AmountUnits.isEmpty())
    AmountUnits = "\n(" + AmountUnits + ")";

  mpMoieties->horizontalHeaderItem(COL_AMOUNT)->setText("Total Amount" + AmountUnits);

  // Fill the moieties table
  int i = 0;

  if (pModel->getMoieties().size() > 0)
    {
      CCopasiVector< CMoiety >::const_iterator it = pModel->getMoieties().begin();
      CCopasiVector< CMoiety >::const_iterator end = pModel->getMoieties().end();
      mpMoieties->setRowCount(end - it);

      QTableWidgetItem * pItem;

      for (; it != end; ++it, i++)
        {
          pItem = new QTableWidgetItem(FROM_UTF8(it->getObjectName()));
          mpMoieties->setItem(i, COL_SPECIES, pItem);;

          pItem = new QTableWidgetItem(QVariant::Double);
          pItem->setData(Qt::DisplayRole, it->getNumber());
          mpMoieties->setItem(i, COL_NUMBER, pItem);

          it.constCast()->refreshAmount();
          pItem = new QTableWidgetItem(QVariant::Double);
          pItem->setData(Qt::DisplayRole, it->getAmount());
          mpMoieties->setItem(i, COL_AMOUNT, pItem);

          pItem = new QTableWidgetItem("");
          mpMoieties->setItem(i, COL_BTN, pItem);

          // Show the Button
          pItem = mpMoieties->item(i, COL_BTN);
          pItem->setFlags(pItem->flags() | Qt::ItemIsEditable | Qt::ItemIsEnabled);
          mpMoieties->openPersistentEditor(pItem);

          pItem = new QTableWidgetItem(FROM_UTF8(it->getDescription(pModel)));
          mpMoieties->setItem(i, COL_EQUATION, pItem);
        }
    }

  mpTabWidget->setTabText(mpTabWidget->indexOf(mpMoieties), "Moieties (" + QString::number(i) + ")");

  mpMoieties->resizeColumnsToContents();
  mpMoieties->resizeRowsToContents();

  // Fill the stoichiometry matrix
  CColorScaleBiLog * tcs = NULL;
  const CArrayAnnotation * pAnnotation =
    static_cast< const CArrayAnnotation * >(pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)")));
  tcs = new CColorScaleBiLog();
  mpStoichiometry->setColorCoding(tcs);
  mpStoichiometry->setColorScalingAutomatic(true);
  mpStoichiometry->setArrayAnnotation(pAnnotation);

  // Fill the link matrix
  pAnnotation =
    static_cast< const CArrayAnnotation * >(pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)")));
  tcs = new CColorScaleBiLog();
  mpLinkMatrix->setColorCoding(tcs);
  mpLinkMatrix->setColorScalingAutomatic(true);
  mpLinkMatrix->setArrayAnnotation(pAnnotation);

  // Fill the reduced stoichiometry matrix
  pAnnotation =
    static_cast< const CArrayAnnotation * >(pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)")));
  tcs = new CColorScaleBiLog();
  mpReducedStoichiometry->setColorCoding(tcs);
  mpReducedStoichiometry->setColorScalingAutomatic(true);
  mpReducedStoichiometry->setArrayAnnotation(pAnnotation);

  return;
}

void CQMoietiesTaskResult::slotSave(void)
{
  C_INT32 Answer = QMessageBox::No;
  QString fileName;

  while (Answer == QMessageBox::No)
    {
      fileName =
        CopasiFileDialog::getSaveFileName(this, "Save File Dialog",
                                          "untitled.txt", "TEXT Files (*.txt)", "Save to");

      if (fileName.isEmpty()) return;

      // Checks whether the file exists
      Answer = checkSelection(fileName);

      if (Answer == QMessageBox::Cancel) return;
    }

  std::ofstream file(CLocaleString::fromUtf8(TO_UTF8(fileName)).c_str());

  if (file.fail())
    return;

  if (mpMoietiesTask != NULL)
    file << mpMoietiesTask->getResult();

  return;
}

void CQMoietiesTaskResult::slotCreateGlobalQuantity(const QModelIndex & index)
{
  int row = index.row();

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CModel * pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel();

  if (pModel == NULL) return;

  const CCopasiVector< CMoiety > & Moieties = pModel->getMoieties();

  if (row >= (C_INT32) Moieties.size()) return;

  const CMoiety * pMoiety = &Moieties[row];

  CModelValue * pMV = pModel->createModelValue("Moiety[" + pMoiety->getObjectName() + "].TotalAmount");

  int i = 0;

  while (pMV == NULL)
    pMV = pModel->createModelValue("Moiety[" + pMoiety->getObjectName() + "].TotalAmount_" + TO_UTF8(QString::number(++i)));

  pMV->setInitialExpression(pMoiety->getExpression());
  protectedNotify(ListViews::MODELVALUE, ListViews::ADD);
}

// virtual
void CQMoietiesTaskResult::setFramework(int framework)
{
  CopasiWidget::setFramework(framework);

  switch (mFramework)
    {
      case 0: // Concentration
        mpMoieties->showColumn(COL_AMOUNT);
        mpMoieties->hideColumn(COL_NUMBER);
        break;

      case 1: // Particle Number
        mpMoieties->hideColumn(COL_AMOUNT);
        mpMoieties->showColumn(COL_NUMBER);
        break;
    }
}
<commit_msg>- need to set row count for moieties explicitly, as iterators might not be dereferencable<commit_after>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

#include "CQMoietiesTaskResult.h"

#include "copasi.h"

#include "resourcesUI/CQIconResource.h"
#include "CQPushButtonDelegate.h"
#include "CopasiFileDialog.h"
#include "CQMessageBox.h"
#include "qtUtilities.h"

#include "function/CExpression.h"
#include "model/CModel.h"
#include "moieties/CMoietiesTask.h"
#include "report/CKeyFactory.h"
#include "utilities/utility.h"
#include "report/CCopasiRootContainer.h"
#include "commandline/CLocaleString.h"

#define COL_SPECIES  0
#define COL_NUMBER   1
#define COL_AMOUNT   2
#define COL_BTN      3
#define COL_EQUATION 4

/*
 *  Constructs a CQMoietiesTaskResult which is a child of 'parent', with the
 *  name 'name'.'
 */
CQMoietiesTaskResult::CQMoietiesTaskResult(QWidget* parent, const char* name)
  : CopasiWidget(parent, name)
{
  setupUi(this);

  init();
}

/*
 *  Destroys the object and frees any allocated resources
 */
CQMoietiesTaskResult::~CQMoietiesTaskResult()
{
  // no need to delete child widgets, Qt does it all for us
}

void CQMoietiesTaskResult::init()
{
  mpMoietiesTask = NULL;

  QImage ToolBtn;

  // Initialize the moieties tab
  mpMoieties->setColumnCount(5);

  QTableWidgetItem * pItem = new QTableWidgetItem("Dependent Species");
  mpMoieties->setHorizontalHeaderItem(COL_SPECIES, pItem);
  pItem = new QTableWidgetItem("Total Particle Number");
  mpMoieties->setHorizontalHeaderItem(COL_NUMBER, pItem);
  pItem = new QTableWidgetItem("Total Amount");
  mpMoieties->setHorizontalHeaderItem(COL_AMOUNT, pItem);
  pItem = new QTableWidgetItem("");
  mpMoieties->setHorizontalHeaderItem(COL_BTN, pItem);
  pItem = new QTableWidgetItem("Expression");
  mpMoieties->setHorizontalHeaderItem(COL_EQUATION, pItem);

  CQPushButtonDelegate * pDelegate = new CQPushButtonDelegate(CQIconResource::icon(CQIconResource::tool), "",  CQPushButtonDelegate::ToolButton, this);
  mpMoieties->setItemDelegateForColumn(COL_BTN, pDelegate);

  connect(pDelegate, SIGNAL(clicked(const QModelIndex &)), this, SLOT(slotCreateGlobalQuantity(const QModelIndex &)));

  // Initialize the stoichiometry tab
  mpStoichiometry->setLegendEnabled(true);

  // Initialize the stoichiometry tab
  mpLinkMatrix->setLegendEnabled(true);

  // Initialize the stoichiometry tab
  mpReducedStoichiometry->setLegendEnabled(true);
}

bool CQMoietiesTaskResult::update(ListViews::ObjectType objectType,
                                  ListViews::Action action,
                                  const std::string & /* key */)
{
  // :TODO:
  switch (objectType)
    {
      case ListViews::MODEL:

        switch (action)
          {
            case ListViews::ADD:
              clear();
              break;

            case ListViews::CHANGE:
              break;

            default:
              break;
          }

        break;

      default:
        break;
    }

  return true;
}

void CQMoietiesTaskResult::clear()
{
  mpMoieties->setRowCount(0);
  mpStoichiometry->setArrayAnnotation(NULL);
  mpLinkMatrix->setArrayAnnotation(NULL);
  mpReducedStoichiometry->setArrayAnnotation(NULL);
}

bool CQMoietiesTaskResult::leave()
{return true;}

bool CQMoietiesTaskResult::enterProtected()
{
  mpMoietiesTask = dynamic_cast< CMoietiesTask * >(mpObject);

  load();

  return true;
}

void CQMoietiesTaskResult::load()
{
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = &CCopasiRootContainer::getDatamodelList()->operator[](0);
  assert(pDataModel != NULL);
  CModel * pModel = pDataModel->getModel();

  if (pModel == NULL) return;

  // Set the units for the amount column
  QString AmountUnits = FROM_UTF8(pModel->getQuantityUnitsDisplayString());

  if (!AmountUnits.isEmpty())
    AmountUnits = "\n(" + AmountUnits + ")";

  mpMoieties->horizontalHeaderItem(COL_AMOUNT)->setText("Total Amount" + AmountUnits);

  // Fill the moieties table
  int i = 0;

  if (pModel->getMoieties().size() > 0)
    {
      CCopasiVector< CMoiety >::const_iterator it = pModel->getMoieties().begin();
      CCopasiVector< CMoiety >::const_iterator end = pModel->getMoieties().end();
      mpMoieties->setRowCount(pModel->getMoieties().size());

      QTableWidgetItem * pItem;

      for (; it != end; ++it, i++)
        {
          pItem = new QTableWidgetItem(FROM_UTF8(it->getObjectName()));
          mpMoieties->setItem(i, COL_SPECIES, pItem);;

          pItem = new QTableWidgetItem(QVariant::Double);
          pItem->setData(Qt::DisplayRole, it->getNumber());
          mpMoieties->setItem(i, COL_NUMBER, pItem);

          it.constCast()->refreshAmount();
          pItem = new QTableWidgetItem(QVariant::Double);
          pItem->setData(Qt::DisplayRole, it->getAmount());
          mpMoieties->setItem(i, COL_AMOUNT, pItem);

          pItem = new QTableWidgetItem("");
          mpMoieties->setItem(i, COL_BTN, pItem);

          // Show the Button
          pItem = mpMoieties->item(i, COL_BTN);
          pItem->setFlags(pItem->flags() | Qt::ItemIsEditable | Qt::ItemIsEnabled);
          mpMoieties->openPersistentEditor(pItem);

          pItem = new QTableWidgetItem(FROM_UTF8(it->getDescription(pModel)));
          mpMoieties->setItem(i, COL_EQUATION, pItem);
        }
    }

  mpTabWidget->setTabText(mpTabWidget->indexOf(mpMoieties), "Moieties (" + QString::number(i) + ")");

  mpMoieties->resizeColumnsToContents();
  mpMoieties->resizeRowsToContents();

  // Fill the stoichiometry matrix
  CColorScaleBiLog * tcs = NULL;
  const CArrayAnnotation * pAnnotation =
    static_cast< const CArrayAnnotation * >(pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)")));
  tcs = new CColorScaleBiLog();
  mpStoichiometry->setColorCoding(tcs);
  mpStoichiometry->setColorScalingAutomatic(true);
  mpStoichiometry->setArrayAnnotation(pAnnotation);

  // Fill the link matrix
  pAnnotation =
    static_cast< const CArrayAnnotation * >(pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)")));
  tcs = new CColorScaleBiLog();
  mpLinkMatrix->setColorCoding(tcs);
  mpLinkMatrix->setColorScalingAutomatic(true);
  mpLinkMatrix->setArrayAnnotation(pAnnotation);

  // Fill the reduced stoichiometry matrix
  pAnnotation =
    static_cast< const CArrayAnnotation * >(pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)")));
  tcs = new CColorScaleBiLog();
  mpReducedStoichiometry->setColorCoding(tcs);
  mpReducedStoichiometry->setColorScalingAutomatic(true);
  mpReducedStoichiometry->setArrayAnnotation(pAnnotation);

  return;
}

void CQMoietiesTaskResult::slotSave(void)
{
  C_INT32 Answer = QMessageBox::No;
  QString fileName;

  while (Answer == QMessageBox::No)
    {
      fileName =
        CopasiFileDialog::getSaveFileName(this, "Save File Dialog",
                                          "untitled.txt", "TEXT Files (*.txt)", "Save to");

      if (fileName.isEmpty()) return;

      // Checks whether the file exists
      Answer = checkSelection(fileName);

      if (Answer == QMessageBox::Cancel) return;
    }

  std::ofstream file(CLocaleString::fromUtf8(TO_UTF8(fileName)).c_str());

  if (file.fail())
    return;

  if (mpMoietiesTask != NULL)
    file << mpMoietiesTask->getResult();

  return;
}

void CQMoietiesTaskResult::slotCreateGlobalQuantity(const QModelIndex & index)
{
  int row = index.row();

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CModel * pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel();

  if (pModel == NULL) return;

  const CCopasiVector< CMoiety > & Moieties = pModel->getMoieties();

  if (row >= (C_INT32) Moieties.size()) return;

  const CMoiety * pMoiety = &Moieties[row];

  CModelValue * pMV = pModel->createModelValue("Moiety[" + pMoiety->getObjectName() + "].TotalAmount");

  int i = 0;

  while (pMV == NULL)
    pMV = pModel->createModelValue("Moiety[" + pMoiety->getObjectName() + "].TotalAmount_" + TO_UTF8(QString::number(++i)));

  pMV->setInitialExpression(pMoiety->getExpression());
  protectedNotify(ListViews::MODELVALUE, ListViews::ADD);
}

// virtual
void CQMoietiesTaskResult::setFramework(int framework)
{
  CopasiWidget::setFramework(framework);

  switch (mFramework)
    {
      case 0: // Concentration
        mpMoieties->showColumn(COL_AMOUNT);
        mpMoieties->hideColumn(COL_NUMBER);
        break;

      case 1: // Particle Number
        mpMoieties->hideColumn(COL_AMOUNT);
        mpMoieties->showColumn(COL_NUMBER);
        break;
    }
}
<|endoftext|>


<commit_before>#define _USE_MATH_DEFINES
#include <math.h>
#include "BLITSineHardSync_oscillator.h"

namespace Steinberg{ namespace Vst{

	// constructor
	BLITSineHardSync_note::BLITSineHardSync_note()
		:_adsr(Off)
		,t(0.0)
		,sin(0.0)
		,blit(0.0)
		,n(0)
		,dt(0.0)
		,srate(44100)
	{
	}

	//
	void BLITSineHardSync_note::setSampleRate(int srate)
	{
		this->srate = srate;
	}

	//
	void BLITSineHardSync_note::release()
	{
		_adsr = Off;
	}

	//
	BLITSineHardSync_note::ADSR BLITSineHardSync_note::adsr()const
	{
		return _adsr;
	}

	//
	void BLITSineHardSync_note::trigger(const NoteOnEvent& noteOn)
	{
		_noteOn = noteOn; // copy
		_adsr = On;

		//
		double freq = 440.0*( ::pow(2.0, (_noteOn.pitch - _note_no_center)/12.0 ));
		n = static_cast<int>(srate / 2.0 / freq);
		t = 0.5;
		blit = 0.0;
		sin = 0.0;
		dt = freq / srate;
	}

	//
	int32 BLITSineHardSync_note::id()const
	{
		return _noteOn.noteId;
	}

	//
	double BLITSineHardSync_note::velocity()const
	{
		return _noteOn.velocity;
	}

	//--------------------------------------------------------------------------

	// constructor
	BLITSineHardSync_oscillator::BLITSineHardSync_oscillator()
	{
		// sine wave table
		for(size_t ii = 0; ii < _sinTable.size()-1; ii++)
		{
			_sinTable[ii] = sin( 2.0*M_PI * ii/(_sinTable.size()-1));
		}
		_sinTable.back() = 0.0;

		// initialize parameter
		setLeak(0.995);
		setSlave(1.2);
	}

	// set leak parameter
	void BLITSineHardSync_oscillator::setLeak(double value)
	{
		_leak = value;
	}

	// set slave parameter
	void BLITSineHardSync_oscillator::setSlave(double value)
	{
		if( value < 1.0 + 1.0e-12 )
		{
			_b1 = -1.0;
			_b2 = 0.0;
			_b3 = 0.0;
		}
		else if( value < 2 - 1.0e-12 )
		{
			// _b[n] = -2*n*::sin(M_PI*value)/(M_PI*(n+value)*(n-value));

			_b1 = -2*1*::sin(M_PI*value)/(M_PI*(1+value)*(1-value));
			_b2 = -2*2*::sin(M_PI*value)/(M_PI*(2+value)*(2-value));
			_b3 = -4*::sin(M_PI*value);
		}
		else
		{
			_b1 = 0.0;
			_b2 = 1.0;
			_b3 = 0.0;
		}
	}

	// calculate linear-interpolated sine wave
	double BLITSineHardSync_oscillator::LinearInterpolatedSin(double x)const
	{
		// scale table size
		double pos = (_sinTable.size()-1) * x;

		// cast to int
		unsigned int idx_A = static_cast<int>(pos);

		// linear interpolate
		double s = pos - idx_A;
		return (1.0-s)*_sinTable[idx_A] + s*_sinTable[idx_A+1];
	}

	// BLIT ?
	double BLITSineHardSync_oscillator::BLIT(double t, int N)const
	{
		int N1 = N+3;
		double cos1 = LinearInterpolatedSin(::fmod(0.5*t*N1+0.25, 1.0));

		int N2 = N-3+1;
		double sin1 = LinearInterpolatedSin(::fmod(0.5*t*N2, 1.0));

		double sin2 = LinearInterpolatedSin(0.5*t);

		if( (1.0e-8) < t && t < 1.0-(1.0e-8) )
		{
			return cos1*sin1/sin2;
		}
		else
		{
			// apply L'Hopital's rule
			return cos1*N2;
		}
	}

	//
	void BLITSineHardSync_oscillator::updateOscillater(BLITSineHardSync_note& note)
	{
		// update t
		note.t += note.dt;
		if ( 1.0 <= note.t )note.t -= 1.0;

		if( note.n >= 3)
		{
			// update BLIT section(n=3 -> Nyquist limit)
			note.blit = note.blit*_leak + BLIT(note.t, note.n)*note.dt;

			// update value
			note.sin = _b1*LinearInterpolatedSin(note.t)
			         + _b2*LinearInterpolatedSin(::fmod(2*note.t, 1.0))
					 + _b3*note.blit;
		}
		else if( note.n == 2 )
		{
			// reset BLIT section
			note.blit = 0.0;

			// update value
			note.sin = _b1*LinearInterpolatedSin(note.t)
			         + _b2*LinearInterpolatedSin(::fmod(2*note.t, 1.0));
		}
		else
		{
			// reset BLIT section
			note.blit = 0.0;

			// update value
			note.sin = _b1*LinearInterpolatedSin(note.t);
		}
	}

}} // namespace
<commit_msg>ロピタルの定理の計算ミスを修正<commit_after>#define _USE_MATH_DEFINES
#include <math.h>
#include "BLITSineHardSync_oscillator.h"

namespace Steinberg{ namespace Vst{

	// constructor
	BLITSineHardSync_note::BLITSineHardSync_note()
		:_adsr(Off)
		,t(0.0)
		,sin(0.0)
		,blit(0.0)
		,n(0)
		,dt(0.0)
		,srate(44100)
	{
	}

	//
	void BLITSineHardSync_note::setSampleRate(int srate)
	{
		this->srate = srate;
	}

	//
	void BLITSineHardSync_note::release()
	{
		_adsr = Off;
	}

	//
	BLITSineHardSync_note::ADSR BLITSineHardSync_note::adsr()const
	{
		return _adsr;
	}

	//
	void BLITSineHardSync_note::trigger(const NoteOnEvent& noteOn)
	{
		_noteOn = noteOn; // copy
		_adsr = On;

		//
		double freq = 440.0*( ::pow(2.0, (_noteOn.pitch - _note_no_center)/12.0 ));
		n = static_cast<int>(srate / 2.0 / freq);
		t = 0.5;
		blit = 0.0;
		sin = 0.0;
		dt = freq / srate;
	}

	//
	int32 BLITSineHardSync_note::id()const
	{
		return _noteOn.noteId;
	}

	//
	double BLITSineHardSync_note::velocity()const
	{
		return _noteOn.velocity;
	}

	//--------------------------------------------------------------------------

	// constructor
	BLITSineHardSync_oscillator::BLITSineHardSync_oscillator()
	{
		// sine wave table
		for(size_t ii = 0; ii < _sinTable.size()-1; ii++)
		{
			_sinTable[ii] = sin( 2.0*M_PI * ii/(_sinTable.size()-1));
		}
		_sinTable.back() = 0.0;

		// initialize parameter
		setLeak(0.995);
		setSlave(1.2);
	}

	// set leak parameter
	void BLITSineHardSync_oscillator::setLeak(double value)
	{
		_leak = value;
	}

	// set slave parameter
	void BLITSineHardSync_oscillator::setSlave(double value)
	{
		if( value < 1.0 + 1.0e-12 )
		{
			_b1 = -1.0;
			_b2 = 0.0;
			_b3 = 0.0;
		}
		else if( value < 2 - 1.0e-12 )
		{
			// _b[n] = -2*n*::sin(M_PI*value)/(M_PI*(n+value)*(n-value));

			_b1 = -2*1*::sin(M_PI*value)/(M_PI*(1+value)*(1-value));
			_b2 = -2*2*::sin(M_PI*value)/(M_PI*(2+value)*(2-value));
			_b3 = -4*::sin(M_PI*value);
		}
		else
		{
			_b1 = 0.0;
			_b2 = 1.0;
			_b3 = 0.0;
		}
	}

	// calculate linear-interpolated sine wave
	double BLITSineHardSync_oscillator::LinearInterpolatedSin(double x)const
	{
		// scale table size
		double pos = (_sinTable.size()-1) * x;

		// cast to int
		unsigned int idx_A = static_cast<int>(pos);

		// linear interpolate
		double s = pos - idx_A;
		return (1.0-s)*_sinTable[idx_A] + s*_sinTable[idx_A+1];
	}

	// BLIT ?
	double BLITSineHardSync_oscillator::BLIT(double t, int N)const
	{
		int N1 = N+3;
		double cos1 = LinearInterpolatedSin(::fmod(0.5*t*N1+0.25, 1.0));

		int N2 = N-3+1;
		double sin1 = LinearInterpolatedSin(::fmod(0.5*t*N2, 1.0));

		double sin2 = LinearInterpolatedSin(0.5*t);

		if( (1.0e-8) < t && t < 1.0-(1.0e-8) )
		{
			return cos1*sin1/sin2;
		}
		else
		{
			// apply L'Hopital's rule
			return N2;
		}
	}

	//
	void BLITSineHardSync_oscillator::updateOscillater(BLITSineHardSync_note& note)
	{
		// update t
		note.t += note.dt;
		if ( 1.0 <= note.t )note.t -= 1.0;

		if( note.n >= 3)
		{
			// update BLIT section(n=3 -> Nyquist limit)
			note.blit = note.blit*_leak + BLIT(note.t, note.n)*note.dt;

			// update value
			note.sin = _b1*LinearInterpolatedSin(note.t)
			         + _b2*LinearInterpolatedSin(::fmod(2*note.t, 1.0))
					 + _b3*note.blit;
		}
		else if( note.n == 2 )
		{
			// reset BLIT section
			note.blit = 0.0;

			// update value
			note.sin = _b1*LinearInterpolatedSin(note.t)
			         + _b2*LinearInterpolatedSin(::fmod(2*note.t, 1.0));
		}
		else
		{
			// reset BLIT section
			note.blit = 0.0;

			// update value
			note.sin = _b1*LinearInterpolatedSin(note.t);
		}
	}

}} // namespace
<|endoftext|>