text
stringlengths 5
1.04M
|
|---|
// A. Polycarp's Pockets
#include <stdio.h>
#include <algorithm>
#include <set>
int main(){
int n;
scanf("%d\n", &n);
int a[n];
for (int i=0; i<n; ++i){
scanf("%d", &(a[i]));
}
int minPockets = 0;
if (n==1){
minPockets = 1;
}
else {
std::sort(a, a + n);
std::set<int> st(a, a+n);
for (auto e: st){
int count = std::count(a, a+n, e);
if (count > minPockets) minPockets = count;
}
}
printf("%d\n", minPockets);
return 0;
}
|
/*
* Copyright (C) 2016 Google, 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 <cassert>
#include <cmath>
#include <cstring>
#include <array>
#include <unordered_map>
#include "Helpers.h"
#include "Meshes.h"
namespace {
class Mesh {
public:
struct Position {
float x;
float y;
float z;
};
struct Normal {
float x;
float y;
float z;
};
struct Face {
int v0;
int v1;
int v2;
};
static uint32_t vertex_stride()
{
// Position + Normal
const int comp_count = 6;
return sizeof(float) * comp_count;
}
static VkVertexInputBindingDescription vertex_input_binding()
{
VkVertexInputBindingDescription vi_binding = {};
vi_binding.binding = 0;
vi_binding.stride = vertex_stride();
vi_binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return vi_binding;
}
static std::vector<VkVertexInputAttributeDescription> vertex_input_attributes()
{
std::vector<VkVertexInputAttributeDescription> vi_attrs(2);
// Position
vi_attrs[0].location = 0;
vi_attrs[0].binding = 0;
vi_attrs[0].format = VK_FORMAT_R32G32B32_SFLOAT;
vi_attrs[0].offset = 0;
// Normal
vi_attrs[1].location = 1;
vi_attrs[1].binding = 0;
vi_attrs[1].format = VK_FORMAT_R32G32B32_SFLOAT;
vi_attrs[1].offset = sizeof(float) * 3;
return vi_attrs;
}
static VkIndexType index_type()
{
return VK_INDEX_TYPE_UINT32;
}
static VkPipelineInputAssemblyStateCreateInfo input_assembly_state()
{
VkPipelineInputAssemblyStateCreateInfo ia_info = {};
ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
ia_info.primitiveRestartEnable = false;
return ia_info;
}
void build(const std::vector<std::array<float, 6>> &vertices, const std::vector<std::array<int, 3>> &faces)
{
positions_.reserve(vertices.size());
normals_.reserve(vertices.size());
for (const auto &v : vertices) {
positions_.emplace_back(Position{ v[0], v[1], v[2] });
normals_.emplace_back(Normal{ v[3], v[4], v[5] });
}
faces_.reserve(faces.size());
for (const auto &f : faces)
faces_.emplace_back(Face{ f[0], f[1], f[2] });
}
uint32_t vertex_count() const
{
return static_cast<uint32_t>(positions_.size());
}
VkDeviceSize vertex_buffer_size() const
{
return vertex_stride() * vertex_count();
}
void vertex_buffer_write(void *data) const
{
float *dst = reinterpret_cast<float *>(data);
for (size_t i = 0; i < positions_.size(); i++) {
const Position &pos = positions_[i];
const Normal &normal = normals_[i];
dst[0] = pos.x;
dst[1] = pos.y;
dst[2] = pos.z;
dst[3] = normal.x;
dst[4] = normal.y;
dst[5] = normal.z;
dst += 6;
}
}
uint32_t index_count() const
{
return static_cast<uint32_t>(faces_.size() * 3);
}
VkDeviceSize index_buffer_size() const
{
return sizeof(uint32_t) * index_count();
}
void index_buffer_write(void *data) const
{
uint32_t *dst = reinterpret_cast<uint32_t *>(data);
for (const auto &face : faces_) {
dst[0] = face.v0;
dst[1] = face.v1;
dst[2] = face.v2;
dst += 3;
}
}
std::vector<Position> positions_;
std::vector<Normal> normals_;
std::vector<Face> faces_;
};
class BuildPyramid {
public:
BuildPyramid(Mesh &mesh)
{
const std::vector<std::array<float, 6>> vertices = {
// position normal
{ 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f },
{ -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f },
{ 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f },
{ 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f },
{ -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f },
};
const std::vector<std::array<int, 3>> faces = {
{ 0, 1, 2 },
{ 0, 2, 3 },
{ 0, 3, 4 },
{ 0, 4, 1 },
{ 1, 4, 3 },
{ 1, 3, 2 },
};
mesh.build(vertices, faces);
}
};
class BuildIcosphere {
public:
BuildIcosphere(Mesh &mesh) : mesh_(mesh), radius_(1.0f)
{
const int tessellate_level = 2;
build_icosahedron();
for (int i = 0; i < tessellate_level; i++)
tessellate();
}
private:
void build_icosahedron()
{
// https://en.wikipedia.org/wiki/Regular_icosahedron
const float l1 = std::sqrt(2.0f / (5.0f + std::sqrt(5.0f))) * radius_;
const float l2 = std::sqrt(2.0f / (5.0f - std::sqrt(5.0f))) * radius_;
// vertices are from three golden rectangles
const std::vector<std::array<float, 6>> icosahedron_vertices = {
// position normal
{ -l1, -l2, 0.0f, -l1, -l2, 0.0f, },
{ l1, -l2, 0.0f, l1, -l2, 0.0f, },
{ l1, l2, 0.0f, l1, l2, 0.0f, },
{ -l1, l2, 0.0f, -l1, l2, 0.0f, },
{ -l2, 0.0f, -l1, -l2, 0.0f, -l1, },
{ l2, 0.0f, -l1, l2, 0.0f, -l1, },
{ l2, 0.0f, l1, l2, 0.0f, l1, },
{ -l2, 0.0f, l1, -l2, 0.0f, l1, },
{ 0.0f, -l1, -l2, 0.0f, -l1, -l2, },
{ 0.0f, l1, -l2, 0.0f, l1, -l2, },
{ 0.0f, l1, l2, 0.0f, l1, l2, },
{ 0.0f, -l1, l2, 0.0f, -l1, l2, },
};
const std::vector<std::array<int, 3>> icosahedron_faces = {
// triangles sharing vertex 0
{ 0, 1, 11 },
{ 0, 11, 7 },
{ 0, 7, 4 },
{ 0, 4, 8 },
{ 0, 8, 1 },
// adjacent triangles
{ 11, 1, 6 },
{ 7, 11, 10 },
{ 4, 7, 3 },
{ 8, 4, 9 },
{ 1, 8, 5 },
// triangles sharing vertex 2
{ 2, 3, 10 },
{ 2, 10, 6 },
{ 2, 6, 5 },
{ 2, 5, 9 },
{ 2, 9, 3 },
// adjacent triangles
{ 10, 3, 7 },
{ 6, 10, 11 },
{ 5, 6, 1 },
{ 9, 5, 8 },
{ 3, 9, 4 },
};
mesh_.build(icosahedron_vertices, icosahedron_faces);
}
void tessellate()
{
size_t middle_point_count = mesh_.faces_.size() * 3 / 2;
size_t final_face_count = mesh_.faces_.size() * 4;
std::vector<Mesh::Face> faces;
faces.reserve(final_face_count);
middle_points_.clear();
middle_points_.reserve(middle_point_count);
mesh_.positions_.reserve(mesh_.vertex_count() + middle_point_count);
mesh_.normals_.reserve(mesh_.vertex_count() + middle_point_count);
for (const auto &f : mesh_.faces_) {
int v0 = f.v0;
int v1 = f.v1;
int v2 = f.v2;
int v01 = add_middle_point(v0, v1);
int v12 = add_middle_point(v1, v2);
int v20 = add_middle_point(v2, v0);
faces.emplace_back(Mesh::Face{ v0, v01, v20 });
faces.emplace_back(Mesh::Face{ v1, v12, v01 });
faces.emplace_back(Mesh::Face{ v2, v20, v12 });
faces.emplace_back(Mesh::Face{ v01, v12, v20 });
}
mesh_.faces_.swap(faces);
}
int add_middle_point(int a, int b)
{
uint64_t key = (a < b) ? ((uint64_t) a << 32 | b) : ((uint64_t) b << 32 | a);
auto it = middle_points_.find(key);
if (it != middle_points_.end())
return it->second;
const Mesh::Position &pos_a = mesh_.positions_[a];
const Mesh::Position &pos_b = mesh_.positions_[b];
Mesh::Position pos_mid = {
(pos_a.x + pos_b.x) / 2.0f,
(pos_a.y + pos_b.y) / 2.0f,
(pos_a.z + pos_b.z) / 2.0f,
};
float scale = radius_ / std::sqrt(pos_mid.x * pos_mid.x +
pos_mid.y * pos_mid.y +
pos_mid.z * pos_mid.z);
pos_mid.x *= scale;
pos_mid.y *= scale;
pos_mid.z *= scale;
Mesh::Normal normal_mid = { pos_mid.x, pos_mid.y, pos_mid.z };
normal_mid.x /= radius_;
normal_mid.y /= radius_;
normal_mid.z /= radius_;
mesh_.positions_.emplace_back(pos_mid);
mesh_.normals_.emplace_back(normal_mid);
int mid = mesh_.vertex_count() - 1;
middle_points_.emplace(std::make_pair(key, mid));
return mid;
}
Mesh &mesh_;
const float radius_;
std::unordered_map<uint64_t, uint32_t> middle_points_;
};
class BuildTeapot {
public:
BuildTeapot(Mesh &mesh)
{
#include "Meshes.teapot.h"
const int position_count = sizeof(teapot_positions) / sizeof(teapot_positions[0]);
const int index_count = sizeof(teapot_indices) / sizeof(teapot_indices[0]);
assert(position_count % 3 == 0 && index_count % 3 == 0);
Mesh::Position translate;
float scale;
get_transform(teapot_positions, position_count, translate, scale);
for (int i = 0; i < position_count; i += 3) {
mesh.positions_.emplace_back(Mesh::Position{
(teapot_positions[i + 0] + translate.x) * scale,
(teapot_positions[i + 1] + translate.y) * scale,
(teapot_positions[i + 2] + translate.z) * scale,
});
mesh.normals_.emplace_back(Mesh::Normal{
teapot_normals[i + 0],
teapot_normals[i + 1],
teapot_normals[i + 2],
});
}
for (int i = 0; i < index_count; i += 3) {
mesh.faces_.emplace_back(Mesh::Face{
teapot_indices[i + 0],
teapot_indices[i + 1],
teapot_indices[i + 2]
});
}
}
void get_transform(const float *positions, int position_count,
Mesh::Position &translate, float &scale)
{
float min[3] = {
positions[0],
positions[1],
positions[2],
};
float max[3] = {
positions[0],
positions[1],
positions[2],
};
for (int i = 3; i < position_count; i += 3) {
for (int j = 0; j < 3; j++) {
if (min[j] > positions[i + j])
min[j] = positions[i + j];
if (max[j] < positions[i + j])
max[j] = positions[i + j];
}
}
translate.x = -(min[0] + max[0]) / 2.0f;
translate.y = -(min[1] + max[1]) / 2.0f;
translate.z = -(min[2] + max[2]) / 2.0f;
float extents[3] = {
max[0] + translate.x,
max[1] + translate.y,
max[2] + translate.z,
};
float max_extent = extents[0];
if (max_extent < extents[1])
max_extent = extents[1];
if (max_extent < extents[2])
max_extent = extents[2];
scale = 1.0f / max_extent;
}
};
void build_meshes(std::array<Mesh, Meshes::MESH_COUNT> &meshes)
{
BuildPyramid build_pyramid(meshes[Meshes::MESH_PYRAMID]);
BuildIcosphere build_icosphere(meshes[Meshes::MESH_ICOSPHERE]);
BuildTeapot build_teapot(meshes[Meshes::MESH_TEAPOT]);
}
} // namespace
Meshes::Meshes(VkDevice dev, const std::vector<VkMemoryPropertyFlags> &mem_flags)
: dev_(dev),
vertex_input_binding_(Mesh::vertex_input_binding()),
vertex_input_attrs_(Mesh::vertex_input_attributes()),
vertex_input_state_(),
input_assembly_state_(Mesh::input_assembly_state()),
index_type_(Mesh::index_type())
{
vertex_input_state_.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertex_input_state_.vertexBindingDescriptionCount = 1;
vertex_input_state_.pVertexBindingDescriptions = &vertex_input_binding_;
vertex_input_state_.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertex_input_attrs_.size());
vertex_input_state_.pVertexAttributeDescriptions = vertex_input_attrs_.data();
std::array<Mesh, MESH_COUNT> meshes;
build_meshes(meshes);
draw_commands_.reserve(meshes.size());
uint32_t first_index = 0;
int32_t vertex_offset = 0;
VkDeviceSize vb_size = 0;
VkDeviceSize ib_size = 0;
for (const auto &mesh : meshes) {
VkDrawIndexedIndirectCommand draw = {};
draw.indexCount = mesh.index_count();
draw.instanceCount = 1;
draw.firstIndex = first_index;
draw.vertexOffset = vertex_offset;
draw.firstInstance = 0;
draw_commands_.push_back(draw);
first_index += mesh.index_count();
vertex_offset += mesh.vertex_count();
vb_size += mesh.vertex_buffer_size();
ib_size += mesh.index_buffer_size();
}
allocate_resources(vb_size, ib_size, mem_flags);
uint8_t *vb_data, *ib_data;
vk::assert_success(vkMapMemory(dev_, mem_, 0, VK_WHOLE_SIZE,
0, reinterpret_cast<void **>(&vb_data)));
ib_data = vb_data + ib_mem_offset_;
for (const auto &mesh : meshes) {
mesh.vertex_buffer_write(vb_data);
mesh.index_buffer_write(ib_data);
vb_data += mesh.vertex_buffer_size();
ib_data += mesh.index_buffer_size();
}
vkUnmapMemory(dev_, mem_);
}
Meshes::~Meshes()
{
vkFreeMemory(dev_, mem_, nullptr);
vkDestroyBuffer(dev_, vb_, nullptr);
vkDestroyBuffer(dev_, ib_, nullptr);
}
void Meshes::cmd_bind_buffers(VkCommandBuffer cmd) const
{
const VkDeviceSize vb_offset = 0;
vkCmdBindVertexBuffers(cmd, 0, 1, &vb_, &vb_offset);
vkCmdBindIndexBuffer(cmd, ib_, 0, index_type_);
}
void Meshes::cmd_draw(VkCommandBuffer cmd, Type type) const
{
const auto &draw = draw_commands_[type];
vkCmdDrawIndexed(cmd, draw.indexCount, draw.instanceCount,
draw.firstIndex, draw.vertexOffset, draw.firstInstance);
}
void Meshes::allocate_resources(VkDeviceSize vb_size, VkDeviceSize ib_size, const std::vector<VkMemoryPropertyFlags> &mem_flags)
{
VkBufferCreateInfo buf_info = {};
buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.size = vb_size;
buf_info.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
vkCreateBuffer(dev_, &buf_info, nullptr, &vb_);
buf_info.size = ib_size;
buf_info.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
vkCreateBuffer(dev_, &buf_info, nullptr, &ib_);
VkMemoryRequirements vb_mem_reqs, ib_mem_reqs;
vkGetBufferMemoryRequirements(dev_, vb_, &vb_mem_reqs);
vkGetBufferMemoryRequirements(dev_, ib_, &ib_mem_reqs);
// indices follow vertices
ib_mem_offset_ = vb_mem_reqs.size +
(ib_mem_reqs.alignment - (vb_mem_reqs.size % ib_mem_reqs.alignment));
VkMemoryAllocateInfo mem_info = {};
mem_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
mem_info.allocationSize = ib_mem_offset_ + ib_mem_reqs.size;
// find any supported and mappable memory type
uint32_t mem_types = (vb_mem_reqs.memoryTypeBits & ib_mem_reqs.memoryTypeBits);
for (uint32_t idx = 0; idx < mem_flags.size(); idx++) {
if ((mem_types & (1 << idx)) &&
(mem_flags[idx] & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) &&
(mem_flags[idx] & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) {
// TODO this may not be reachable
mem_info.memoryTypeIndex = idx;
break;
}
}
vkAllocateMemory(dev_, &mem_info, nullptr, &mem_);
vkBindBufferMemory(dev_, vb_, mem_, 0);
vkBindBufferMemory(dev_, ib_, mem_, ib_mem_offset_);
}
|
#ifndef STAN_MATH_PRIM_SCAL_PROB_SCALED_INV_CHI_SQUARE_LPDF_HPP
#define STAN_MATH_PRIM_SCAL_PROB_SCALED_INV_CHI_SQUARE_LPDF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/err/check_positive_finite.hpp>
#include <stan/math/prim/scal/fun/size_zero.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/fun/digamma.hpp>
#include <stan/math/prim/scal/fun/lgamma.hpp>
#include <stan/math/prim/scal/fun/grad_reg_inc_gamma.hpp>
#include <cmath>
namespace stan {
namespace math {
/**
* The log of a scaled inverse chi-squared density for y with the
* specified degrees of freedom parameter and scale parameter.
*
\f{eqnarray*}{
y &\sim& \mbox{\sf{Inv-}}\chi^2(\nu, s^2) \\
\log (p (y \, |\, \nu, s)) &=& \log \left( \frac{(\nu / 2)^{\nu / 2}}{\Gamma
(\nu / 2)} s^\nu y^{- (\nu / 2 + 1)} \exp^{-\nu s^2 / (2y)} \right) \\
&=& \frac{\nu}{2} \log(\frac{\nu}{2}) - \log (\Gamma (\nu / 2)) + \nu \log(s) -
(\frac{\nu}{2} + 1) \log(y) - \frac{\nu s^2}{2y} \\ & & \mathrm{ where } \; y >
0 \f}
* @param y A scalar variable.
* @param nu Degrees of freedom.
* @param s Scale parameter.
* @throw std::domain_error if nu is not greater than 0
* @throw std::domain_error if s is not greater than 0.
* @throw std::domain_error if y is not greater than 0.
* @tparam T_y Type of scalar.
* @tparam T_dof Type of degrees of freedom.
*/
template <bool propto, typename T_y, typename T_dof, typename T_scale>
typename return_type<T_y, T_dof, T_scale>::type scaled_inv_chi_square_lpdf(
const T_y& y, const T_dof& nu, const T_scale& s) {
static const char* function = "scaled_inv_chi_square_lpdf";
typedef typename stan::partials_return_type<T_y, T_dof, T_scale>::type
T_partials_return;
check_not_nan(function, "Random variable", y);
check_positive_finite(function, "Degrees of freedom parameter", nu);
check_positive_finite(function, "Scale parameter", s);
check_consistent_sizes(function, "Random variable", y,
"Degrees of freedom parameter", nu, "Scale parameter",
s);
if (size_zero(y, nu, s))
return 0;
if (!include_summand<propto, T_y, T_dof, T_scale>::value)
return 0;
T_partials_return logp(0);
scalar_seq_view<T_y> y_vec(y);
scalar_seq_view<T_dof> nu_vec(nu);
scalar_seq_view<T_scale> s_vec(s);
size_t N = max_size(y, nu, s);
for (size_t n = 0; n < N; n++) {
if (value_of(y_vec[n]) <= 0)
return LOG_ZERO;
}
using std::log;
VectorBuilder<include_summand<propto, T_dof, T_y, T_scale>::value,
T_partials_return, T_dof>
half_nu(length(nu));
for (size_t i = 0; i < length(nu); i++)
if (include_summand<propto, T_dof, T_y, T_scale>::value)
half_nu[i] = 0.5 * value_of(nu_vec[i]);
VectorBuilder<include_summand<propto, T_dof, T_y>::value, T_partials_return,
T_y>
log_y(length(y));
for (size_t i = 0; i < length(y); i++)
if (include_summand<propto, T_dof, T_y>::value)
log_y[i] = log(value_of(y_vec[i]));
VectorBuilder<include_summand<propto, T_dof, T_y, T_scale>::value,
T_partials_return, T_y>
inv_y(length(y));
for (size_t i = 0; i < length(y); i++)
if (include_summand<propto, T_dof, T_y, T_scale>::value)
inv_y[i] = 1.0 / value_of(y_vec[i]);
VectorBuilder<include_summand<propto, T_dof, T_scale>::value,
T_partials_return, T_scale>
log_s(length(s));
for (size_t i = 0; i < length(s); i++)
if (include_summand<propto, T_dof, T_scale>::value)
log_s[i] = log(value_of(s_vec[i]));
VectorBuilder<include_summand<propto, T_dof>::value, T_partials_return, T_dof>
log_half_nu(length(nu));
VectorBuilder<include_summand<propto, T_dof>::value, T_partials_return, T_dof>
lgamma_half_nu(length(nu));
VectorBuilder<!is_constant_all<T_dof>::value, T_partials_return, T_dof>
digamma_half_nu_over_two(length(nu));
for (size_t i = 0; i < length(nu); i++) {
if (include_summand<propto, T_dof>::value)
lgamma_half_nu[i] = lgamma(half_nu[i]);
if (include_summand<propto, T_dof>::value)
log_half_nu[i] = log(half_nu[i]);
if (!is_constant_all<T_dof>::value)
digamma_half_nu_over_two[i] = digamma(half_nu[i]) * 0.5;
}
operands_and_partials<T_y, T_dof, T_scale> ops_partials(y, nu, s);
for (size_t n = 0; n < N; n++) {
const T_partials_return s_dbl = value_of(s_vec[n]);
const T_partials_return nu_dbl = value_of(nu_vec[n]);
if (include_summand<propto, T_dof>::value)
logp += half_nu[n] * log_half_nu[n] - lgamma_half_nu[n];
if (include_summand<propto, T_dof, T_scale>::value)
logp += nu_dbl * log_s[n];
if (include_summand<propto, T_dof, T_y>::value)
logp -= (half_nu[n] + 1.0) * log_y[n];
if (include_summand<propto, T_dof, T_y, T_scale>::value)
logp -= half_nu[n] * s_dbl * s_dbl * inv_y[n];
if (!is_constant_all<T_y>::value) {
ops_partials.edge1_.partials_[n]
+= -(half_nu[n] + 1.0) * inv_y[n]
+ half_nu[n] * s_dbl * s_dbl * inv_y[n] * inv_y[n];
}
if (!is_constant_all<T_dof>::value) {
ops_partials.edge2_.partials_[n]
+= 0.5 * log_half_nu[n] + 0.5 - digamma_half_nu_over_two[n] + log_s[n]
- 0.5 * log_y[n] - 0.5 * s_dbl * s_dbl * inv_y[n];
}
if (!is_constant_all<T_scale>::value) {
ops_partials.edge3_.partials_[n]
+= nu_dbl / s_dbl - nu_dbl * inv_y[n] * s_dbl;
}
}
return ops_partials.build(logp);
}
template <typename T_y, typename T_dof, typename T_scale>
inline typename return_type<T_y, T_dof, T_scale>::type
scaled_inv_chi_square_lpdf(const T_y& y, const T_dof& nu, const T_scale& s) {
return scaled_inv_chi_square_lpdf<false>(y, nu, s);
}
} // namespace math
} // namespace stan
#endif
|
/*
* Copyright (C) 2010, 2011, 2012 Stephen F. Booth <me@sbooth.org>
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of Stephen F. Booth nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "ChannelLayoutsAreEqual.h"
bool
ChannelLayoutsAreEqual(const AudioChannelLayout *lhs, const AudioChannelLayout *rhs)
{
if(lhs == rhs)
return true;
if(nullptr == lhs || nullptr == rhs)
return false;
// First check if the tags are equal
if(lhs->mChannelLayoutTag != rhs->mChannelLayoutTag)
return false;
// If the tags are equal, check for special values
if(kAudioChannelLayoutTag_UseChannelBitmap == lhs->mChannelLayoutTag)
return (lhs->mChannelBitmap == rhs->mChannelBitmap);
if(kAudioChannelLayoutTag_UseChannelDescriptions == lhs->mChannelLayoutTag) {
if(lhs->mNumberChannelDescriptions != rhs->mNumberChannelDescriptions)
return false;
size_t bytesToCompare = lhs->mNumberChannelDescriptions * sizeof(AudioChannelDescription);
return (0 == memcmp(&lhs->mChannelDescriptions, &rhs->mChannelDescriptions, bytesToCompare));
}
return true;
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "ServerFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Basics/process-utils.h"
#include "Cluster/HeartbeatThread.h"
#include "Cluster/ServerState.h"
#include "Logger/Logger.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "Replication/ReplicationFeature.h"
#include "RestServer/DatabaseFeature.h"
#include "RestServer/VocbaseContext.h"
#include "Scheduler/SchedulerFeature.h"
#include "V8/v8-conv.h"
#include "V8/v8-globals.h"
#include "V8/v8-utils.h"
#include "V8Server/V8Context.h"
#include "V8Server/V8DealerFeature.h"
using namespace arangodb::application_features;
using namespace arangodb::options;
using namespace arangodb::rest;
namespace arangodb {
ServerFeature::ServerFeature(application_features::ApplicationServer& server, int* res)
: ApplicationFeature(server, "Server"),
_vstMaxSize(1024 * 30),
_result(res),
_operationMode(OperationMode::MODE_SERVER)
#if _WIN32
,
_codePage(65001), // default to UTF8
_originalCodePage(UINT16_MAX)
#endif
{
setOptional(true);
startsAfter("AQLPhase");
startsAfter("Statistics");
startsAfter("Upgrade");
}
void ServerFeature::collectOptions(std::shared_ptr<ProgramOptions> options) {
options->addOption("--console", "start a JavaScript emergency console",
new BooleanParameter(&_console));
options->addSection("server", "Server features");
options->addOption("--server.rest-server", "start a rest-server",
new BooleanParameter(&_restServer),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden));
options->addObsoleteOption(
"--server.session-timeout",
"timeout of web interface server sessions (in seconds)", true);
options->addSection("javascript", "Configure the Javascript engine");
options->addOption("--javascript.script", "run scripts and exit",
new VectorParameter<StringParameter>(&_scripts));
options->addSection("vst", "Configure the VelocyStream protocol");
options->addOption("--vst.maxsize",
"maximal size (in bytes) for a VelocyPack chunk",
new UInt32Parameter(&_vstMaxSize));
#if _WIN32
options->addOption("--console.code-page",
"Windows code page to use; defaults to UTF8",
new UInt16Parameter(&_codePage),
arangodb::options::makeFlags(arangodb::options::Flags::Hidden));
#endif
}
void ServerFeature::validateOptions(std::shared_ptr<ProgramOptions> options) {
int count = 0;
if (_console) {
_operationMode = OperationMode::MODE_CONSOLE;
++count;
}
if (!_scripts.empty()) {
_operationMode = OperationMode::MODE_SCRIPT;
++count;
}
if (1 < count) {
LOG_TOPIC("353cd", FATAL, arangodb::Logger::FIXME)
<< "cannot combine '--console', '--javascript.unit-tests' and "
<< "'--javascript.script'";
FATAL_ERROR_EXIT();
}
if (_operationMode == OperationMode::MODE_SERVER && !_restServer) {
LOG_TOPIC("8daab", FATAL, arangodb::Logger::FIXME)
<< "need at least '--console', '--javascript.unit-tests' or"
<< "'--javascript.script if rest-server is disabled";
FATAL_ERROR_EXIT();
}
V8DealerFeature* v8dealer =
ApplicationServer::getFeature<V8DealerFeature>("V8Dealer");
if (v8dealer->isEnabled()) {
if (_operationMode == OperationMode::MODE_SCRIPT) {
v8dealer->setMinimumContexts(2);
} else {
v8dealer->setMinimumContexts(1);
}
} else if (_operationMode != OperationMode::MODE_SERVER) {
LOG_TOPIC("a114b", FATAL, arangodb::Logger::FIXME)
<< "Options '--console', '--javascript.unit-tests'"
<< " or '--javascript.script' are not supported without V8";
FATAL_ERROR_EXIT();
}
if (!_restServer) {
ApplicationServer::disableFeatures({"Daemon", "Endpoint", "GeneralServer",
"SslServer", "Statistics",
"Supervisor"});
if (!options->processingResult().touched("replication.auto-start")) {
// turn off replication applier when we do not have a rest server
// but only if the config option is not explicitly set (the recovery
// test want the applier to be enabled for testing it)
ReplicationFeature* replicationFeature =
ApplicationServer::getFeature<ReplicationFeature>("Replication");
replicationFeature->disableReplicationApplier();
}
}
if (_operationMode == OperationMode::MODE_CONSOLE) {
ApplicationServer::disableFeatures({"Daemon", "Supervisor"});
v8dealer->setMinimumContexts(2);
}
if (_operationMode == OperationMode::MODE_SERVER ||
_operationMode == OperationMode::MODE_CONSOLE) {
ApplicationServer::getFeature<ApplicationFeature>("Shutdown")->disable();
}
}
void ServerFeature::start() {
#if _WIN32
_originalCodePage = GetConsoleOutputCP();
if (IsValidCodePage(_codePage)) {
SetConsoleOutputCP(_codePage);
}
#endif
waitForHeartbeat();
*_result = EXIT_SUCCESS;
switch (_operationMode) {
case OperationMode::MODE_SCRIPT:
case OperationMode::MODE_CONSOLE:
break;
case OperationMode::MODE_SERVER:
LOG_TOPIC("7031b", TRACE, Logger::STARTUP) << "server operation mode: SERVER";
break;
}
// flush all log output before we go on... this is sensible because any
// of the following options may print or prompt, and pending log entries
// might overwrite that
Logger::flush();
if (!isConsoleMode()) {
// install CTRL-C handlers
server()->registerStartupCallback([]() {
ApplicationServer::getFeature<SchedulerFeature>("Scheduler")->buildControlCHandler();
});
}
}
void ServerFeature::stop() {
#if _WIN32
if (IsValidCodePage(_originalCodePage)) {
SetConsoleOutputCP(_originalCodePage);
}
#endif
}
void ServerFeature::beginShutdown() {
std::string msg =
ArangoGlobalContext::CONTEXT->binaryName() + " [shutting down]";
TRI_SetProcessTitle(msg.c_str());
_isStopping = true;
}
void ServerFeature::waitForHeartbeat() {
if (!ServerState::instance()->isCoordinator()) {
// waiting for the heartbeart thread is necessary on coordinator only
return;
}
while (true) {
if (HeartbeatThread::hasRunOnce()) {
break;
}
std::this_thread::sleep_for(std::chrono::microseconds(100 * 1000));
}
}
std::string ServerFeature::operationModeString(OperationMode mode) {
switch (mode) {
case OperationMode::MODE_CONSOLE:
return "console";
case OperationMode::MODE_SCRIPT:
return "script";
case OperationMode::MODE_SERVER:
return "server";
default:
return "unknown";
}
}
} // namespace arangodb
|
#ifdef PEGASUS_OS_TRU64
#ifndef __UNIX_NETWORKINGIDAUTHENTICATION_PRIVATE_H
#define __UNIX_NETWORKINGIDAUTHENTICATION_PRIVATE_H
#endif
#endif
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop.h"
#include <algorithm>
#include "base/compiler_specific.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/message_pump_default.h"
#include "base/string_util.h"
#include "base/thread_local.h"
#if defined(OS_MACOSX)
#include "base/message_pump_mac.h"
#endif
#if defined(OS_POSIX)
#include "base/message_pump_libevent.h"
#endif
#if defined(OS_LINUX) || defined(OS_BSD)
#ifdef MOZ_WIDGET_GTK2
#include "base/message_pump_glib.h"
#endif
#ifdef MOZ_WIDGET_QT
#include "base/message_pump_qt.h"
#endif
#endif
#ifdef ANDROID
#include "base/message_pump_android.h"
#endif
#include "MessagePump.h"
using base::Time;
using base::TimeDelta;
using base::TimeTicks;
// A lazily created thread local storage for quick access to a thread's message
// loop, if one exists. This should be safe and free of static constructors.
static base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
base::LINKER_INITIALIZED);
//------------------------------------------------------------------------------
// Logical events for Histogram profiling. Run with -message-loop-histogrammer
// to get an accounting of messages and actions taken on each thread.
static const int kTaskRunEvent = 0x1;
static const int kTimerEvent = 0x2;
// Provide range of message IDs for use in histogramming and debug display.
static const int kLeastNonZeroMessageId = 1;
static const int kMaxMessageId = 1099;
static const int kNumberOfDistinctMessagesDisplayed = 1100;
//------------------------------------------------------------------------------
#if defined(OS_WIN)
// Upon a SEH exception in this thread, it restores the original unhandled
// exception filter.
static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
::SetUnhandledExceptionFilter(old_filter);
return EXCEPTION_CONTINUE_SEARCH;
}
// Retrieves a pointer to the current unhandled exception filter. There
// is no standalone getter method.
static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
top_filter = ::SetUnhandledExceptionFilter(0);
::SetUnhandledExceptionFilter(top_filter);
return top_filter;
}
#endif // defined(OS_WIN)
//------------------------------------------------------------------------------
// static
MessageLoop* MessageLoop::current() {
// TODO(darin): sadly, we cannot enable this yet since people call us even
// when they have no intention of using us.
//DCHECK(loop) << "Ouch, did you forget to initialize me?";
return lazy_tls_ptr.Pointer()->Get();
}
PRInt32 message_loop_id_seq = 0;
MessageLoop::MessageLoop(Type type)
: type_(type),
nestable_tasks_allowed_(true),
exception_restoration_(false),
state_(NULL),
run_depth_base_(1),
#ifdef OS_WIN
os_modal_loop_(false),
#endif // OS_WIN
next_sequence_num_(0),
id_(PR_ATOMIC_INCREMENT(&message_loop_id_seq)) {
DCHECK(!current()) << "should only have one message loop per thread";
lazy_tls_ptr.Pointer()->Set(this);
if (type_ == TYPE_MOZILLA_UI) {
pump_ = new mozilla::ipc::MessagePump();
return;
}
if (type_ == TYPE_MOZILLA_CHILD) {
pump_ = new mozilla::ipc::MessagePumpForChildProcess();
// There is a MessageLoop Run call from XRE_InitChildProcess
// and another one from MessagePumpForChildProcess. The one
// from MessagePumpForChildProcess becomes the base, so we need
// to set run_depth_base_ to 2 or we'll never be able to process
// Idle tasks.
run_depth_base_ = 2;
return;
}
#if defined(OS_WIN)
// TODO(rvargas): Get rid of the OS guards.
if (type_ == TYPE_DEFAULT) {
pump_ = new base::MessagePumpDefault();
} else if (type_ == TYPE_IO) {
pump_ = new base::MessagePumpForIO();
} else {
DCHECK(type_ == TYPE_UI);
pump_ = new base::MessagePumpForUI();
}
#elif defined(OS_POSIX)
if (type_ == TYPE_UI) {
#if defined(OS_MACOSX)
pump_ = base::MessagePumpMac::Create();
#elif defined(OS_LINUX) || defined(OS_BSD)
pump_ = new base::MessagePumpForUI();
#endif // OS_LINUX
} else if (type_ == TYPE_IO) {
pump_ = new base::MessagePumpLibevent();
} else {
pump_ = new base::MessagePumpDefault();
}
#endif // OS_POSIX
}
MessageLoop::~MessageLoop() {
DCHECK(this == current());
// Let interested parties have one last shot at accessing this.
FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
WillDestroyCurrentMessageLoop());
DCHECK(!state_);
// Clean up any unprocessed tasks, but take care: deleting a task could
// result in the addition of more tasks (e.g., via DeleteSoon). We set a
// limit on the number of times we will allow a deleted task to generate more
// tasks. Normally, we should only pass through this loop once or twice. If
// we end up hitting the loop limit, then it is probably due to one task that
// is being stubborn. Inspect the queues to see who is left.
bool did_work;
for (int i = 0; i < 100; ++i) {
DeletePendingTasks();
ReloadWorkQueue();
// If we end up with empty queues, then break out of the loop.
did_work = DeletePendingTasks();
if (!did_work)
break;
}
DCHECK(!did_work);
// OK, now make it so that no one can find us.
lazy_tls_ptr.Pointer()->Set(NULL);
}
void MessageLoop::AddDestructionObserver(DestructionObserver *obs) {
DCHECK(this == current());
destruction_observers_.AddObserver(obs);
}
void MessageLoop::RemoveDestructionObserver(DestructionObserver *obs) {
DCHECK(this == current());
destruction_observers_.RemoveObserver(obs);
}
void MessageLoop::Run() {
AutoRunState save_state(this);
RunHandler();
}
void MessageLoop::RunAllPending() {
AutoRunState save_state(this);
state_->quit_received = true; // Means run until we would otherwise block.
RunHandler();
}
// Runs the loop in two different SEH modes:
// enable_SEH_restoration_ = false : any unhandled exception goes to the last
// one that calls SetUnhandledExceptionFilter().
// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
// that was existed before the loop was run.
void MessageLoop::RunHandler() {
#if defined(OS_WIN)
if (exception_restoration_) {
LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
MOZ_SEH_TRY {
RunInternal();
} MOZ_SEH_EXCEPT(SEHFilter(current_filter)) {
}
return;
}
#endif
RunInternal();
}
//------------------------------------------------------------------------------
void MessageLoop::RunInternal() {
DCHECK(this == current());
pump_->Run(this);
}
//------------------------------------------------------------------------------
// Wrapper functions for use in above message loop framework.
bool MessageLoop::ProcessNextDelayedNonNestableTask() {
if (state_->run_depth > run_depth_base_)
return false;
if (deferred_non_nestable_work_queue_.empty())
return false;
Task* task = deferred_non_nestable_work_queue_.front().task;
deferred_non_nestable_work_queue_.pop();
RunTask(task);
return true;
}
//------------------------------------------------------------------------------
void MessageLoop::Quit() {
DCHECK(current() == this);
if (state_) {
state_->quit_received = true;
} else {
NOTREACHED() << "Must be inside Run to call Quit";
}
}
void MessageLoop::PostTask(
const tracked_objects::Location& from_here, Task* task) {
PostTask_Helper(from_here, task, 0, true);
}
void MessageLoop::PostDelayedTask(
const tracked_objects::Location& from_here, Task* task, int delay_ms) {
PostTask_Helper(from_here, task, delay_ms, true);
}
void MessageLoop::PostNonNestableTask(
const tracked_objects::Location& from_here, Task* task) {
PostTask_Helper(from_here, task, 0, false);
}
void MessageLoop::PostNonNestableDelayedTask(
const tracked_objects::Location& from_here, Task* task, int delay_ms) {
PostTask_Helper(from_here, task, delay_ms, false);
}
void MessageLoop::PostIdleTask(
const tracked_objects::Location& from_here, Task* task) {
DCHECK(current() == this);
task->SetBirthPlace(from_here);
PendingTask pending_task(task, false);
deferred_non_nestable_work_queue_.push(pending_task);
}
// Possibly called on a background thread!
void MessageLoop::PostTask_Helper(
const tracked_objects::Location& from_here, Task* task, int delay_ms,
bool nestable) {
task->SetBirthPlace(from_here);
PendingTask pending_task(task, nestable);
if (delay_ms > 0) {
pending_task.delayed_run_time =
TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
} else {
DCHECK(delay_ms == 0) << "delay should not be negative";
}
// Warning: Don't try to short-circuit, and handle this thread's tasks more
// directly, as it could starve handling of foreign threads. Put every task
// into this queue.
scoped_refptr<base::MessagePump> pump;
{
AutoLock locked(incoming_queue_lock_);
incoming_queue_.push(pending_task);
pump = pump_;
}
// Since the incoming_queue_ may contain a task that destroys this message
// loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
// We use a stack-based reference to the message pump so that we can call
// ScheduleWork outside of incoming_queue_lock_.
pump->ScheduleWork();
}
void MessageLoop::SetNestableTasksAllowed(bool allowed) {
if (nestable_tasks_allowed_ != allowed) {
nestable_tasks_allowed_ = allowed;
if (!nestable_tasks_allowed_)
return;
// Start the native pump if we are not already pumping.
pump_->ScheduleWorkForNestedLoop();
}
}
void MessageLoop::ScheduleWork() {
// Start the native pump if we are not already pumping.
pump_->ScheduleWork();
}
bool MessageLoop::NestableTasksAllowed() const {
return nestable_tasks_allowed_;
}
//------------------------------------------------------------------------------
void MessageLoop::RunTask(Task* task) {
DCHECK(nestable_tasks_allowed_);
// Execute the task and assume the worst: It is probably not reentrant.
nestable_tasks_allowed_ = false;
task->Run();
delete task;
nestable_tasks_allowed_ = true;
}
bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
if (pending_task.nestable || state_->run_depth <= run_depth_base_) {
RunTask(pending_task.task);
// Show that we ran a task (Note: a new one might arrive as a
// consequence!).
return true;
}
// We couldn't run the task now because we're in a nested message loop
// and the task isn't nestable.
deferred_non_nestable_work_queue_.push(pending_task);
return false;
}
void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
// Move to the delayed work queue. Initialize the sequence number
// before inserting into the delayed_work_queue_. The sequence number
// is used to faciliate FIFO sorting when two tasks have the same
// delayed_run_time value.
PendingTask new_pending_task(pending_task);
new_pending_task.sequence_num = next_sequence_num_++;
delayed_work_queue_.push(new_pending_task);
}
void MessageLoop::ReloadWorkQueue() {
// We can improve performance of our loading tasks from incoming_queue_ to
// work_queue_ by waiting until the last minute (work_queue_ is empty) to
// load. That reduces the number of locks-per-task significantly when our
// queues get large.
if (!work_queue_.empty())
return; // Wait till we *really* need to lock and load.
// Acquire all we can from the inter-thread queue with one lock acquisition.
{
AutoLock lock(incoming_queue_lock_);
if (incoming_queue_.empty())
return;
std::swap(incoming_queue_, work_queue_);
DCHECK(incoming_queue_.empty());
}
}
bool MessageLoop::DeletePendingTasks() {
bool did_work = !work_queue_.empty();
while (!work_queue_.empty()) {
PendingTask pending_task = work_queue_.front();
work_queue_.pop();
if (!pending_task.delayed_run_time.is_null()) {
// We want to delete delayed tasks in the same order in which they would
// normally be deleted in case of any funny dependencies between delayed
// tasks.
AddToDelayedWorkQueue(pending_task);
} else {
// TODO(darin): Delete all tasks once it is safe to do so.
// Until it is totally safe, just do it when running purify.
#ifdef PURIFY
delete pending_task.task;
#endif // PURIFY
}
}
did_work |= !deferred_non_nestable_work_queue_.empty();
while (!deferred_non_nestable_work_queue_.empty()) {
// TODO(darin): Delete all tasks once it is safe to do so.
// Until it is totaly safe, just delete them to keep purify happy.
#ifdef PURIFY
Task* task = deferred_non_nestable_work_queue_.front().task;
#endif
deferred_non_nestable_work_queue_.pop();
#ifdef PURIFY
delete task;
#endif
}
did_work |= !delayed_work_queue_.empty();
while (!delayed_work_queue_.empty()) {
Task* task = delayed_work_queue_.top().task;
delayed_work_queue_.pop();
delete task;
}
return did_work;
}
bool MessageLoop::DoWork() {
if (!nestable_tasks_allowed_) {
// Task can't be executed right now.
return false;
}
for (;;) {
ReloadWorkQueue();
if (work_queue_.empty())
break;
// Execute oldest task.
do {
PendingTask pending_task = work_queue_.front();
work_queue_.pop();
if (!pending_task.delayed_run_time.is_null()) {
AddToDelayedWorkQueue(pending_task);
// If we changed the topmost task, then it is time to re-schedule.
if (delayed_work_queue_.top().task == pending_task.task)
pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
} else {
if (DeferOrRunPendingTask(pending_task))
return true;
}
} while (!work_queue_.empty());
}
// Nothing happened.
return false;
}
bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) {
if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
*next_delayed_work_time = TimeTicks();
return false;
}
if (delayed_work_queue_.top().delayed_run_time > TimeTicks::Now()) {
*next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
return false;
}
PendingTask pending_task = delayed_work_queue_.top();
delayed_work_queue_.pop();
if (!delayed_work_queue_.empty())
*next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
return DeferOrRunPendingTask(pending_task);
}
bool MessageLoop::DoIdleWork() {
if (ProcessNextDelayedNonNestableTask())
return true;
if (state_->quit_received)
pump_->Quit();
return false;
}
//------------------------------------------------------------------------------
// MessageLoop::AutoRunState
MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
// Make the loop reference us.
previous_state_ = loop_->state_;
if (previous_state_) {
run_depth = previous_state_->run_depth + 1;
} else {
run_depth = 1;
}
loop_->state_ = this;
// Initialize the other fields:
quit_received = false;
#if defined(OS_WIN)
dispatcher = NULL;
#endif
}
MessageLoop::AutoRunState::~AutoRunState() {
loop_->state_ = previous_state_;
}
//------------------------------------------------------------------------------
// MessageLoop::PendingTask
bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
// Since the top of a priority queue is defined as the "greatest" element, we
// need to invert the comparison here. We want the smaller time to be at the
// top of the heap.
if (delayed_run_time < other.delayed_run_time)
return false;
if (delayed_run_time > other.delayed_run_time)
return true;
// If the times happen to match, then we use the sequence number to decide.
// Compare the difference to support integer roll-over.
return (sequence_num - other.sequence_num) > 0;
}
//------------------------------------------------------------------------------
// MessageLoopForUI
#if defined(OS_WIN)
void MessageLoopForUI::Run(Dispatcher* dispatcher) {
AutoRunState save_state(this);
state_->dispatcher = dispatcher;
RunHandler();
}
void MessageLoopForUI::AddObserver(Observer* observer) {
pump_win()->AddObserver(observer);
}
void MessageLoopForUI::RemoveObserver(Observer* observer) {
pump_win()->RemoveObserver(observer);
}
void MessageLoopForUI::WillProcessMessage(const MSG& message) {
pump_win()->WillProcessMessage(message);
}
void MessageLoopForUI::DidProcessMessage(const MSG& message) {
pump_win()->DidProcessMessage(message);
}
void MessageLoopForUI::PumpOutPendingPaintMessages() {
pump_ui()->PumpOutPendingPaintMessages();
}
#endif // defined(OS_WIN)
//------------------------------------------------------------------------------
// MessageLoopForIO
#if defined(OS_WIN)
void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
pump_io()->RegisterIOHandler(file, handler);
}
bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
return pump_io()->WaitForIOCompletion(timeout, filter);
}
#elif defined(OS_POSIX)
bool MessageLoopForIO::WatchFileDescriptor(int fd,
bool persistent,
Mode mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
return pump_libevent()->WatchFileDescriptor(
fd,
persistent,
static_cast<base::MessagePumpLibevent::Mode>(mode),
controller,
delegate);
}
bool
MessageLoopForIO::CatchSignal(int sig,
SignalEvent* sigevent,
SignalWatcher* delegate)
{
return pump_libevent()->CatchSignal(sig, sigevent, delegate);
}
#endif
|
/* Convert.cc
*Hilfsprogramm
*
*Bereitet die gegebenen Daten in eine
*f�r xpress geeignete Form auf
*
*Ben�tigt
*-basis/Load.giv (Min und Maxfrequenzen + Kanten)
*-basis/Pool.giv (Linienpool)
*-Pool-cost.giv (Kosten)
*
*Ausgabe
*"moseldaten" in der Form
*
*nr_lines: ?
*nr_edges: ?
*A:[?
*?
*?]
*cost:[?]
*Min:[?]
*Max:[?]
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <set>
#include <algorithm>
#include <string>
#include "../../essentials/config/config.h"
using namespace std;
struct od_entry
{
od_entry(unsigned short a, unsigned short b, double value)
{
i = a;
j = b;
val = value;
}
unsigned short i;
unsigned short j;
double val;
};
struct edge
{
edge(unsigned short i, unsigned short j)
{
s = i;
t = j;
};
unsigned short s;
unsigned short t;
};
int main(void)
{
cout << "Begin reading configuration" << endl;
config::from_file("basis/Config.cnf", false);
string edge_file_name = config::get_string_value("default_edges_file");
string load_file_name = config::get_string_value("default_loads_file");
string pool_file_name = config::get_string_value("default_pool_file");
string pool_cost_file_name = config::get_string_value("default_pool_cost_file");
string od_file_name = config::get_string_value("default_od_file");
int passengers_per_vehicle = atoi(config::get_string_value("gen_passengers_per_vehicle").c_str());
string log_level = config::get_string_value("console_log_level");
transform(log_level.begin(), log_level.end(), log_level.begin(), ::toupper);
bool verbose_output = log_level.compare("DEBUG") == 0;
int timelimit = config::get_integer_value("lc_timelimit");
int thread_limit = config::get_integer_value("lc_threads");
double mip_gap = config::get_double_value("lc_mip_gap");
bool write_lp_file = config::get_bool_value("lc_write_lp_file");
cout << "Finished reading configuration" << endl;
cout << "Begin reading input data" << endl;
int temp;
string text;
int nr_lines;
int nr_edges;
int L[3000][500];
vector<edge> edges;
vector<set<unsigned short> > line_knots;
int Min[3000];
int Max[3000];
double cost[3000];
vector<od_entry> OD;
size_t pos;
//Empty matrices
for (int i=0; i<=2999; i++)
for(int j=0; j<=499; j++)
{
L[i][j]=0;
//OD[i][j]=0;
}
if (verbose_output) {
cout << "Reading in edges..." << flush;
}
ifstream edgef (edge_file_name.c_str());
int source, sink;
while (!edgef.eof())
{
getline(edgef,text);
if(text!=""&&(text.c_str())[0]>=48&&(text.c_str())[0]<=57)
{
nr_edges=atoi(text.c_str());
pos=text.find(";");
text=text.substr(pos+1);
source = atoi(text.c_str());
pos=text.find(";");
text=text.substr(pos+1);
sink = atoi(text.c_str());
edge e(source,sink);
edges.push_back(e);
/*
pos=text.find(";");
text=text.substr(pos+1);
cost[nr_edges-1] = atof(text.c_str());
pos=text.find(";");
text=text.substr(pos+1);
Min[nr_edges-1]=atoi(text.c_str());
pos=text.find(";");
text=text.substr(pos+1);
Max[nr_edges-1]=atoi(text.c_str());
*/
}
}
edgef.close();
ifstream load(load_file_name.c_str());
while (!load.eof())
{
getline(load,text);
if(text!=""&&(text.c_str())[0]>=48&&(text.c_str())[0]<=57)
{
nr_edges=atoi(text.c_str());
pos=text.find(";");
text=text.substr(pos+1);
pos=text.find(";");
text=text.substr(pos+1);
Min[nr_edges-1]=atoi(text.c_str());
pos=text.find(";");
text=text.substr(pos+1);
Max[nr_edges-1]=atoi(text.c_str());
}
}
load.close();
if (verbose_output) {
cout << "done." << endl << flush;
}
ifstream pool (pool_file_name.c_str());
int last_line_number = 0;
int control = 1;
if (verbose_output) {
cout << "Reading in lines..." << flush;
}
while(!pool.eof())
{
getline(pool,text);
if(text!=""&&(text.c_str())[0]>=48&&(text.c_str())[0]<=57)
{
nr_lines=atoi(text.c_str());
if (last_line_number != nr_lines)
{
last_line_number = nr_lines;
set<unsigned short> temp_set;
line_knots.push_back(temp_set);
control = 1;
}
pos=text.find(";");
text=text.substr(pos+1);
if (atoi(text.c_str()) != control)
{
cout<<"ERROR: No consistent numbering in line "<<last_line_number<<"\n";
exit(1);
}
else
++control;
pos=text.find(";");
text=text.substr(pos+1);
temp=atoi(text.c_str());
edge e = edges[temp-1];
line_knots[nr_lines-1].insert(e.s);
line_knots[nr_lines-1].insert(e.t);
L[nr_lines-1][temp-1]=1;
}
}
pool.close();
if (verbose_output) {
cout << "done.\nReading in line costs..." << flush;
}
ifstream poolcost(pool_cost_file_name.c_str());
while(!poolcost.eof())
{
getline(poolcost,text);
if(text!=""&&(text.c_str())[0]>=48&&(text.c_str())[0]<=57)
{
nr_lines=atoi(text.c_str());
pos=text.find(";");
text=text.substr(pos+1);
pos=text.find(";");
text=text.substr(pos+1);
cost[nr_lines-1] = atof(text.c_str());
}
}
poolcost.close();
if (verbose_output) {
cout << "done.\n" << flush;
}
ifstream od_file (od_file_name.c_str());
int i_pos;
int j_pos;
if (verbose_output) {
cout << "Reading in OD matrix..." << flush;
}
while (!od_file.eof())
{
getline(od_file,text);
if(text!=""&&(text.c_str())[0]>=48&&(text.c_str())[0]<=57)
{
i_pos=atoi(text.c_str());
pos=text.find(";");
text=text.substr(pos+1);
j_pos = atoi(text.c_str());
pos=text.find(";");
text=text.substr(pos+1);
od_entry e(i_pos-1,j_pos-1,atof(text.c_str()));
OD.push_back(e);
}
}
od_file.close();
if (verbose_output) {
cout << "done.\n" << flush;
}
//Alle Daten fertig eingelesen!
//Beginne jetzt, die Datei zu schreiben
cout << "Finished reading input data" << endl;
cout << "Begin computing line concept game" << endl;
if (verbose_output) {
cout << "Begin writing mosel input data" << endl;
}
ofstream out("line-planning/Moseldaten");
out << "Linienzahl: " << nr_lines << endl;
out << "Kantenzahl: " << nr_edges << endl;
out << "ODsize: " << OD.size() << endl;
out << "timelimit: " << timelimit << endl;
out << "threadlimit: " << thread_limit << endl;
out << "outputMessages: " << verbose_output << endl;
out << "mipGap: " << mip_gap << endl;
out << "writeLpFile: " << write_lp_file << endl;
if (verbose_output) {
cout<<"Edge-path incidence matrix...";
}
out<<"H:[";
for (int i=0; i<nr_lines; i++)
{
for (int j=0; j<nr_edges; j++)
{
out<<L[i][j];
if (j!=nr_edges-1||i!=nr_edges-1)
out<<" ";
}
if (i!=nr_lines-1) out<<endl;
}
out<<"]"<<endl;
if (verbose_output) {
cout << "done.\nCosts...";
}
out<<"cost:[";
for (int i=0; i<nr_lines; i++)
{
out<<cost[i];
if (i!=nr_lines-1) out<<" ";
}
out<<"]"<<endl;
if (verbose_output) {
cout << "done.\nMin values...";
}
out<<"Min:[";
for (int i=0; i<nr_edges; i++)
{
out<<Min[i];
if (i!=nr_edges-1) out<<" ";
}
out<<"]"<<endl;
if (verbose_output) {
cout << "done.\nMax values...";
}
out<<"Max:[";
for (int i=0; i<nr_edges; i++)
{
out<<Max[i];
if (i!=nr_edges-1) out<<" ";
}
out<<"]"<<endl;
if (verbose_output) {
cout << "done.\nOD-pair-path matrix...";
}
vector<bool> feasible(OD.size());
out<<"K:[";
for (unsigned int i=0; i<OD.size(); i++)
{
feasible[i] = false;
for (int j=0; j<nr_lines; j++)
{
if ( line_knots[j].find((OD[i]).i)!=line_knots[j].end() && line_knots[j].find((OD[i]).j) != line_knots[j].end())
{
out<<"1";
feasible[i] = true;
}
else
out<<"0";
if (j!=nr_lines-1||i!=OD.size()-1)
out<<" ";
}
if (i!=OD.size()-1) out<<endl;
}
out<<"]"<<endl;
if (verbose_output) {
cout << "done.\nOD min values...";
}
//search for largest OD-Value
int max_od = 0;
for (unsigned int i=0; i<OD.size(); ++i)
if (max_od < OD[i].val)
max_od = OD[i].val;
out<<"OD:[";
for (unsigned int i=0; i<OD.size(); ++i)
{
//only consider the most important values
if (/*OD[i].val >= 0.5 * max_od && */feasible[i])
out<<(OD[i].val-1)/ passengers_per_vehicle + 1;
else
out<<"0";
if (i!=OD.size()-1) out<<" ";
}
out<<"]\n";
if (verbose_output) {
cout << "done.\nLP formulation is ready to go!\n";
}
out.close();
return 0;
}
|
#include <ege/flow/parallel-nucleus.hxx>
namespace ege
{
namespace flow
{
ParallelNucleus::ParallelNucleus(std::shared_ptr<SyncExecutionQueue> queue, unsigned numberOfThreads):
EnqueueExecutor(queue),
queue(queue),
numberOfThreads(numberOfThreads),
threads([queue, numberOfThreads]() -> ExecutorThread**
{
ExecutorThread** array = new ExecutorThread*[numberOfThreads];
for (unsigned i = 0; i < numberOfThreads; ++i)
array[i] = new ExecutorThread(queue);
return array;
} ())
{
for (unsigned i = 0; i < numberOfThreads; ++i)
threads[i]->start();
}
ParallelNucleus::ParallelNucleus(unsigned numberOfThreads):
ParallelNucleus(std::shared_ptr<SyncExecutionQueue>(new SyncExecutionQueue), numberOfThreads)
{
}
ParallelNucleus::~ParallelNucleus()
{
for (unsigned i = 0; i < numberOfThreads; ++i)
threads[i]->requireExecutionStop(false);
for (unsigned i = 0; i < numberOfThreads; ++i)
{
threads[i]->join();
delete threads[i];
}
delete threads;
}
unsigned ParallelNucleus::getNumberOfThreads() const noexcept
{
return numberOfThreads;
}
}
}
|
#include "kalman_filter.h"
#include <iostream>
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::cout;
using std::endl;
KalmanFilter::KalmanFilter() {}
KalmanFilter::~KalmanFilter() {}
void KalmanFilter::Init(VectorXd &x_in, MatrixXd &P_in, MatrixXd &F_in,
MatrixXd &H_in, MatrixXd &R_in, MatrixXd &Q_in) {
x_ = x_in;
P_ = P_in;
F_ = F_in;
H_ = H_in;
R_ = R_in;
Q_ = Q_in;
}
void KalmanFilter::Predict() {
/**
* TODO: predict the state
*/
x_ = F_ * x_ ;
MatrixXd Ft = F_.transpose();
P_ = F_ * P_ * Ft + Q_;
}
VectorXd CartesianToPolarCalculation(const VectorXd &x_){
float px,py,vx,vy;
px = x_[0];
py = x_[1];
vx = x_[2];
vy = x_[3];
double rho;
double phi;
double rho_dot;
rho = sqrt(px*px + py*py);
phi = atan2(py, px);
// To eliminate DIV by zero during rho_dot the derivative,
// assign minimum value to rho
if(rho < 0.000001)
{
rho = 0.000001;
}
rho_dot = (px*vx + py*vy)/rho;
VectorXd z_pred = VectorXd(3);
z_pred << rho, phi, rho_dot;
return z_pred;
}
// Standard Kalman Filter
void KalmanFilter::Update(const VectorXd &z) {
/**
* TODO: update the state by using Kalman Filter equations
*/
MatrixXd Ht = H_.transpose();
MatrixXd P_Ht = P_ * Ht;
MatrixXd S = H_ * P_Ht + R_;
MatrixXd Si = S.inverse();
MatrixXd K = P_Ht * Si;
VectorXd y = z - H_ * x_;
// New state values are
x_ = x_ + (K * y);
int x_size = x_.size();
MatrixXd I = MatrixXd::Identity(x_size, x_size);
P_ = (I - K * H_) * P_;
}
void KalmanFilter::UpdateEKF(const VectorXd &z) {
/**
TODO:
* update the state by using Extended Kalman Filter equations
*/
/*
* Radar measurements conversion from (x,y,vx,vy) - cartesian
* to (rho,phi,rho_dot) - polar coordinates
*/
VectorXd z_p = CartesianToPolarCalculation(x_); // For the Prediction values
double px = x_(0);
double py = x_(1);
double vx = x_(2);
double vy = x_(3);
VectorXd y = z - z_p;
double rho = sqrt(px*px + py*py);
double theta = atan2(py, px);
double rho_dot = (px*vx + py*vy) / rho;
VectorXd h = VectorXd(3);
h << rho, theta, rho_dot;
cout << "H : " << h << endl;
// the values in EKF tend to be between PI and -PI hence normalize them
// for effectveness
while ( M_PI < y(1)){
y(1) -= 2*M_PI;
}
while ( -M_PI > y(1)){
y(1) += 2*M_PI;
}
// Kalman Gain calculations
MatrixXd Ht = H_.transpose();
MatrixXd S = H_ * P_ * Ht + R_;
MatrixXd Si = S.inverse();
MatrixXd K = P_ * Ht * Si;
// State update
x_ = x_ + (K * y);
int x_size = x_.size();
MatrixXd I = MatrixXd::Identity(x_size, x_size);
P_ = (I - K * H_) * P_;
}
|
#include "neopch.h"
#include "Neon/Editor/Panels/InspectorPanel.h"
#include "Neon/Renderer/Mesh.h"
#include "Neon/Renderer/Renderer.h"
#include "Neon/Renderer/SceneRenderer.h"
#include "Neon/Scene/Actor.h"
#include "Neon/Scene/Components/LightComponent.h"
#include "Neon/Scene/Components/OceanComponent.h"
#include "Neon/Scene/Components/SkeletalMeshComponent.h"
#include "Neon/Scene/Components/StaticMeshComponent.h"
#include <imgui/imgui.h>
#include <imgui/imgui_internal.h>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/quaternion.hpp>
namespace Neon
{
static bool DrawVec3Control(const std::string& label, glm::vec3& values, float resetValue = 0.f, float columnWidth = 120.f)
{
bool modified = false;
ImGuiIO& io = ImGui::GetIO();
auto boldFont = io.Fonts->Fonts[0];
ImGui::PushID(label.c_str());
ImGui::Columns(2);
ImGui::SetColumnWidth(0, columnWidth);
ImGui::Text(label.c_str());
ImGui::NextColumn();
ImGui::PushMultiItemsWidths(3, ImGui::CalcItemWidth());
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2{0, 0});
float lineHeight = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f;
ImVec2 buttonSize = {lineHeight + 3.0f, lineHeight};
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{0.8f, 0.1f, 0.15f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{0.9f, 0.2f, 0.2f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4{0.8f, 0.1f, 0.15f, 1.0f});
ImGui::PushFont(boldFont);
if (ImGui::Button("X", buttonSize))
{
values.x = resetValue;
modified = true;
}
ImGui::PopFont();
ImGui::PopStyleColor(3);
ImGui::SameLine();
modified |= ImGui::DragFloat("##X", &values.x, 0.1f, 0.0f, 0.0f, "%.2f");
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{0.2f, 0.7f, 0.2f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{0.3f, 0.8f, 0.3f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4{0.2f, 0.7f, 0.2f, 1.0f});
ImGui::PushFont(boldFont);
if (ImGui::Button("Y", buttonSize))
{
values.y = resetValue;
modified = true;
}
ImGui::PopFont();
ImGui::PopStyleColor(3);
ImGui::SameLine();
modified |= ImGui::DragFloat("##Y", &values.y, 0.1f, 0.0f, 0.0f, "%.2f");
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{0.1f, 0.25f, 0.8f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{0.2f, 0.35f, 0.9f, 1.0f});
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4{0.1f, 0.25f, 0.8f, 1.0f});
ImGui::PushFont(boldFont);
if (ImGui::Button("Z", buttonSize))
{
values.z = resetValue;
modified = true;
}
ImGui::PopFont();
ImGui::PopStyleColor(3);
ImGui::SameLine();
modified |= ImGui::DragFloat("##Z", &values.z, 0.1f, 0.0f, 0.0f, "%.2f");
ImGui::PopItemWidth();
ImGui::PopStyleVar();
ImGui::Columns(1);
ImGui::PopID();
return modified;
}
void InspectorPanel::Render() const
{
SharedRef<Actor> selectedActor = SceneRenderer::GetSelectedActor();
ImGui::Begin("Inspector");
if (selectedActor)
{
const char* name = selectedActor->GetTag().c_str();
DrawVec3Control("Translation", selectedActor->GetTranslation());
glm::vec3 originalEulerAngles = glm::degrees(glm::eulerAngles(selectedActor->GetRotation()));
if (DrawVec3Control("Rotation", originalEulerAngles))
{
// Wrap euler angles between -180 and 180 degrees
originalEulerAngles -= 360.f * glm::floor((originalEulerAngles + glm::vec3(180.f)) / 360.f);
selectedActor->GetRotation() = glm::radians(originalEulerAngles);
}
DrawVec3Control("Scale", selectedActor->GetScale());
ImGui::Spacing();
DrawActorComponents(selectedActor);
/*DrawComponent<StaticMeshComponent>("Static Mesh Component", selectedActor, [this](StaticMeshComponent& component) {
ImGui::BeginTable("##meshfiletable", 3);
ImGui::TableSetupColumn("##meshfileTitle", 0, 100);
ImGui::TableSetupColumn("##meshfile", 0, 700);
ImGui::TableSetupColumn("##meshfileButton", 0, 40);
ImGui::TableNextColumn();
ImGui::Text("File Path");
ImGui::TableNextColumn();
if (component.GetMesh())
{
ImGui::InputText("##meshfilepath", (char*)component.GetMesh()->GetFilePath().c_str(), 256,
ImGuiInputTextFlags_ReadOnly);
}
else
{
ImGui::InputText("##meshfilepath", (char*)"Null", 256, ImGuiInputTextFlags_ReadOnly);
}
ImGui::TableNextColumn();
if (ImGui::Button("...##openmesh"))
{
std::string file = Application::Get().OpenFile();
if (!file.empty())
{
RendererContext::Get()->SafeDeleteResource(StaleResourceWrapper::Create(component.GetMesh()));
component.LoadMesh(file);
}
}
ImGui::EndTable();
if (component.GetMesh() && ImGui::TreeNodeEx("Materials"))
{
RenderMeshProperties(component.GetMesh());
}
});
ImGui::Spacing();
DrawComponent<SkeletalMeshComponent>(
"Skeletal Mesh Component", selectedActor, [this](SkeletalMeshComponent& component) {
ImGui::BeginTable("##meshfiletable", 3);
ImGui::TableSetupColumn("##meshfileTitle", 0, 100);
ImGui::TableSetupColumn("##meshfile", 0, 700);
ImGui::TableSetupColumn("##meshfileButton", 0, 40);
ImGui::TableNextColumn();
ImGui::Text("File Path");
ImGui::TableNextColumn();
if (component.GetMesh())
{
ImGui::InputText("##meshfilepath", (char*)component.GetMesh()->GetFilePath().c_str(), 256,
ImGuiInputTextFlags_ReadOnly);
}
else
{
ImGui::InputText("##meshfilepath", (char*)"Null", 256, ImGuiInputTextFlags_ReadOnly);
}
ImGui::TableNextColumn();
if (ImGui::Button("...##openmesh"))
{
std::string file = Application::Get().OpenFile();
if (!file.empty())
{
RendererContext::Get()->SafeDeleteResource(StaleResourceWrapper::Create(component.GetMesh()));
component.LoadMesh(file);
}
}
ImGui::EndTable();
if (component.GetMesh() && ImGui::TreeNodeEx("Materials"))
{
RenderMeshProperties(component.GetMesh());
}
});
ImGui::Spacing();
DrawComponent<LightComponent>("Light Component", selectedActor, [](LightComponent& component) {
});
DrawComponent<OceanComponent>("Ocean Component", selectedActor, [](OceanComponent& component) {
});
ImGui::Spacing();*/
ImGui::Separator();
float windowSizeX = ImGui::GetContentRegionAvail().x;
ImGui::Indent((windowSizeX - 300.f) / 2.f);
if (ImGui::Button("Add Component", ImVec2(300, 30)))
{
ImGui::OpenPopup("AddComponentPanel");
}
if (ImGui::BeginPopup("AddComponentPanel"))
{
if (ImGui::Button("StaticMeshComponent"))
{
selectedActor->AddComponent<StaticMeshComponent>(selectedActor.Ptr());
ImGui::CloseCurrentPopup();
}
if (ImGui::Button("SkeletalMeshComponent"))
{
selectedActor->AddComponent<SkeletalMeshComponent>(selectedActor.Ptr());
ImGui::CloseCurrentPopup();
}
if (ImGui::Button("LightComponent"))
{
selectedActor->AddComponent<LightComponent>(selectedActor.Ptr());
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
}
ImGui::End();
}
void InspectorPanel::DrawActorComponents(SharedRef<Actor> actor) const
{
for (auto& component : actor->GetActorComponents())
{
ImVec2 contentRegionAvailable = ImGui::GetContentRegionAvail();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2{4, 4});
float lineHeight = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f;
ImGui::Separator();
const ImGuiTreeNodeFlags treeNodeFlags = ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_Framed |
ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_AllowItemOverlap |
ImGuiTreeNodeFlags_FramePadding;
bool open = ImGui::TreeNodeEx((void*)typeid(component).hash_code(), treeNodeFlags, typeid(component).name());
ImGui::PopStyleVar();
ImGui::SameLine(contentRegionAvailable.x - lineHeight * 0.5f);
if (ImGui::Button("::", ImVec2{lineHeight, lineHeight}))
{
ImGui::OpenPopup("ComponentSettings");
}
bool removeComponent = false;
if (ImGui::BeginPopup("ComponentSettings"))
{
if (ImGui::MenuItem("Remove component"))
{
removeComponent = true;
}
ImGui::EndPopup();
}
if (open)
{
component->RenderGui();
ImGui::TreePop();
}
if (removeComponent)
{
actor->RemoveComponent(component);
}
ImGui::Spacing();
}
}
} // namespace Neon
|
// This file implements the IDebugStackFrame Interface and Gateway for Python.
// Generated by makegw.py
#include "stdafx.h"
#include "PyIDebugStackFrame.h"
// @doc - This file contains autoduck documentation
// ---------------------------------------------------
//
// Interface Implementation
PyIDebugStackFrame::PyIDebugStackFrame(IUnknown *pdisp) : PyIUnknown(pdisp) { ob_type = &type; }
PyIDebugStackFrame::~PyIDebugStackFrame() {}
/* static */ IDebugStackFrame *PyIDebugStackFrame::GetI(PyObject *self)
{
return (IDebugStackFrame *)PyIUnknown::GetI(self);
}
// @pymethod |PyIDebugStackFrame|GetCodeContext|Returns the current code context associated with the stack frame.
PyObject *PyIDebugStackFrame::GetCodeContext(PyObject *self, PyObject *args)
{
IDebugStackFrame *pIDSF = GetI(self);
if (pIDSF == NULL)
return NULL;
IDebugCodeContext *ppcc;
if (!PyArg_ParseTuple(args, ":GetCodeContext"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIDSF->GetCodeContext(&ppcc);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(ppcc, IID_IDebugCodeContext, FALSE);
}
// @pymethod <o unicode>|PyIDebugStackFrame|GetDescriptionString|Returns a short or long textual description of the
// stack frame.
PyObject *PyIDebugStackFrame::GetDescriptionString(PyObject *self, PyObject *args)
{
IDebugStackFrame *pIDSF = GetI(self);
if (pIDSF == NULL)
return NULL;
BSTR pbstrDescription;
BOOL flong;
// @pyparm int|fLong||If false, provide only the name of the function associated with the stack frame. When true it
// may also provide the parameter(s) to the function or whatever else is relevant.
if (!PyArg_ParseTuple(args, "i:GetDescriptionString", &flong))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIDSF->GetDescriptionString(flong, &pbstrDescription);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
PyObject *obpbstrDescription;
obpbstrDescription = MakeBstrToObj(pbstrDescription);
PyObject *pyretval = Py_BuildValue("O", obpbstrDescription);
Py_XDECREF(obpbstrDescription);
return pyretval;
}
// @pymethod <o unicode>|PyIDebugStackFrame|GetLanguageString|Returns a short or long textual description of the
// language.
PyObject *PyIDebugStackFrame::GetLanguageString(PyObject *self, PyObject *args)
{
IDebugStackFrame *pIDSF = GetI(self);
if (pIDSF == NULL)
return NULL;
BSTR pbstrDescription;
BOOL flong;
// @pyparm int|fLong||If False, just the language name should be provided, eg, "Python". If True a full product
// description may be provided (eg, "Python 1.4 ActiveX Debugging Host")
if (!PyArg_ParseTuple(args, "i:GetLanguageString", &flong))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIDSF->GetLanguageString(flong, &pbstrDescription);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
PyObject *obpbstrDescription;
obpbstrDescription = MakeBstrToObj(pbstrDescription);
PyObject *pyretval = Py_BuildValue("O", obpbstrDescription);
Py_XDECREF(obpbstrDescription);
return pyretval;
}
// @pymethod <o PyIDebugApplicationThread>|PyIDebugStackFrame|GetThread|Returns the thread associated with this stack
// frame.
PyObject *PyIDebugStackFrame::GetThread(PyObject *self, PyObject *args)
{
IDebugStackFrame *pIDSF = GetI(self);
if (pIDSF == NULL)
return NULL;
IDebugApplicationThread *ppat;
if (!PyArg_ParseTuple(args, ":GetThread"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIDSF->GetThread(&ppat);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(ppat, IID_IDebugApplicationThread, FALSE);
}
// @pymethod <o PyIDebugProperty>|PyIDebugStackFrame|GetDebugProperty|Returns the debug property.
PyObject *PyIDebugStackFrame::GetDebugProperty(PyObject *self, PyObject *args)
{
IDebugStackFrame *pIDSF = GetI(self);
if (pIDSF == NULL)
return NULL;
IDebugProperty *ppdp;
if (!PyArg_ParseTuple(args, ":GetDebugProperty"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIDSF->GetDebugProperty(&ppdp);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(ppdp, IID_IDebugProperty, FALSE);
}
// @object PyIDebugStackFrame|Description of the interface
static struct PyMethodDef PyIDebugStackFrame_methods[] = {
{"GetCodeContext", PyIDebugStackFrame::GetCodeContext,
1}, // @pymeth GetCodeContext|Returns the current code context associated with the stack frame.
{"GetDescriptionString", PyIDebugStackFrame::GetDescriptionString,
1}, // @pymeth GetDescriptionString|Returns a short or long textual description of the stack frame.
{"GetLanguageString", PyIDebugStackFrame::GetLanguageString,
1}, // @pymeth GetLanguageString|Returns a short or long textual description of the language.
{"GetThread", PyIDebugStackFrame::GetThread,
1}, // @pymeth GetThread|Returns the thread associated with this stack frame.
{"GetDebugProperty", PyIDebugStackFrame::GetDebugProperty,
1}, // @pymeth GetThread|Returns the debug property object associated with this stack frame.
{NULL}};
PyComTypeObject PyIDebugStackFrame::type("PyIDebugStackFrame", &PyIUnknown::type, sizeof(PyIDebugStackFrame),
PyIDebugStackFrame_methods, GET_PYCOM_CTOR(PyIDebugStackFrame));
// ---------------------------------------------------
//
// Gateway Implementation
STDMETHODIMP PyGDebugStackFrame::GetCodeContext(
/* [out] */ IDebugCodeContext __RPC_FAR *__RPC_FAR *ppcc)
{
PY_GATEWAY_METHOD;
if (ppcc == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("GetCodeContext", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obppcc;
if (!PyArg_Parse(result, "O", &obppcc))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obppcc, IID_IDebugCodeContext, (void **)ppcc, FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGDebugStackFrame::GetDescriptionString(
/* [in] */ BOOL fLong,
/* [out] */ BSTR __RPC_FAR *pbstrDescription)
{
PY_GATEWAY_METHOD;
PyObject *result;
HRESULT hr = InvokeViaPolicy("GetDescriptionString", &result, "i", fLong);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obpbstrDescription;
if (!PyArg_Parse(result, "O", &obpbstrDescription))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_BstrFromPyObject(obpbstrDescription, pbstrDescription))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGDebugStackFrame::GetLanguageString(
/* [in] */ BOOL fLong,
/* [out] */ BSTR __RPC_FAR *pbstrDescription)
{
PY_GATEWAY_METHOD;
PyObject *result;
HRESULT hr = InvokeViaPolicy("GetLanguageString", &result, "i", fLong);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obpbstrDescription;
if (!PyArg_Parse(result, "O", &obpbstrDescription))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_BstrFromPyObject(obpbstrDescription, pbstrDescription))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGDebugStackFrame::GetThread(
/* [out] */ IDebugApplicationThread __RPC_FAR *__RPC_FAR *ppat)
{
PY_GATEWAY_METHOD;
if (ppat == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("GetThread", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obppat;
if (!PyArg_Parse(result, "O", &obppat))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obppat, IID_IDebugApplicationThread, (void **)ppat, FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGDebugStackFrame::GetDebugProperty(
/* [out] */ IDebugProperty __RPC_FAR *__RPC_FAR *ppdp)
{
PY_GATEWAY_METHOD;
if (ppdp == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("GetDebugProperty", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
if (!PyCom_InterfaceFromPyInstanceOrObject(result, IID_IDebugProperty, (void **)ppdp, FALSE /* bNoneOK */))
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
|
/*
//@HEADER
// ************************************************************************
//
// KokkosKernels 0.9: Linear Algebra and Graph Kernels
// Copyright 2017 Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Siva Rajamanickam (srajama@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#define KOKKOSKERNELS_IMPL_COMPILE_LIBRARY true
#include "KokkosKernels_config.h"
#if defined (KOKKOSKERNELS_INST_KOKKOS_COMPLEX_FLOAT_) \
&& defined (KOKKOSKERNELS_INST_LAYOUTRIGHT) \
&& defined (KOKKOSKERNELS_INST_EXECSPACE_OPENMP) \
&& defined (KOKKOSKERNELS_INST_MEMSPACE_HBWSPACE) \
&& defined (KOKKOSKERNELS_INST_MEMSPACE_HOSTSPACE) \
&& defined (KOKKOSKERNELS_INST_ORDINAL_INT) \
&& defined (KOKKOSKERNELS_INST_OFFSET_INT)
#include "KokkosSparse_spgemm_symbolic_spec.hpp"
namespace KokkosSparse {
namespace Impl {
KOKKOSSPARSE_SPGEMM_SYMBOLIC_ETI_SPEC_INST(Kokkos::complex<float>, int, int, Kokkos::LayoutRight, Kokkos::OpenMP, Kokkos::Experimental::HBWSpace, Kokkos::HostSpace)
} // Impl
} // KokkosSparse
#endif
|
/*
* This file is a part of the open source stm32plus library.
* Copyright (c) 2011,2012,2013 Andy Brown <www.andybrown.me.uk>
* Please see website for licensing terms.
*/
#include "config/stm32plus.h"
#include "config/button.h"
#include "config/exti.h"
using namespace stm32plus;
/**
* Button demo that uses EXTI interrupts to signal that
* the button is pressed. EXTI allows you to process
* input from GPIO pins asynchronously.
*
* This demo assumes that you have a button on PA8 and
* an LED on PF6. The LED will light as long as the
* button is held down.
*
* An Exti8 (external interrupt) is attached to PA8 and
* is configured to trigger on both rising (pressed)
* and falling (released) edges.
*
* To use this demo on the STM32F4DISCOVERY board you
* will need to make the following changes to target the
* onboard button and LEDs:
*
* LED_PIN to 13
* BUTTON_PIN to 0
* GpioF... to GpioD...
* Exti8 to Exit0
*
* Compatible MCU:
* STM32F1
* STM32F4
*
* Tested on devices:
* STM32F103ZET6
* STM32F407VGT6
*/
class ExtiTest {
protected:
volatile bool _stateChanged;
enum {
LED_PIN = 6,
BUTTON_PIN = 8
};
public:
void run() {
// initialise the LED and button pins
GpioF<DefaultDigitalOutputFeature<LED_PIN> > pf;
GpioA<DefaultDigitalInputFeature<BUTTON_PIN> > pa;
// enable EXTI on the button pin and subscribe to interrupts
Exti8 exti(EXTI_Mode_Interrupt,EXTI_Trigger_Rising_Falling,pa[BUTTON_PIN]);
exti.ExtiInterruptEventSender.insertSubscriber(
ExtiInterruptEventSourceSlot::bind(this,&ExtiTest::onInterrupt)
);
// lights off (this LED is active low, i.e. PF6 is a sink)
pf[LED_PIN].set();
// main loop
for(;;) {
_stateChanged=false; // race conditition, but it's demo code...
// wait for the interrupt to tell us that there's been a button press/release
while(!_stateChanged);
// act on the new state and reset for the next run
pf[LED_PIN].setState(pa[BUTTON_PIN].read());
}
}
/**
* Interrupt callback from the EXTI interrupt
*/
void onInterrupt(uint8_t /* extiLine */) {
_stateChanged=true;
}
};
/*
* Main entry point
*/
int main() {
ExtiTest test;
test.run();
// not reached
return 0;
}
|
#ifndef STAN_MATH_REV_ARR_FUN_TO_VAR_HPP
#define STAN_MATH_REV_ARR_FUN_TO_VAR_HPP
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/scal/fun/to_var.hpp>
#include <vector>
namespace stan {
namespace math {
/**
* Converts argument to an automatic differentiation variable.
*
* Returns a var variable with the input value.
*
* @param[in] v A std::vector<double>
* @return A std::vector<var> with the values set
*/
inline std::vector<var> to_var(const std::vector<double>& v) {
std::vector<var> var_vector(v.size());
for (size_t n = 0; n < v.size(); n++)
var_vector[n] = v[n];
return var_vector;
}
/**
* Converts argument to an automatic differentiation variable.
*
* Returns a var variable with the input value.
*
* @param[in] v A std::vector<var>
* @return A std::vector<var>
*/
inline std::vector<var> to_var(const std::vector<var>& v) { return v; }
} // namespace math
} // namespace stan
#endif
|
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 "org/apache/http/impl/cookie/RFC2965VersionAttributeHandler.h"
#include "elastos/core/StringUtils.h"
#include "elastos/utility/CStringTokenizer.h"
#include "elastos/utility/logging/Logger.h"
using Elastos::Core::StringUtils;
using Elastos::Utility::IStringTokenizer;
using Elastos::Utility::CStringTokenizer;
using Elastos::Utility::Logging::Logger;
using Org::Apache::Http::Cookie::EIID_ICookieAttributeHandler;
using Org::Apache::Http::Cookie::IClientCookie;
using Org::Apache::Http::Cookie::ISetCookie;
using Org::Apache::Http::Cookie::ISetCookie2;
namespace Org {
namespace Apache {
namespace Http {
namespace Impl {
namespace Cookie {
CAR_INTERFACE_IMPL(RFC2965VersionAttributeHandler, Object, ICookieAttributeHandler)
ECode RFC2965VersionAttributeHandler::Parse(
/* [in] */ ISetCookie* cookie,
/* [in] */ const String& value)
{
if (cookie == NULL) {
Logger::E("RFC2965VersionAttributeHandler", "Cookie may not be null");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
if (value.IsNull()) {
Logger::E("RFC2965VersionAttributeHandler", "Missing value for version attribute");
return E_MALFORMED_COOKIE_EXCEPTION;
}
Int32 version = -1;
// try {
version = StringUtils::ParseInt32(value);
// } catch (NumberFormatException e) {
// version = -1;
// }
if (version < 0) {
Logger::E("RFC2965VersionAttributeHandler", "Invalid cookie version.");
return E_MALFORMED_COOKIE_EXCEPTION;
}
return cookie->SetVersion(version);
}
ECode RFC2965VersionAttributeHandler::Validate(
/* [in] */ ICookie* cookie,
/* [in] */ ICookieOrigin* origin)
{
if (cookie == NULL) {
Logger::E("RFC2965VersionAttributeHandler", "Cookie may not be null");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
AutoPtr<ISetCookie2> cookie2 = ISetCookie2::Probe(cookie);
if (cookie2 != NULL) {
AutoPtr<IClientCookie> clientCookie = IClientCookie::Probe(cookie);
Boolean contain;
if (clientCookie != NULL && (clientCookie->ContainsAttribute(IClientCookie::VERSION_ATTR, &contain), !contain)) {
Logger::E("RFC2965VersionAttributeHandler", "Violates RFC 2965. Version attribute is required.");
return E_MALFORMED_COOKIE_EXCEPTION;
}
}
return NOERROR;
}
ECode RFC2965VersionAttributeHandler::Match(
/* [in] */ ICookie* cookie,
/* [in] */ ICookieOrigin* origin,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
*result = TRUE;
return NOERROR;
}
} // namespace Cookie
} // namespace Impl
} // namespace Http
} // namespace Apache
} // namespace Org
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/codecommit/model/PostCommentReplyRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::CodeCommit::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
PostCommentReplyRequest::PostCommentReplyRequest() :
m_inReplyToHasBeenSet(false),
m_clientRequestToken(Aws::Utils::UUID::RandomUUID()),
m_clientRequestTokenHasBeenSet(true),
m_contentHasBeenSet(false)
{
}
Aws::String PostCommentReplyRequest::SerializePayload() const
{
JsonValue payload;
if(m_inReplyToHasBeenSet)
{
payload.WithString("inReplyTo", m_inReplyTo);
}
if(m_clientRequestTokenHasBeenSet)
{
payload.WithString("clientRequestToken", m_clientRequestToken);
}
if(m_contentHasBeenSet)
{
payload.WithString("content", m_content);
}
return payload.WriteReadable();
}
Aws::Http::HeaderValueCollection PostCommentReplyRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "CodeCommit_20150413.PostCommentReply"));
return headers;
}
|
/// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// 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:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// 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.
#ifndef VMEXIT_LOOP_ENTRY_HPP
#define VMEXIT_LOOP_ENTRY_HPP
#include <bsl/exit_code.hpp>
namespace mk
{
/// <!-- description -->
/// @brief Executes the main VMExit loop
///
/// <!-- inputs/outputs -->
/// @return Returns bsl::exit_success on success and bsl::exit_failure
/// otherwise
///
extern "C" [[nodiscard]] auto vmexit_loop_entry() noexcept -> bsl::exit_code;
}
#endif
|
#include "../raycaster/hittable/object.h"
#include "../raycaster/geometry.h"
#include "../raycaster/hittable/object.h"
#include "../raycaster/accelerator/bvh.h"
#include "../scene.h"
#include "../../image/image.h"
#include "../../math/random.h"
#include "../camera.h"
#include "../raycaster/caster.h"
#include "../raycaster/material.h"
#include "../../thread/threadpool.h"
#include "samples.h"
Scene Samples::BasicSphere(std::atomic<i32>* progress)
{
Geometry::RegisterGeometry("Sphere", new Sphere());
Material* earthMat = Material::RegisterMaterial("EarthLambertian", new Lambertian("earthmap.bmp"));
Material* sunMat = Material::RegisterMaterial("SunDiffuse", new DiffuseLight(Vector3(1.0f, 0.83f, 0.25f), 1.0f));
Object* earth = Object::CreateSphere(Vector3(0, 0, 0), 1, earthMat);
Object* sun = Object::CreateSphere(Vector3(200, 1, 0), 100, sunMat);
progress->store(50);
BVHNode* tree = BVHNode::NewBVHTree({ sun, earth });
Scene world;
world.name = "SimpleSpaceEarth";
world.top = tree;
world.objList = { sun, earth };
world.sky = nullptr; // = Black
world.renderCamera = new Camera(Vector3(0, 0, 250), Vector3(50, 0, 0), Vector3(0, 1, 0), 15.0f, 16.0f / 9.0f, .01f, 250);
progress->store(100);
return world;
}
Scene Samples::SingleSphere(std::atomic<i32>* progress)
{
Geometry::RegisterGeometry("Sphere", new Sphere());
Material* earthMat = Material::RegisterMaterial("EarthLambertian", new Lambertian("earthmap.bmp"));
Object* earth = Object::CreateSphere(Vector3(0, 0, 0), 1, earthMat);
progress->store(50);
BVHNode* tree = BVHNode::NewBVHTree({ earth });
Scene world;
world.name = "SingleEarth";
world.top = tree;
world.objList = { earth };
world.sky = new ColorTexture(Vector3(0.1f, 0.1f, 0.1f));
world.renderCamera = new Camera(Vector3(15, 15, 15), Vector3(0, 0, 0), Vector3(0, 1, 0), 45.0f, 16.0f / 9.0f, .01f, 250);
progress->store(100);
return world;
}
Scene Samples::ColoredSpheres(std::atomic<i32>* progress)
{
Geometry::RegisterGeometry("Sphere", new Sphere());
Material* r = Material::RegisterMaterial("Red", new Lambertian(Vector3(1, 0, 0)));
Material* g = Material::RegisterMaterial("Green", new Lambertian(Vector3(0, 1, 0)));
Material* b = Material::RegisterMaterial("Blue", new Lambertian(Vector3(0, 1, 1)));
Material* c = Material::RegisterMaterial("Check", new Lambertian(Vector3(0, 0, 0), Vector3(1, 1, 1)));
Material* l = Material::RegisterMaterial("Light", new DiffuseLight(Vector3(1, 1, 1), 2.0f));
Object* s0 = Object::CreateSphere(Vector3(0, 0, 0), 1, r);
Object* s1 = Object::CreateSphere(Vector3(2, 0, 0), 1, g);
Object* s2 = Object::CreateSphere(Vector3(-2, 0, 0), 1, b);
Object* ground = Object::CreateSphere(Vector3(0, -1001, 0), 1000, c);
Object* light = Object::CreateSphere(Vector3(-5, 5, -5), 5, l);
progress->store(50);
BVHNode* tree = BVHNode::NewBVHTree({ s0, s1, s2, ground, light });
Scene world;
world.name = "ColoredSpheres";
world.top = tree;
world.objList = { s0, s1, s2, ground, light };
world.sky = nullptr; // Black
world.renderCamera = new Camera(Vector3(10, 5, 10), Vector3(0, 0, 0), Vector3(0, 1, 0), 45.0f, 16.0f / 9.0f, .01f, sqrtf(22));
progress->store(100);
return world;
}
|
/*=============================================================================
Copyright (c) 2011-2017 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_NUMERIC_FFT_FIT_IFFT_HPP
#define SPROUT_NUMERIC_FFT_FIT_IFFT_HPP
#include <sprout/config.hpp>
#include <sprout/iterator/distance.hpp>
#include <sprout/container/traits.hpp>
#include <sprout/container/functions.hpp>
#include <sprout/numeric/fft/fixed/ifft.hpp>
#include <sprout/algorithm/fit/results.hpp>
#include <sprout/sub_array/sub_array.hpp>
#include <sprout/sub_array/sub.hpp>
#include <sprout/pit/pit.hpp>
namespace sprout {
namespace fit {
namespace detail {
template<typename ForwardIterator, typename Result>
inline SPROUT_CONSTEXPR typename sprout::fit::results::algorithm<Result>::type
ifft_impl(
ForwardIterator const& first, ForwardIterator const& last, Result const& result,
typename sprout::container_traits<Result>::difference_type offset
)
{
return sprout::sub_copy(
sprout::get_internal(sprout::fixed::ifft(first, last, result)),
offset,
offset + sprout::fit_size(result, sprout::distance(first, last))
);
}
} // namespace detail
//
// ifft
//
template<typename ForwardIterator, typename Result>
inline SPROUT_CONSTEXPR typename sprout::fit::results::algorithm<Result>::type
ifft(ForwardIterator first, ForwardIterator last, Result const& result) {
return sprout::fit::detail::ifft_impl(first, last, result, sprout::internal_begin_offset(result));
}
template<typename Result, typename ForwardIterator>
inline SPROUT_CONSTEXPR typename sprout::fixed::results::algorithm<Result>::type
ifft(ForwardIterator first, ForwardIterator last) {
return sprout::fit::ifft(first, last, sprout::pit<Result>());
}
} // namespace fit
} // namespace sprout
#endif // #ifndef SPROUT_NUMERIC_FFT_FIT_IFFT_HPP
|
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Exp.h"
#include "Convert.h"
namespace tflchef
{
void TFliteOpExp::filler(const tflite::Operator *op, TFliteImport *import,
tflchef::ModelRecipe *model_recipe) const
{
// Nothing to do with filler
}
tflchef::Operation *TFliteOpExp::build(const tflite::Operator *op, TFliteImport *import,
tflchef::ModelRecipe *model_recipe) const
{
auto operation = model_recipe->add_operation();
operation->set_type("Exp");
return operation;
}
} // namespace tflchef
|
/*
* Copyright 2021 Assured Information Security, 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.
*/
#pragma once
#include "CLIENT_ID_IMPL.hh"
#include "NT_TIB_IMPL.hh"
#include "windows/kernel/nt/structs/structs.hh"
#include <introvirt/core/memory/guest_ptr.hh>
#include <introvirt/windows/kernel/nt/types/TEB.hh>
#include <optional>
namespace introvirt {
namespace windows {
namespace nt {
template <typename PtrType>
class NtKernelImpl;
template <typename PtrType>
class TEB_IMPL final : public TEB {
public:
const NT_TIB& NtTib() const override;
const CLIENT_ID& ClientId() const override;
WinError LastErrorValue() const override;
void LastErrorValue(WinError LastErrorValue) override;
NTSTATUS LastStatusValue() const override;
void LastStatusValue(NTSTATUS value) override;
GuestVirtualAddress address() const override;
TEB_IMPL(const NtKernelImpl<PtrType>& kernel, const GuestVirtualAddress& gva);
private:
const NtKernelImpl<PtrType>& kernel_;
const GuestVirtualAddress gva_;
const structs::TEB* teb_;
guest_ptr<char[]> buffer_;
mutable std::optional<NT_TIB_IMPL<PtrType>> NtTib_;
mutable std::optional<CLIENT_ID_IMPL<PtrType>> ClientId_;
};
} // namespace nt
} // namespace windows
} // namespace introvirt
|
#include<iostream>
using namespace std;
int main() {
int tc,n,k,t,d,sess_data,glob_time=0,time_diff,charge=0,flag=0;
cin>>tc;
while (tc--) {
glob_time=0;
time_diff=0;
charge=0;
flag=0;
cin>>n>>k;
while (n--) {
cin>>t>>d;
glob_time+=t;
if(flag==1){
charge+=t*d;
}
if(glob_time>=k && flag==0){
time_diff=glob_time-k;
charge+=time_diff*d;
flag=1;
}
}
cout<<charge<<"\n";
}
return 0;
}
|
/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 - 2020 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include "src/actions/disruptive/allow.h"
#include <iostream>
#include <string>
#include "modsecurity/rules_set.h"
#include "modsecurity/transaction.h"
#include "modsecurity/rule.h"
#include "src/utils/string.h"
#include "modsecurity/modsecurity.h"
namespace modsecurity {
namespace actions {
namespace disruptive {
bool Allow::init(std::string *error) {
std::string a = utils::string::tolower(m_parser_payload);
if (a == "phase") {
m_allowType = PhaseAllowType;
} else if (a == "request") {
m_allowType = RequestAllowType;
} else if (a == "") {
m_allowType = FromNowOnAllowType;
} else {
error->assign("Allow: if specified, the parameter " \
"most be: phase, request");
return false;
}
return true;
}
bool Allow::evaluate(Rule *rule, Transaction *transaction) {
ms_dbg_a(transaction, 4, "Dropping the evaluation of upcoming rules " \
"in favor of an `allow' action of type: " \
+ allowTypeToName(m_allowType));
transaction->m_allowType = m_allowType;
return true;
}
} // namespace disruptive
} // namespace actions
} // namespace modsecurity
|
/*++
Copyright (c) Microsoft Corporation All Rights Reserved
Module Name:
spdiftopo.cpp
Abstract:
Implementation of topology miniport for the spdif (internal).
--*/
#pragma warning (disable : 4127)
#include <sysvad.h>
#include "simple.h"
#include "mintopo.h"
#include "spdiftopo.h"
#include "spdiftoptable.h"
#pragma code_seg("PAGE")
//=============================================================================
NTSTATUS
PropertyHandler_SpdifTopoFilter
(
_In_ PPCPROPERTY_REQUEST PropertyRequest
)
/*++
Routine Description:
Redirects property request to miniport object
Arguments:
PropertyRequest -
Return Value:
NT status code.
--*/
{
PAGED_CODE();
ASSERT(PropertyRequest);
DPF_ENTER(("[PropertyHandler_SpdifTopoFilter]"));
// PropertryRequest structure is filled by portcls.
// MajorTarget is a pointer to miniport object for miniports.
//
NTSTATUS ntStatus = STATUS_INVALID_DEVICE_REQUEST;
PCMiniportTopology pMiniport = (PCMiniportTopology)PropertyRequest->MajorTarget;
if (IsEqualGUIDAligned(*PropertyRequest->PropertyItem->Set, KSPROPSETID_Jack))
{
if (PropertyRequest->PropertyItem->Id == KSPROPERTY_JACK_DESCRIPTION)
{
ntStatus = pMiniport->PropertyHandlerJackDescription(
PropertyRequest,
ARRAYSIZE(SpdifJackDescriptions),
SpdifJackDescriptions
);
}
else if (PropertyRequest->PropertyItem->Id == KSPROPERTY_JACK_DESCRIPTION2)
{
ntStatus = pMiniport->PropertyHandlerJackDescription2(
PropertyRequest,
ARRAYSIZE(SpdifJackDescriptions),
SpdifJackDescriptions,
0 // jack capabilities
);
}
}
return ntStatus;
} // PropertyHandler_SpdifTopoFilter
#pragma code_seg()
|
//------------------------------------------------------------------------------------------------//
/// @file document/scene_editor/nodes_handling/scene_editor_group_nodes.cpp
//------------------------------------------------------------------------------------------------//
//-INCLUDES---------------------------------------------------------------------------------------//
#include "document/scene_editor/nodes_handling/scene_editor_group_nodes.h"
#include "document/scene_editor/scene_editor.h"
//------------------------------------------------------------------------------------------------//
namespace coffee_editor
{
//-META---------------------------------------------------------------------------------------//
COFFEE_BeginType(SceneEditorGroupNodes);
COFFEE_Ancestor(ApplicationCommand);
COFFEE_EndType();
//-CONSTRUCTORS-------------------------------------------------------------------------------//
SceneEditorGroupNodes::SceneEditorGroupNodes() :
ApplicationCommand("Group", "Group selected node(s)")
{
}
//-QUERIES------------------------------------------------------------------------------------//
bool SceneEditorGroupNodes::IsUsable() const
{
return GetSelectionManager()->GetObjectCount()>0;
}
//-HANDLERS-----------------------------------------------------------------------------------//
void SceneEditorGroupNodes::OnExecute()
{
SceneEditor* scene_editor((SceneEditor*) &GetParent().GetParent());
if (scene_editor->GetScene().GetState()==resource::HANDLER_STATE_Ready)
{
edition::SelectionManager* selection_manager = GetSelectionManager();
basic::Prow<meta::Object*> objects = selection_manager->GetObjectArray();
edition::UndoManager* undo_manager = GetUndoManager();
scene::Node* node = COFFEE_New(scene::Node, "Group");
node->AddComponent(COFFEE_New(scene::Transform));
node->AddComponent(COFFEE_New(scene::Bounding));
selection_manager->Clear(false);
selection_manager->Select(*node, true, true, false);
undo_manager->Add(COFFEE_New(edition::PluginAttachNodeUndo, node));
scene_editor->GetCurrentNode().Attach(*node);
for (uint32 index=0 ; index<objects.GetSize() ; ++index)
{
scene::Node* child = static_cast<scene::Node*>(objects[index]);
undo_manager->Add(COFFEE_New(edition::PluginDetachNodeUndo, child));
child->Detach();
undo_manager->Add(COFFEE_New(edition::PluginAttachNodeUndo, child));
node->Attach(*child);
}
selection_manager->Select(*node, true, true, false);
undo_manager->Accept("Create Group");
scene_editor->UpdateExplorer();
}
}
}
//------------------------------------------------------------------------------------------------//
|
/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2019 Filipe Coelho <falktx@falktx.com>
* Copyright (C) 2019 Jean Pierre Cimalando <jp-dev@inbox.ru>
* Copyright (C) 2019 Robin Gareus <robin@gareus.org>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// we need this for now
//#define PUGL_GRAB_FOCUS 1
#include "../Base.hpp"
#ifdef DGL_CAIRO
# define PUGL_CAIRO
# include "../Cairo.hpp"
#endif
#ifdef DGL_OPENGL
# define PUGL_OPENGL
# include "../OpenGL.hpp"
#endif
#include "pugl/pugl.h"
#if defined(__GNUC__) && (__GNUC__ >= 7)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif
#if defined(DISTRHO_OS_WINDOWS)
# include "pugl/pugl_win.cpp"
# undef max
# undef min
#elif defined(DISTRHO_OS_MAC)
# define PuglWindow DISTRHO_JOIN_MACRO(PuglWindow, DGL_NAMESPACE)
# define PuglOpenGLView DISTRHO_JOIN_MACRO(PuglOpenGLView, DGL_NAMESPACE)
# include "pugl/pugl_osx.m"
#else
# include <sys/types.h>
# include <unistd.h>
extern "C" {
# include "pugl/pugl_x11.c"
}
#endif
#if defined(__GNUC__) && (__GNUC__ >= 7)
# pragma GCC diagnostic pop
#endif
#include "ApplicationPrivateData.hpp"
#include "WidgetPrivateData.hpp"
#include "../StandaloneWindow.hpp"
#include "../../distrho/extra/String.hpp"
#define FOR_EACH_WIDGET(it) \
for (std::list<Widget*>::iterator it = fWidgets.begin(); it != fWidgets.end(); ++it)
#define FOR_EACH_WIDGET_INV(rit) \
for (std::list<Widget*>::reverse_iterator rit = fWidgets.rbegin(); rit != fWidgets.rend(); ++rit)
#if defined(DEBUG) && defined(DGL_DEBUG_EVENTS)
# define DBG(msg) std::fprintf(stderr, "%s", msg);
# define DBGp(...) std::fprintf(stderr, __VA_ARGS__);
# define DBGF std::fflush(stderr);
#else
# define DBG(msg)
# define DBGp(...)
# define DBGF
#endif
START_NAMESPACE_DGL
// -----------------------------------------------------------------------
// Window Private
struct Window::PrivateData {
PrivateData(Application& app, Window* const self)
: fApp(app),
fSelf(self),
fView(puglInit()),
fFirstInit(true),
fVisible(false),
fResizable(true),
fUsingEmbed(false),
fWidth(1),
fHeight(1),
fScaling(1.0),
fAutoScaling(1.0),
fTitle(nullptr),
fWidgets(),
fModal(),
#if defined(DISTRHO_OS_WINDOWS)
hwnd(nullptr),
hwndParent(nullptr)
#elif defined(DISTRHO_OS_MAC)
fNeedsIdle(true),
mView(nullptr),
mWindow(nullptr),
mParentWindow(nullptr)
# ifndef DGL_FILE_BROWSER_DISABLED
, fOpenFilePanel(nullptr),
fFilePanelDelegate(nullptr)
# endif
#else
xDisplay(nullptr),
xWindow(0)
#endif
{
DBG("Creating window without parent..."); DBGF;
init();
}
PrivateData(Application& app, Window* const self, Window& parent)
: fApp(app),
fSelf(self),
fView(puglInit()),
fFirstInit(true),
fVisible(false),
fResizable(true),
fUsingEmbed(false),
fWidth(1),
fHeight(1),
fScaling(1.0),
fAutoScaling(1.0),
fTitle(nullptr),
fWidgets(),
fModal(parent.pData),
#if defined(DISTRHO_OS_WINDOWS)
hwnd(nullptr),
hwndParent(nullptr)
#elif defined(DISTRHO_OS_MAC)
fNeedsIdle(false),
mView(nullptr),
mWindow(nullptr),
mParentWindow(nullptr)
# ifndef DGL_FILE_BROWSER_DISABLED
, fOpenFilePanel(nullptr),
fFilePanelDelegate(nullptr)
# endif
#else
xDisplay(nullptr),
xWindow(0)
#endif
{
DBG("Creating window with parent..."); DBGF;
init();
const PuglInternals* const parentImpl(parent.pData->fView->impl);
// NOTE: almost a 1:1 copy of setTransientWinId()
#if defined(DISTRHO_OS_WINDOWS)
hwndParent = parentImpl->hwnd;
SetWindowLongPtr(hwnd, GWLP_HWNDPARENT, (LONG_PTR)hwndParent);
#elif defined(DISTRHO_OS_MAC)
mParentWindow = parentImpl->window;
#else
XSetTransientForHint(xDisplay, xWindow, parentImpl->win);
#endif
}
PrivateData(Application& app, Window* const self, const intptr_t parentId, const double scaling, const bool resizable)
: fApp(app),
fSelf(self),
fView(puglInit()),
fFirstInit(true),
fVisible(parentId != 0),
fResizable(resizable),
fUsingEmbed(parentId != 0),
fWidth(1),
fHeight(1),
fScaling(scaling),
fAutoScaling(1.0),
fTitle(nullptr),
fWidgets(),
fModal(),
#if defined(DISTRHO_OS_WINDOWS)
hwnd(nullptr),
hwndParent(nullptr)
#elif defined(DISTRHO_OS_MAC)
fNeedsIdle(parentId == 0),
mView(nullptr),
mWindow(nullptr),
mParentWindow(nullptr)
# ifndef DGL_FILE_BROWSER_DISABLED
, fOpenFilePanel(nullptr),
fFilePanelDelegate(nullptr)
# endif
#else
xDisplay(nullptr),
xWindow(0)
#endif
{
if (fUsingEmbed)
{
DBG("Creating embedded window..."); DBGF;
puglInitWindowParent(fView, parentId);
}
else
{
DBG("Creating window without parent..."); DBGF;
}
init();
if (fUsingEmbed)
{
DBG("NOTE: Embed window is always visible and non-resizable\n");
puglShowWindow(fView);
fApp.pData->oneShown();
fFirstInit = false;
}
}
void init()
{
if (fSelf == nullptr || fView == nullptr)
{
DBG("Failed!\n");
return;
}
puglInitUserResizable(fView, fResizable);
puglInitWindowSize(fView, static_cast<int>(fWidth), static_cast<int>(fHeight));
puglSetHandle(fView, this);
puglSetDisplayFunc(fView, onDisplayCallback);
puglSetKeyboardFunc(fView, onKeyboardCallback);
puglSetMotionFunc(fView, onMotionCallback);
puglSetMouseFunc(fView, onMouseCallback);
puglSetScrollFunc(fView, onScrollCallback);
puglSetSpecialFunc(fView, onSpecialCallback);
puglSetReshapeFunc(fView, onReshapeCallback);
puglSetCloseFunc(fView, onCloseCallback);
#ifndef DGL_FILE_BROWSER_DISABLED
puglSetFileSelectedFunc(fView, fileBrowserSelectedCallback);
#endif
puglCreateWindow(fView, nullptr);
PuglInternals* impl = fView->impl;
#if defined(DISTRHO_OS_WINDOWS)
hwnd = impl->hwnd;
DISTRHO_SAFE_ASSERT(hwnd != 0);
#elif defined(DISTRHO_OS_MAC)
mView = impl->view;
mWindow = impl->window;
DISTRHO_SAFE_ASSERT(mView != nullptr);
if (fUsingEmbed) {
DISTRHO_SAFE_ASSERT(mWindow == nullptr);
} else {
DISTRHO_SAFE_ASSERT(mWindow != nullptr);
}
#else
xDisplay = impl->display;
xWindow = impl->win;
DISTRHO_SAFE_ASSERT(xWindow != 0);
if (! fUsingEmbed)
{
const pid_t pid = getpid();
const Atom _nwp = XInternAtom(xDisplay, "_NET_WM_PID", False);
XChangeProperty(xDisplay, xWindow, _nwp, XA_CARDINAL, 32, PropModeReplace, (const uchar*)&pid, 1);
const Atom _wt = XInternAtom(xDisplay, "_NET_WM_WINDOW_TYPE", False);
// Setting the window to both dialog and normal will produce a decorated floating dialog
// Order is important: DIALOG needs to come before NORMAL
const Atom _wts[2] = {
XInternAtom(xDisplay, "_NET_WM_WINDOW_TYPE_DIALOG", False),
XInternAtom(xDisplay, "_NET_WM_WINDOW_TYPE_NORMAL", False)
};
XChangeProperty(xDisplay, xWindow, _wt, XA_ATOM, 32, PropModeReplace, (const uchar*)&_wts, 2);
}
#endif
puglEnterContext(fView);
fApp.pData->windows.push_back(fSelf);
DBG("Success!\n");
}
~PrivateData()
{
DBG("Destroying window..."); DBGF;
if (fModal.enabled)
{
exec_fini();
close();
}
fWidgets.clear();
if (fUsingEmbed)
{
puglHideWindow(fView);
fApp.pData->oneHidden();
}
if (fSelf != nullptr)
{
fApp.pData->windows.remove(fSelf);
fSelf = nullptr;
}
if (fView != nullptr)
{
puglDestroy(fView);
fView = nullptr;
}
if (fTitle != nullptr)
{
std::free(fTitle);
fTitle = nullptr;
}
#if defined(DISTRHO_OS_WINDOWS)
hwnd = 0;
#elif defined(DISTRHO_OS_MAC)
mView = nullptr;
mWindow = nullptr;
#else
xDisplay = nullptr;
xWindow = 0;
#endif
#if defined(DISTRHO_OS_MAC) && !defined(DGL_FILE_BROWSER_DISABLED)
if (fOpenFilePanel)
{
[fOpenFilePanel release];
fOpenFilePanel = nullptr;
}
if (fFilePanelDelegate)
{
[fFilePanelDelegate release];
fFilePanelDelegate = nullptr;
}
#endif
DBG("Success!\n");
}
// -------------------------------------------------------------------
void close()
{
DBG("Window close\n");
if (fUsingEmbed)
return;
setVisible(false);
if (! fFirstInit)
{
fApp.pData->oneHidden();
fFirstInit = true;
}
}
void exec(const bool lockWait)
{
DBG("Window exec\n");
exec_init();
if (lockWait)
{
for (; fVisible && fModal.enabled;)
{
idle();
d_msleep(10);
}
exec_fini();
}
else
{
idle();
}
}
// -------------------------------------------------------------------
void exec_init()
{
DBG("Window modal loop starting..."); DBGF;
DISTRHO_SAFE_ASSERT_RETURN(fModal.parent != nullptr, setVisible(true));
fModal.enabled = true;
fModal.parent->fModal.childFocus = this;
fModal.parent->setVisible(true);
setVisible(true);
DBG("Ok\n");
}
void exec_fini()
{
DBG("Window modal loop stopping..."); DBGF;
fModal.enabled = false;
if (fModal.parent != nullptr)
{
fModal.parent->fModal.childFocus = nullptr;
// the mouse position probably changed since the modal appeared,
// so send a mouse motion event to the modal's parent window
#if defined(DISTRHO_OS_WINDOWS)
// TODO
#elif defined(DISTRHO_OS_MAC)
// TODO
#else
int i, wx, wy;
uint u;
::Window w;
if (XQueryPointer(fModal.parent->xDisplay, fModal.parent->xWindow, &w, &w, &i, &i, &wx, &wy, &u) == True)
fModal.parent->onPuglMotion(wx, wy);
#endif
}
DBG("Ok\n");
}
// -------------------------------------------------------------------
void focus()
{
DBG("Window focus\n");
#if defined(DISTRHO_OS_WINDOWS)
SetForegroundWindow(hwnd);
SetActiveWindow(hwnd);
SetFocus(hwnd);
#elif defined(DISTRHO_OS_MAC)
if (mWindow != nullptr)
[mWindow makeKeyWindow];
#else
XRaiseWindow(xDisplay, xWindow);
XSetInputFocus(xDisplay, xWindow, RevertToPointerRoot, CurrentTime);
XFlush(xDisplay);
#endif
}
// -------------------------------------------------------------------
void setVisible(const bool yesNo)
{
if (fVisible == yesNo)
{
DBG("Window setVisible matches current state, ignoring request\n");
return;
}
if (fUsingEmbed)
{
DBG("Window setVisible cannot be called when embedded\n");
return;
}
DBG("Window setVisible called\n");
fVisible = yesNo;
if (yesNo && fFirstInit)
setSize(fWidth, fHeight, true);
#if defined(DISTRHO_OS_WINDOWS)
if (yesNo)
{
if (fFirstInit)
{
RECT rectChild, rectParent;
if (hwndParent != nullptr &&
GetWindowRect(hwnd, &rectChild) &&
GetWindowRect(hwndParent, &rectParent))
{
SetWindowPos(hwnd, hwndParent,
rectParent.left + (rectChild.right-rectChild.left)/2,
rectParent.top + (rectChild.bottom-rectChild.top)/2,
0, 0, SWP_SHOWWINDOW|SWP_NOSIZE);
}
else
{
ShowWindow(hwnd, SW_SHOWNORMAL);
}
}
else
{
ShowWindow(hwnd, SW_RESTORE);
}
}
else
{
ShowWindow(hwnd, SW_HIDE);
}
UpdateWindow(hwnd);
#elif defined(DISTRHO_OS_MAC)
if (yesNo)
{
if (mWindow != nullptr)
{
if (mParentWindow != nullptr)
[mParentWindow addChildWindow:mWindow
ordered:NSWindowAbove];
[mWindow setIsVisible:YES];
}
else
{
[mView setHidden:NO];
}
}
else
{
if (mWindow != nullptr)
{
if (mParentWindow != nullptr)
[mParentWindow removeChildWindow:mWindow];
[mWindow setIsVisible:NO];
}
else
{
[mView setHidden:YES];
}
}
#else
if (yesNo)
XMapRaised(xDisplay, xWindow);
else
XUnmapWindow(xDisplay, xWindow);
XFlush(xDisplay);
#endif
if (yesNo)
{
if (fFirstInit)
{
fApp.pData->oneShown();
fFirstInit = false;
}
}
else if (fModal.enabled)
exec_fini();
}
// -------------------------------------------------------------------
void setResizable(const bool yesNo)
{
if (fResizable == yesNo)
{
DBG("Window setResizable matches current state, ignoring request\n");
return;
}
if (fUsingEmbed)
{
DBG("Window setResizable cannot be called when embedded\n");
return;
}
DBG("Window setResizable called\n");
fResizable = yesNo;
fView->user_resizable = yesNo;
#if defined(DISTRHO_OS_WINDOWS)
const int winFlags = fResizable ? GetWindowLong(hwnd, GWL_STYLE) | WS_SIZEBOX
: GetWindowLong(hwnd, GWL_STYLE) & ~WS_SIZEBOX;
SetWindowLong(hwnd, GWL_STYLE, winFlags);
#elif defined(DISTRHO_OS_MAC)
const uint flags(yesNo ? (NSViewWidthSizable|NSViewHeightSizable) : 0x0);
[mView setAutoresizingMask:flags];
#endif
setSize(fWidth, fHeight, true);
}
// -------------------------------------------------------------------
void setGeometryConstraints(uint width, uint height, bool aspect)
{
// Did you forget to set DISTRHO_UI_USER_RESIZABLE ?
DISTRHO_SAFE_ASSERT_RETURN(fResizable,);
fView->min_width = width;
fView->min_height = height;
puglUpdateGeometryConstraints(fView, width, height, aspect);
}
// -------------------------------------------------------------------
void setSize(uint width, uint height, const bool forced = false)
{
if (width <= 1 || height <= 1)
{
DBGp("Window setSize called with invalid value(s) %i %i, ignoring request\n", width, height);
return;
}
if (fWidth == width && fHeight == height && ! forced)
{
DBGp("Window setSize matches current size, ignoring request (%i %i)\n", width, height);
return;
}
fWidth = width;
fHeight = height;
DBGp("Window setSize called %s, size %i %i, resizable %s\n", forced ? "(forced)" : "(not forced)", width, height, fResizable?"true":"false");
#if defined(DISTRHO_OS_WINDOWS)
const int winFlags = WS_POPUPWINDOW | WS_CAPTION | (fResizable ? WS_SIZEBOX : 0x0);
RECT wr = { 0, 0, static_cast<LONG>(width), static_cast<LONG>(height) };
AdjustWindowRectEx(&wr, fUsingEmbed ? WS_CHILD : winFlags, FALSE, WS_EX_TOPMOST);
SetWindowPos(hwnd, 0, 0, 0, wr.right-wr.left, wr.bottom-wr.top,
SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOOWNERZORDER|SWP_NOZORDER);
if (! forced)
UpdateWindow(hwnd);
#elif defined(DISTRHO_OS_MAC)
[mView setFrame:NSMakeRect(0, 0, width, height)];
if (mWindow != nullptr)
{
const NSSize size = NSMakeSize(width, height);
[mWindow setContentSize:size];
if (fResizable)
{
[mWindow setContentMinSize:NSMakeSize(1, 1)];
[mWindow setContentMaxSize:NSMakeSize(99999, 99999)];
[[mWindow standardWindowButton:NSWindowZoomButton] setHidden:NO];
}
else
{
[mWindow setContentMinSize:size];
[mWindow setContentMaxSize:size];
[[mWindow standardWindowButton:NSWindowZoomButton] setHidden:YES];
}
}
#else
if (! fResizable)
{
XSizeHints sizeHints;
memset(&sizeHints, 0, sizeof(sizeHints));
sizeHints.flags = PSize|PMinSize|PMaxSize;
sizeHints.width = static_cast<int>(width);
sizeHints.height = static_cast<int>(height);
sizeHints.min_width = static_cast<int>(width);
sizeHints.min_height = static_cast<int>(height);
sizeHints.max_width = static_cast<int>(width);
sizeHints.max_height = static_cast<int>(height);
XSetWMNormalHints(xDisplay, xWindow, &sizeHints);
}
XResizeWindow(xDisplay, xWindow, width, height);
if (! forced)
XFlush(xDisplay);
#endif
puglPostRedisplay(fView);
}
// -------------------------------------------------------------------
const char* getTitle() const noexcept
{
static const char* const kFallback = "";
return fTitle != nullptr ? fTitle : kFallback;
}
void setTitle(const char* const title)
{
DBGp("Window setTitle \"%s\"\n", title);
if (fTitle != nullptr)
std::free(fTitle);
fTitle = strdup(title);
#if defined(DISTRHO_OS_WINDOWS)
SetWindowTextA(hwnd, title);
#elif defined(DISTRHO_OS_MAC)
if (mWindow != nullptr)
{
NSString* titleString = [[NSString alloc]
initWithBytes:title
length:strlen(title)
encoding:NSUTF8StringEncoding];
[mWindow setTitle:titleString];
}
#else
XStoreName(xDisplay, xWindow, title);
Atom netWmName = XInternAtom(xDisplay, "_NET_WM_NAME", False);
Atom utf8String = XInternAtom(xDisplay, "UTF8_STRING", False);
XChangeProperty(xDisplay, xWindow, netWmName, utf8String, 8, PropModeReplace, (unsigned char *)title, strlen(title));
#endif
}
void setTransientWinId(const uintptr_t winId)
{
DISTRHO_SAFE_ASSERT_RETURN(winId != 0,);
#if defined(DISTRHO_OS_WINDOWS)
hwndParent = (HWND)winId;
SetWindowLongPtr(hwnd, GWLP_HWNDPARENT, (LONG_PTR)winId);
#elif defined(DISTRHO_OS_MAC)
NSWindow* const parentWindow = [NSApp windowWithWindowNumber:winId];
DISTRHO_SAFE_ASSERT_RETURN(parentWindow != nullptr,);
[parentWindow addChildWindow:mWindow
ordered:NSWindowAbove];
#else
XSetTransientForHint(xDisplay, xWindow, static_cast< ::Window>(winId));
#endif
}
// -------------------------------------------------------------------
double getScaling() const noexcept
{
return fScaling;
}
void setAutoScaling(const double scaling) noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(scaling > 0.0,);
fAutoScaling = scaling;
}
// -------------------------------------------------------------------
bool getIgnoringKeyRepeat() const noexcept
{
return fView->ignoreKeyRepeat;
}
void setIgnoringKeyRepeat(bool ignore) noexcept
{
puglIgnoreKeyRepeat(fView, ignore);
}
// -------------------------------------------------------------------
void addWidget(Widget* const widget)
{
fWidgets.push_back(widget);
}
void removeWidget(Widget* const widget)
{
fWidgets.remove(widget);
}
void idle()
{
puglProcessEvents(fView);
#ifdef DISTRHO_OS_MAC
if (fNeedsIdle)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSEvent* event;
for (;;)
{
event = [NSApp
nextEventMatchingMask:NSAnyEventMask
untilDate:[NSDate distantPast]
inMode:NSDefaultRunLoopMode
dequeue:YES];
if (event == nil)
break;
[NSApp sendEvent: event];
}
[pool release];
}
#endif
#if defined(DISTRHO_OS_WINDOWS) && !defined(DGL_FILE_BROWSER_DISABLED)
if (fSelectedFile.isNotEmpty())
{
char* const buffer = fSelectedFile.getAndReleaseBuffer();
fView->fileSelectedFunc(fView, buffer);
std::free(buffer);
}
#endif
if (fModal.enabled && fModal.parent != nullptr)
fModal.parent->idle();
}
// -------------------------------------------------------------------
void onPuglDisplay()
{
fSelf->onDisplayBefore();
FOR_EACH_WIDGET(it)
{
Widget* const widget(*it);
widget->pData->display(fWidth, fHeight, fAutoScaling, false);
}
fSelf->onDisplayAfter();
}
int onPuglKeyboard(const bool press, const uint key)
{
DBGp("PUGL: onKeyboard : %i %i\n", press, key);
if (fModal.childFocus != nullptr)
{
fModal.childFocus->focus();
return 0;
}
Widget::KeyboardEvent ev;
ev.press = press;
ev.key = key;
ev.mod = static_cast<Modifier>(puglGetModifiers(fView));
ev.time = puglGetEventTimestamp(fView);
FOR_EACH_WIDGET_INV(rit)
{
Widget* const widget(*rit);
if (widget->isVisible() && widget->onKeyboard(ev))
return 0;
}
return 1;
}
int onPuglSpecial(const bool press, const Key key)
{
DBGp("PUGL: onSpecial : %i %i\n", press, key);
if (fModal.childFocus != nullptr)
{
fModal.childFocus->focus();
return 0;
}
Widget::SpecialEvent ev;
ev.press = press;
ev.key = key;
ev.mod = static_cast<Modifier>(puglGetModifiers(fView));
ev.time = puglGetEventTimestamp(fView);
FOR_EACH_WIDGET_INV(rit)
{
Widget* const widget(*rit);
if (widget->isVisible() && widget->onSpecial(ev))
return 0;
}
return 1;
}
void onPuglMouse(const int button, const bool press, int x, int y)
{
DBGp("PUGL: onMouse : %i %i %i %i\n", button, press, x, y);
// FIXME - pugl sends 2 of these for each window on init, don't ask me why. we'll ignore it
if (press && button == 0 && x == 0 && y == 0) return;
if (fModal.childFocus != nullptr)
return fModal.childFocus->focus();
x /= fAutoScaling;
y /= fAutoScaling;
Widget::MouseEvent ev;
ev.button = button;
ev.press = press;
ev.mod = static_cast<Modifier>(puglGetModifiers(fView));
ev.time = puglGetEventTimestamp(fView);
FOR_EACH_WIDGET_INV(rit)
{
Widget* const widget(*rit);
ev.pos = Point<int>(x-widget->getAbsoluteX(), y-widget->getAbsoluteY());
if (widget->isVisible() && widget->onMouse(ev))
break;
}
}
void onPuglMotion(int x, int y)
{
// DBGp("PUGL: onMotion : %i %i\n", x, y);
if (fModal.childFocus != nullptr)
return;
x /= fAutoScaling;
y /= fAutoScaling;
Widget::MotionEvent ev;
ev.mod = static_cast<Modifier>(puglGetModifiers(fView));
ev.time = puglGetEventTimestamp(fView);
FOR_EACH_WIDGET_INV(rit)
{
Widget* const widget(*rit);
ev.pos = Point<int>(x-widget->getAbsoluteX(), y-widget->getAbsoluteY());
if (widget->isVisible() && widget->onMotion(ev))
break;
}
}
void onPuglScroll(int x, int y, float dx, float dy)
{
DBGp("PUGL: onScroll : %i %i %f %f\n", x, y, dx, dy);
if (fModal.childFocus != nullptr)
return;
x /= fAutoScaling;
y /= fAutoScaling;
dx /= fAutoScaling;
dy /= fAutoScaling;
Widget::ScrollEvent ev;
ev.delta = Point<float>(dx, dy);
ev.mod = static_cast<Modifier>(puglGetModifiers(fView));
ev.time = puglGetEventTimestamp(fView);
FOR_EACH_WIDGET_INV(rit)
{
Widget* const widget(*rit);
ev.pos = Point<int>(x-widget->getAbsoluteX(), y-widget->getAbsoluteY());
if (widget->isVisible() && widget->onScroll(ev))
break;
}
}
void onPuglReshape(const int width, const int height)
{
DBGp("PUGL: onReshape : %i %i\n", width, height);
if (width <= 1 && height <= 1)
return;
fWidth = static_cast<uint>(width);
fHeight = static_cast<uint>(height);
fSelf->onReshape(fWidth, fHeight);
FOR_EACH_WIDGET(it)
{
Widget* const widget(*it);
if (widget->pData->needsFullViewport)
widget->setSize(fWidth, fHeight);
}
}
void onPuglClose()
{
DBG("PUGL: onClose\n");
if (fModal.enabled)
exec_fini();
fSelf->onClose();
if (fModal.childFocus != nullptr)
fModal.childFocus->fSelf->onClose();
close();
}
// -------------------------------------------------------------------
bool handlePluginKeyboard(const bool press, const uint key)
{
DBGp("PUGL: handlePluginKeyboard : %i %i\n", press, key);
if (fModal.childFocus != nullptr)
{
fModal.childFocus->focus();
return true;
}
Widget::KeyboardEvent ev;
ev.press = press;
ev.key = key;
ev.mod = static_cast<Modifier>(fView->mods);
ev.time = 0;
if ((ev.mod & kModifierShift) != 0 && ev.key >= 'a' && ev.key <= 'z')
ev.key -= 'a' - 'A'; // a-z -> A-Z
FOR_EACH_WIDGET_INV(rit)
{
Widget* const widget(*rit);
if (widget->isVisible() && widget->onKeyboard(ev))
return true;
}
return false;
}
bool handlePluginSpecial(const bool press, const Key key)
{
DBGp("PUGL: handlePluginSpecial : %i %i\n", press, key);
if (fModal.childFocus != nullptr)
{
fModal.childFocus->focus();
return true;
}
int mods = 0x0;
switch (key)
{
case kKeyShift:
mods |= kModifierShift;
break;
case kKeyControl:
mods |= kModifierControl;
break;
case kKeyAlt:
mods |= kModifierAlt;
break;
default:
break;
}
if (mods != 0x0)
{
if (press)
fView->mods |= mods;
else
fView->mods &= ~(mods);
}
Widget::SpecialEvent ev;
ev.press = press;
ev.key = key;
ev.mod = static_cast<Modifier>(fView->mods);
ev.time = 0;
FOR_EACH_WIDGET_INV(rit)
{
Widget* const widget(*rit);
if (widget->isVisible() && widget->onSpecial(ev))
return true;
}
return false;
}
#if defined(DISTRHO_OS_MAC) && !defined(DGL_FILE_BROWSER_DISABLED)
static void openPanelDidEnd(NSOpenPanel* panel, int returnCode, void *userData)
{
PrivateData* pData = (PrivateData*)userData;
if (returnCode == NSOKButton)
{
NSArray* urls = [panel URLs];
NSURL* fileUrl = nullptr;
for (NSUInteger i = 0, n = [urls count]; i < n && !fileUrl; ++i)
{
NSURL* url = (NSURL*)[urls objectAtIndex:i];
if ([url isFileURL])
fileUrl = url;
}
if (fileUrl)
{
PuglView* view = pData->fView;
if (view->fileSelectedFunc)
{
const char* fileName = [fileUrl.path UTF8String];
view->fileSelectedFunc(view, fileName);
}
}
}
[pData->fOpenFilePanel release];
pData->fOpenFilePanel = nullptr;
}
#endif
// -------------------------------------------------------------------
Application& fApp;
Window* fSelf;
GraphicsContext fContext;
PuglView* fView;
bool fFirstInit;
bool fVisible;
bool fResizable;
bool fUsingEmbed;
uint fWidth;
uint fHeight;
double fScaling;
double fAutoScaling;
char* fTitle;
std::list<Widget*> fWidgets;
struct Modal {
bool enabled;
PrivateData* parent;
PrivateData* childFocus;
Modal()
: enabled(false),
parent(nullptr),
childFocus(nullptr) {}
Modal(PrivateData* const p)
: enabled(false),
parent(p),
childFocus(nullptr) {}
~Modal()
{
DISTRHO_SAFE_ASSERT(! enabled);
DISTRHO_SAFE_ASSERT(childFocus == nullptr);
}
DISTRHO_DECLARE_NON_COPY_STRUCT(Modal)
} fModal;
#if defined(DISTRHO_OS_WINDOWS)
HWND hwnd;
HWND hwndParent;
# ifndef DGL_FILE_BROWSER_DISABLED
String fSelectedFile;
# endif
#elif defined(DISTRHO_OS_MAC)
bool fNeedsIdle;
NSView<PuglGenericView>* mView;
id mWindow;
id mParentWindow;
# ifndef DGL_FILE_BROWSER_DISABLED
NSOpenPanel* fOpenFilePanel;
id fFilePanelDelegate;
# endif
#else
Display* xDisplay;
::Window xWindow;
#endif
// -------------------------------------------------------------------
// Callbacks
#define handlePtr ((PrivateData*)puglGetHandle(view))
static void onDisplayCallback(PuglView* view)
{
handlePtr->onPuglDisplay();
}
static int onKeyboardCallback(PuglView* view, bool press, uint32_t key)
{
return handlePtr->onPuglKeyboard(press, key);
}
static int onSpecialCallback(PuglView* view, bool press, PuglKey key)
{
return handlePtr->onPuglSpecial(press, static_cast<Key>(key));
}
static void onMouseCallback(PuglView* view, int button, bool press, int x, int y)
{
handlePtr->onPuglMouse(button, press, x, y);
}
static void onMotionCallback(PuglView* view, int x, int y)
{
handlePtr->onPuglMotion(x, y);
}
static void onScrollCallback(PuglView* view, int x, int y, float dx, float dy)
{
handlePtr->onPuglScroll(x, y, dx, dy);
}
static void onReshapeCallback(PuglView* view, int width, int height)
{
handlePtr->onPuglReshape(width, height);
}
static void onCloseCallback(PuglView* view)
{
handlePtr->onPuglClose();
}
#ifndef DGL_FILE_BROWSER_DISABLED
static void fileBrowserSelectedCallback(PuglView* view, const char* filename)
{
handlePtr->fSelf->fileBrowserSelected(filename);
}
#endif
#undef handlePtr
DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PrivateData)
};
// -----------------------------------------------------------------------
// Window
Window::Window(Application& app)
: pData(new PrivateData(app, this)) {}
Window::Window(Application& app, Window& parent)
: pData(new PrivateData(app, this, parent)) {}
Window::Window(Application& app, intptr_t parentId, double scaling, bool resizable)
: pData(new PrivateData(app, this, parentId, scaling, resizable)) {}
Window::~Window()
{
delete pData;
}
void Window::show()
{
pData->setVisible(true);
}
void Window::hide()
{
pData->setVisible(false);
}
void Window::close()
{
pData->close();
}
void Window::exec(bool lockWait)
{
pData->exec(lockWait);
}
void Window::focus()
{
pData->focus();
}
void Window::repaint() noexcept
{
puglPostRedisplay(pData->fView);
}
// static int fib_filter_filename_filter(const char* const name)
// {
// return 1;
// (void)name;
// }
#ifndef DGL_FILE_BROWSER_DISABLED
#ifdef DISTRHO_OS_MAC
END_NAMESPACE_DGL
@interface FilePanelDelegate : NSObject
{
void (*fCallback)(NSOpenPanel*, int, void*);
void* fUserData;
}
-(id)initWithCallback:(void(*)(NSOpenPanel*, int, void*))callback userData:(void*)userData;
-(void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
@end
START_NAMESPACE_DGL
#endif
bool Window::openFileBrowser(const FileBrowserOptions& options)
{
# ifdef SOFD_HAVE_X11
using DISTRHO_NAMESPACE::String;
// --------------------------------------------------------------------------
// configure start dir
// TODO: get abspath if needed
// TODO: cross-platform
String startDir(options.startDir);
# ifdef DISTRHO_OS_LINUX
if (startDir.isEmpty())
{
if (char* const dir_name = get_current_dir_name())
{
startDir = dir_name;
std::free(dir_name);
}
}
# endif
DISTRHO_SAFE_ASSERT_RETURN(startDir.isNotEmpty(), false);
if (! startDir.endsWith('/'))
startDir += "/";
DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(0, startDir) == 0, false);
// --------------------------------------------------------------------------
// configure title
String title(options.title);
if (title.isEmpty())
{
title = pData->getTitle();
if (title.isEmpty())
title = "FileBrowser";
}
DISTRHO_SAFE_ASSERT_RETURN(x_fib_configure(1, title) == 0, false);
// --------------------------------------------------------------------------
// configure filters
x_fib_cfg_filter_callback(nullptr); //fib_filter_filename_filter);
// --------------------------------------------------------------------------
// configure buttons
x_fib_cfg_buttons(3, options.buttons.listAllFiles-1);
x_fib_cfg_buttons(1, options.buttons.showHidden-1);
x_fib_cfg_buttons(2, options.buttons.showPlaces-1);
// --------------------------------------------------------------------------
// show
return (x_fib_show(pData->xDisplay, pData->xWindow, /*options.width*/0, /*options.height*/0) == 0);
# elif defined(DISTRHO_OS_WINDOWS)
// the old and compatible dialog API
OPENFILENAMEW ofn;
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = pData->hwnd;
// set initial directory in UTF-16 coding
std::vector<WCHAR> startDirW;
if (options.startDir)
{
startDirW.resize(strlen(options.startDir) + 1);
if (MultiByteToWideChar(CP_UTF8, 0, options.startDir, -1, startDirW.data(), startDirW.size()))
ofn.lpstrInitialDir = startDirW.data();
}
// set title in UTF-16 coding
std::vector<WCHAR> titleW;
if (options.title)
{
titleW.resize(strlen(options.title) + 1);
if (MultiByteToWideChar(CP_UTF8, 0, options.title, -1, titleW.data(), titleW.size()))
ofn.lpstrTitle = titleW.data();
}
// prepare a buffer to receive the result
std::vector<WCHAR> fileNameW(32768); // the Unicode maximum
ofn.lpstrFile = fileNameW.data();
ofn.nMaxFile = (DWORD)fileNameW.size();
// TODO synchronous only, can't do better with WinAPI native dialogs.
// threading might work, if someone is motivated to risk it.
if (GetOpenFileNameW(&ofn))
{
// back to UTF-8
std::vector<char> fileNameA(4 * 32768);
if (WideCharToMultiByte(CP_UTF8, 0, fileNameW.data(), -1, fileNameA.data(), (int)fileNameA.size(), nullptr, nullptr))
{
// handle it during the next idle cycle (fake async)
pData->fSelectedFile = fileNameA.data();
}
}
return true;
# elif defined(DISTRHO_OS_MAC)
if (pData->fOpenFilePanel) // permit one dialog at most
{
[pData->fOpenFilePanel makeKeyAndOrderFront:nil];
return false;
}
NSOpenPanel* panel = [NSOpenPanel openPanel];
pData->fOpenFilePanel = [panel retain];
[panel setCanChooseFiles:YES];
[panel setCanChooseDirectories:NO];
[panel setAllowsMultipleSelection:NO];
if (options.startDir)
[panel setDirectory:[NSString stringWithUTF8String:options.startDir]];
if (options.title)
{
NSString* titleString = [[NSString alloc]
initWithBytes:options.title
length:strlen(options.title)
encoding:NSUTF8StringEncoding];
[panel setTitle:titleString];
}
id delegate = pData->fFilePanelDelegate;
if (!delegate)
{
delegate = [[FilePanelDelegate alloc] initWithCallback:&PrivateData::openPanelDidEnd
userData:pData];
pData->fFilePanelDelegate = [delegate retain];
}
[panel beginSheetForDirectory:nullptr
file:nullptr
modalForWindow:nullptr
modalDelegate:delegate
didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
contextInfo:nullptr];
return true;
# else
// not implemented
return false;
// unused
(void)options;
# endif
}
#ifdef DISTRHO_OS_MAC
END_NAMESPACE_DGL
@implementation FilePanelDelegate
-(id)initWithCallback:(void(*)(NSOpenPanel*, int, void*))callback userData:(void *)userData
{
[super init];
self->fCallback = callback;
self->fUserData = userData;
return self;
}
-(void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
{
self->fCallback(sheet, returnCode, self->fUserData);
(void)contextInfo;
}
@end
START_NAMESPACE_DGL
#endif
#endif // !defined(DGL_FILE_BROWSER_DISABLED)
bool Window::isEmbed() const noexcept
{
return pData->fUsingEmbed;
}
bool Window::isVisible() const noexcept
{
return pData->fVisible;
}
void Window::setVisible(bool yesNo)
{
pData->setVisible(yesNo);
}
bool Window::isResizable() const noexcept
{
return pData->fResizable;
}
void Window::setResizable(bool yesNo)
{
pData->setResizable(yesNo);
}
void Window::setGeometryConstraints(uint width, uint height, bool aspect)
{
pData->setGeometryConstraints(width, height, aspect);
}
uint Window::getWidth() const noexcept
{
return pData->fWidth;
}
uint Window::getHeight() const noexcept
{
return pData->fHeight;
}
Size<uint> Window::getSize() const noexcept
{
return Size<uint>(pData->fWidth, pData->fHeight);
}
void Window::setSize(uint width, uint height)
{
pData->setSize(width, height);
}
void Window::setSize(Size<uint> size)
{
pData->setSize(size.getWidth(), size.getHeight());
}
const char* Window::getTitle() const noexcept
{
return pData->getTitle();
}
void Window::setTitle(const char* title)
{
pData->setTitle(title);
}
void Window::setTransientWinId(uintptr_t winId)
{
pData->setTransientWinId(winId);
}
double Window::getScaling() const noexcept
{
return pData->getScaling();
}
bool Window::getIgnoringKeyRepeat() const noexcept
{
return pData->getIgnoringKeyRepeat();
}
void Window::setIgnoringKeyRepeat(bool ignore) noexcept
{
pData->setIgnoringKeyRepeat(ignore);
}
Application& Window::getApp() const noexcept
{
return pData->fApp;
}
intptr_t Window::getWindowId() const noexcept
{
return puglGetNativeWindow(pData->fView);
}
const GraphicsContext& Window::getGraphicsContext() const noexcept
{
GraphicsContext& context = pData->fContext;
#ifdef DGL_CAIRO
context.cairo = (cairo_t*)puglGetContext(pData->fView);
#endif
return context;
}
void Window::_setAutoScaling(double scaling) noexcept
{
pData->setAutoScaling(scaling);
}
void Window::_addWidget(Widget* const widget)
{
pData->addWidget(widget);
}
void Window::_removeWidget(Widget* const widget)
{
pData->removeWidget(widget);
}
void Window::_idle()
{
pData->idle();
}
// -----------------------------------------------------------------------
void Window::addIdleCallback(IdleCallback* const callback)
{
DISTRHO_SAFE_ASSERT_RETURN(callback != nullptr,)
pData->fApp.pData->idleCallbacks.push_back(callback);
}
void Window::removeIdleCallback(IdleCallback* const callback)
{
DISTRHO_SAFE_ASSERT_RETURN(callback != nullptr,)
pData->fApp.pData->idleCallbacks.remove(callback);
}
// -----------------------------------------------------------------------
void Window::onDisplayBefore()
{
#ifdef DGL_OPENGL
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
#endif
}
void Window::onDisplayAfter()
{
}
void Window::onReshape(uint width, uint height)
{
#ifdef DGL_OPENGL
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, static_cast<GLdouble>(width), static_cast<GLdouble>(height), 0.0, 0.0, 1.0);
glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height));
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
#endif
}
void Window::onClose()
{
}
#ifndef DGL_FILE_BROWSER_DISABLED
void Window::fileBrowserSelected(const char*)
{
}
#endif
bool Window::handlePluginKeyboard(const bool press, const uint key)
{
return pData->handlePluginKeyboard(press, key);
}
bool Window::handlePluginSpecial(const bool press, const Key key)
{
return pData->handlePluginSpecial(press, key);
}
// -----------------------------------------------------------------------
StandaloneWindow::StandaloneWindow()
: Application(),
Window((Application&)*this),
fWidget(nullptr) {}
void StandaloneWindow::exec()
{
Window::show();
Application::exec();
}
void StandaloneWindow::onReshape(uint width, uint height)
{
if (fWidget != nullptr)
fWidget->setSize(width, height);
Window::onReshape(width, height);
}
void StandaloneWindow::_addWidget(Widget* widget)
{
if (fWidget == nullptr)
{
fWidget = widget;
fWidget->pData->needsFullViewport = true;
}
Window::_addWidget(widget);
}
void StandaloneWindow::_removeWidget(Widget* widget)
{
if (fWidget == widget)
{
fWidget->pData->needsFullViewport = false;
fWidget = nullptr;
}
Window::_removeWidget(widget);
}
// -----------------------------------------------------------------------
END_NAMESPACE_DGL
#undef DBG
#undef DBGF
|
#pragma once
#include <window.hpp>
#include <audiostream.hpp>
#include <functional>
class AudioNode :
public Window
{
public:
typedef std::function<void(sample_t * dst, int dstCnt, sample_t const * src, int srcCnt)> dsp_t;
typedef std::function<sample_t(sample_t src)> monodsp_t;
private:
int priority;
protected:
AudioNode(std::string const & title, ImGuiWindowFlags flags = 0);
//! Applies a processing to all audio samples, requires channel adjustments!
static void Render(AudioStream & dst, AudioStream const & src, dsp_t const & dsp);
//! Applies a processing to all channels, dst will have adjusted channel
static void Render(AudioStream & dst, AudioStream const & src, monodsp_t const & dsp);
//! Renders the audio stream
//! @remarks Called from a different thread!
virtual void OnRenderAudio() = 0;
public:
virtual ~AudioNode();
void RenderAudio();
};
|
//
// Copyright (c) 2015-2020 Microsoft Corporation and Contributors.
// SPDX-License-Identifier: Apache-2.0
//
#include "BondSerializer.hpp"
#include "utils/StringUtils.hpp"
#include "utils/Utils.hpp"
#include "bond/All.hpp"
#include "bond/generated/CsProtocol_writers.hpp"
#include "bond/generated/CsProtocol_readers.hpp"
#include "oacr.h"
namespace MAT_NS_BEGIN {
bool BondSerializer::handleSerialize(IncomingEventContextPtr const& ctx)
{
OACR_USE_PTR(this);
{
bond_lite::CompactBinaryProtocolWriter writer(ctx->record.blob);
bond_lite::Serialize(writer, *ctx->source);
}
LOG_TRACE("Event %s/%s submitted, priority %u (%s), serialized size %u bytes, ID %s",
tenantTokenToId(ctx->record.tenantToken).c_str(), ctx->source->baseType.c_str(),
ctx->record.latency, latencyToStr(ctx->record.latency),
static_cast<unsigned>(ctx->record.blob.size()), ctx->record.id.c_str());
return true;
}
} MAT_NS_END
|
/*
* Catch v2.13.3
* Generated: 2020-10-31 18:20:31.045274
* ----------------------------------------------------------
* This file has been merged from multiple headers. Please don't edit it directly
* Copyright (c) 2020 Two Blue Cubes Ltd. All rights reserved.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
// start catch.hpp
#define CATCH_VERSION_MAJOR 2
#define CATCH_VERSION_MINOR 13
#define CATCH_VERSION_PATCH 3
#ifdef __clang__
# pragma clang system_header
#elif defined __GNUC__
# pragma GCC system_header
#endif
// start catch_suppress_warnings.h
#ifdef __clang__
# ifdef __ICC // icpc defines the __clang__ macro
# pragma warning(push)
# pragma warning(disable: 161 1682)
# else // __ICC
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wpadded"
# pragma clang diagnostic ignored "-Wswitch-enum"
# pragma clang diagnostic ignored "-Wcovered-switch-default"
# endif
#elif defined __GNUC__
// Because REQUIREs trigger GCC's -Wparentheses, and because still
// supported version of g++ have only buggy support for _Pragmas,
// Wparentheses have to be suppressed globally.
# pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-variable"
# pragma GCC diagnostic ignored "-Wpadded"
#endif
// end catch_suppress_warnings.h
#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
# define CATCH_IMPL
# define CATCH_CONFIG_ALL_PARTS
#endif
// In the impl file, we want to have access to all parts of the headers
// Can also be used to sanely support PCHs
#if defined(CATCH_CONFIG_ALL_PARTS)
# define CATCH_CONFIG_EXTERNAL_INTERFACES
# if defined(CATCH_CONFIG_DISABLE_MATCHERS)
# undef CATCH_CONFIG_DISABLE_MATCHERS
# endif
# if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
# endif
#endif
#if !defined(CATCH_CONFIG_IMPL_ONLY)
// start catch_platform.h
#ifdef __APPLE__
# include <TargetConditionals.h>
# if TARGET_OS_OSX == 1
# define CATCH_PLATFORM_MAC
# elif TARGET_OS_IPHONE == 1
# define CATCH_PLATFORM_IPHONE
# endif
#elif defined(linux) || defined(__linux) || defined(__linux__)
# define CATCH_PLATFORM_LINUX
#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
# define CATCH_PLATFORM_WINDOWS
#endif
// end catch_platform.h
#ifdef CATCH_IMPL
# ifndef CLARA_CONFIG_MAIN
# define CLARA_CONFIG_MAIN_NOT_DEFINED
# define CLARA_CONFIG_MAIN
# endif
#endif
// start catch_user_interfaces.h
namespace Catch {
unsigned int rngSeed();
}
// end catch_user_interfaces.h
// start catch_tag_alias_autoregistrar.h
// start catch_common.h
// start catch_compiler_capabilities.h
// Detect a number of compiler features - by compiler
// The following features are defined:
//
// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
// ****************
// Note to maintainers: if new toggles are added please document them
// in configuration.md, too
// ****************
// In general each macro has a _NO_<feature name> form
// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
// Many features, at point of detection, define an _INTERNAL_ macro, so they
// can be combined, en-mass, with the _NO_ forms later.
#ifdef __cplusplus
# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
# define CATCH_CPP14_OR_GREATER
# endif
# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
# define CATCH_CPP17_OR_GREATER
# endif
#endif
// We have to avoid both ICC and Clang, because they try to mask themselves
// as gcc, and we want only GCC in this block
#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__)
# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" )
# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" )
# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
#endif
#if defined(__clang__)
# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" )
# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" )
// As of this writing, IBM XL's implementation of __builtin_constant_p has a bug
// which results in calls to destructors being emitted for each temporary,
// without a matching initialization. In practice, this can result in something
// like `std::string::~string` being called on an uninitialized value.
//
// For example, this code will likely segfault under IBM XL:
// ```
// REQUIRE(std::string("12") + "34" == "1234")
// ```
//
// Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented.
# if !defined(__ibmxl__) && !defined(__CUDACC__)
# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppguidelines-pro-type-vararg, hicpp-vararg) */
# endif
# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
_Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
_Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
_Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
_Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
_Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
_Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
#endif // __clang__
////////////////////////////////////////////////////////////////////////////////
// Assume that non-Windows platforms support posix signals by default
#if !defined(CATCH_PLATFORM_WINDOWS)
#define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
#endif
////////////////////////////////////////////////////////////////////////////////
// We know some environments not to support full POSIX signals
#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
#define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
#endif
#ifdef __OS400__
# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
# define CATCH_CONFIG_COLOUR_NONE
#endif
////////////////////////////////////////////////////////////////////////////////
// Android somehow still does not support std::to_string
#if defined(__ANDROID__)
# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
#endif
////////////////////////////////////////////////////////////////////////////////
// Not all Windows environments support SEH properly
#if defined(__MINGW32__)
# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
#endif
////////////////////////////////////////////////////////////////////////////////
// PS4
#if defined(__ORBIS__)
# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
#endif
////////////////////////////////////////////////////////////////////////////////
// Cygwin
#ifdef __CYGWIN__
// Required for some versions of Cygwin to declare gettimeofday
// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
# define _BSD_SOURCE
// some versions of cygwin (most) do not support std::to_string. Use the libstd check.
// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
&& !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
# endif
#endif // __CYGWIN__
////////////////////////////////////////////////////////////////////////////////
// Visual C++
#if defined(_MSC_VER)
# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
// Universal Windows platform does not support SEH
// Or console colours (or console at all...)
# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
# define CATCH_CONFIG_COLOUR_NONE
# else
# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
# endif
// MSVC traditional preprocessor needs some workaround for __VA_ARGS__
// _MSVC_TRADITIONAL == 0 means new conformant preprocessor
// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
# if !defined(__clang__) // Handle Clang masquerading for msvc
# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
# endif // MSVC_TRADITIONAL
# endif // __clang__
#endif // _MSC_VER
#if defined(_REENTRANT) || defined(_MSC_VER)
// Enable async processing, as -pthread is specified or no additional linking is required
# define CATCH_INTERNAL_CONFIG_USE_ASYNC
#endif // _MSC_VER
////////////////////////////////////////////////////////////////////////////////
// Check if we are compiled with -fno-exceptions or equivalent
#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
#endif
////////////////////////////////////////////////////////////////////////////////
// DJGPP
#ifdef __DJGPP__
# define CATCH_INTERNAL_CONFIG_NO_WCHAR
#endif // __DJGPP__
////////////////////////////////////////////////////////////////////////////////
// Embarcadero C++Build
#if defined(__BORLANDC__)
#define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
#endif
////////////////////////////////////////////////////////////////////////////////
// Use of __COUNTER__ is suppressed during code analysis in
// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
// handled by it.
// Otherwise all supported compilers support COUNTER macro,
// but user still might want to turn it off
#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
#define CATCH_INTERNAL_CONFIG_COUNTER
#endif
////////////////////////////////////////////////////////////////////////////////
// RTX is a special version of Windows that is real time.
// This means that it is detected as Windows, but does not provide
// the same set of capabilities as real Windows does.
#if defined(UNDER_RTSS) || defined(RTX64_BUILD)
#define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
#define CATCH_INTERNAL_CONFIG_NO_ASYNC
#define CATCH_CONFIG_COLOUR_NONE
#endif
#if !defined(_GLIBCXX_USE_C99_MATH_TR1)
#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
#endif
// Various stdlib support checks that require __has_include
#if defined(__has_include)
// Check if string_view is available and usable
#if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
# define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
#endif
// Check if optional is available and usable
# if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
# define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
# endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
// Check if byte is available and usable
# if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
# include <cstddef>
# if __cpp_lib_byte > 0
# define CATCH_INTERNAL_CONFIG_CPP17_BYTE
# endif
# endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
// Check if variant is available and usable
# if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
# if defined(__clang__) && (__clang_major__ < 8)
// work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
// fix should be in clang 8, workaround in libstdc++ 8.2
# include <ciso646>
# if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
# define CATCH_CONFIG_NO_CPP17_VARIANT
# else
# define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
# endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
# else
# define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
# endif // defined(__clang__) && (__clang_major__ < 8)
# endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
#endif // defined(__has_include)
#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
# define CATCH_CONFIG_COUNTER
#endif
#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
# define CATCH_CONFIG_WINDOWS_SEH
#endif
// This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
# define CATCH_CONFIG_POSIX_SIGNALS
#endif
// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
# define CATCH_CONFIG_WCHAR
#endif
#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
# define CATCH_CONFIG_CPP11_TO_STRING
#endif
#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
# define CATCH_CONFIG_CPP17_OPTIONAL
#endif
#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
# define CATCH_CONFIG_CPP17_STRING_VIEW
#endif
#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
# define CATCH_CONFIG_CPP17_VARIANT
#endif
#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
# define CATCH_CONFIG_CPP17_BYTE
#endif
#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
#endif
#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
# define CATCH_CONFIG_NEW_CAPTURE
#endif
#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
# define CATCH_CONFIG_DISABLE_EXCEPTIONS
#endif
#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
# define CATCH_CONFIG_POLYFILL_ISNAN
#endif
#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
# define CATCH_CONFIG_USE_ASYNC
#endif
#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
# define CATCH_CONFIG_ANDROID_LOGWRITE
#endif
#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
# define CATCH_CONFIG_GLOBAL_NEXTAFTER
#endif
// Even if we do not think the compiler has that warning, we still have
// to provide a macro that can be used by the code.
#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
#endif
#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
#endif
#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
#endif
#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
#endif
#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
#endif
#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
#endif
// The goal of this macro is to avoid evaluation of the arguments, but
// still have the compiler warn on problems inside...
#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
# define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
#endif
#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
#elif defined(__clang__) && (__clang_major__ < 5)
# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
#endif
#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
#endif
#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
#define CATCH_TRY if ((true))
#define CATCH_CATCH_ALL if ((false))
#define CATCH_CATCH_ANON(type) if ((false))
#else
#define CATCH_TRY try
#define CATCH_CATCH_ALL catch (...)
#define CATCH_CATCH_ANON(type) catch (type)
#endif
#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#endif
// end catch_compiler_capabilities.h
#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
#ifdef CATCH_CONFIG_COUNTER
# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
#else
# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
#endif
#include <iosfwd>
#include <string>
#include <cstdint>
// We need a dummy global operator<< so we can bring it into Catch namespace later
struct Catch_global_namespace_dummy {};
std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
namespace Catch {
struct CaseSensitive { enum Choice {
Yes,
No
}; };
class NonCopyable {
NonCopyable( NonCopyable const& ) = delete;
NonCopyable( NonCopyable && ) = delete;
NonCopyable& operator = ( NonCopyable const& ) = delete;
NonCopyable& operator = ( NonCopyable && ) = delete;
protected:
NonCopyable();
virtual ~NonCopyable();
};
struct SourceLineInfo {
SourceLineInfo() = delete;
SourceLineInfo( char const* _file, std::size_t _line ) noexcept
: file( _file ),
line( _line )
{}
SourceLineInfo( SourceLineInfo const& other ) = default;
SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
SourceLineInfo( SourceLineInfo&& ) noexcept = default;
SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
bool empty() const noexcept { return file[0] == '\0'; }
bool operator == ( SourceLineInfo const& other ) const noexcept;
bool operator < ( SourceLineInfo const& other ) const noexcept;
char const* file;
std::size_t line;
};
std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
// Bring in operator<< from global namespace into Catch namespace
// This is necessary because the overload of operator<< above makes
// lookup stop at namespace Catch
using ::operator<<;
// Use this in variadic streaming macros to allow
// >> +StreamEndStop
// as well as
// >> stuff +StreamEndStop
struct StreamEndStop {
std::string operator+() const;
};
template<typename T>
T const& operator + ( T const& value, StreamEndStop ) {
return value;
}
}
#define CATCH_INTERNAL_LINEINFO \
::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
// end catch_common.h
namespace Catch {
struct RegistrarForTagAliases {
RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
};
} // end namespace Catch
#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
// end catch_tag_alias_autoregistrar.h
// start catch_test_registry.h
// start catch_interfaces_testcase.h
#include <vector>
namespace Catch {
class TestSpec;
struct ITestInvoker {
virtual void invoke () const = 0;
virtual ~ITestInvoker();
};
class TestCase;
struct IConfig;
struct ITestCaseRegistry {
virtual ~ITestCaseRegistry();
virtual std::vector<TestCase> const& getAllTests() const = 0;
virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
};
bool isThrowSafe( TestCase const& testCase, IConfig const& config );
bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
}
// end catch_interfaces_testcase.h
// start catch_stringref.h
#include <cstddef>
#include <string>
#include <iosfwd>
#include <cassert>
namespace Catch {
/// A non-owning string class (similar to the forthcoming std::string_view)
/// Note that, because a StringRef may be a substring of another string,
/// it may not be null terminated.
class StringRef {
public:
using size_type = std::size_t;
using const_iterator = const char*;
private:
static constexpr char const* const s_empty = "";
char const* m_start = s_empty;
size_type m_size = 0;
public: // construction
constexpr StringRef() noexcept = default;
StringRef( char const* rawChars ) noexcept;
constexpr StringRef( char const* rawChars, size_type size ) noexcept
: m_start( rawChars ),
m_size( size )
{}
StringRef( std::string const& stdString ) noexcept
: m_start( stdString.c_str() ),
m_size( stdString.size() )
{}
explicit operator std::string() const {
return std::string(m_start, m_size);
}
public: // operators
auto operator == ( StringRef const& other ) const noexcept -> bool;
auto operator != (StringRef const& other) const noexcept -> bool {
return !(*this == other);
}
auto operator[] ( size_type index ) const noexcept -> char {
assert(index < m_size);
return m_start[index];
}
public: // named queries
constexpr auto empty() const noexcept -> bool {
return m_size == 0;
}
constexpr auto size() const noexcept -> size_type {
return m_size;
}
// Returns the current start pointer. If the StringRef is not
// null-terminated, throws std::domain_exception
auto c_str() const -> char const*;
public: // substrings and searches
// Returns a substring of [start, start + length).
// If start + length > size(), then the substring is [start, size()).
// If start > size(), then the substring is empty.
auto substr( size_type start, size_type length ) const noexcept -> StringRef;
// Returns the current start pointer. May not be null-terminated.
auto data() const noexcept -> char const*;
constexpr auto isNullTerminated() const noexcept -> bool {
return m_start[m_size] == '\0';
}
public: // iterators
constexpr const_iterator begin() const { return m_start; }
constexpr const_iterator end() const { return m_start + m_size; }
};
auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
return StringRef( rawChars, size );
}
} // namespace Catch
constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
return Catch::StringRef( rawChars, size );
}
// end catch_stringref.h
// start catch_preprocessor.hpp
#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
// MSVC needs more evaluations
#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
#else
#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
#endif
#define CATCH_REC_END(...)
#define CATCH_REC_OUT
#define CATCH_EMPTY()
#define CATCH_DEFER(id) id CATCH_EMPTY()
#define CATCH_REC_GET_END2() 0, CATCH_REC_END
#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
// and passes userdata as the first parameter to each invocation,
// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
#else
// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
#endif
#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
#else
#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
#endif
#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define INTERNAL_CATCH_TYPE_GEN\
template<typename...> struct TypeList {};\
template<typename...Ts>\
constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
template<template<typename...> class...> struct TemplateTypeList{};\
template<template<typename...> class...Cs>\
constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
template<typename...>\
struct append;\
template<typename...>\
struct rewrap;\
template<template<typename...> class, typename...>\
struct create;\
template<template<typename...> class, typename>\
struct convert;\
\
template<typename T> \
struct append<T> { using type = T; };\
template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
template< template<typename...> class L1, typename...E1, typename...Rest>\
struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
\
template< template<typename...> class Container, template<typename...> class List, typename...elems>\
struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
\
template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
#define INTERNAL_CATCH_NTTP_1(signature, ...)\
template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
\
template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
#define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
#define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
static void TestName()
#define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
static void TestName()
#define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
#define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
static void TestName()
#define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
static void TestName()
#define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
template<typename Type>\
void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
{\
Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
}
#define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
{\
Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
}
#define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
template<typename Type>\
void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
{\
Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
}
#define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
{\
Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
}
#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
template<typename TestType> \
struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
void test();\
}
#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
void test();\
}
#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
template<typename TestType> \
void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_NTTP_0
#define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)
#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
#else
#define INTERNAL_CATCH_NTTP_0(signature)
#define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))
#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
#endif
// end catch_preprocessor.hpp
// start catch_meta.hpp
#include <type_traits>
namespace Catch {
template<typename T>
struct always_false : std::false_type {};
template <typename> struct true_given : std::true_type {};
struct is_callable_tester {
template <typename Fun, typename... Args>
true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
template <typename...>
std::false_type static test(...);
};
template <typename T>
struct is_callable;
template <typename Fun, typename... Args>
struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
#if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
// std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
// replaced with std::invoke_result here.
template <typename Func, typename... U>
using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
#else
// Keep ::type here because we still support C++11
template <typename Func, typename... U>
using FunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
#endif
} // namespace Catch
namespace mpl_{
struct na;
}
// end catch_meta.hpp
namespace Catch {
template<typename C>
class TestInvokerAsMethod : public ITestInvoker {
void (C::*m_testAsMethod)();
public:
TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
void invoke() const override {
C obj;
(obj.*m_testAsMethod)();
}
};
auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
template<typename C>
auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
}
struct NameAndTags {
NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
StringRef name;
StringRef tags;
};
struct AutoReg : NonCopyable {
AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
~AutoReg();
};
} // end namespace Catch
#if defined(CATCH_CONFIG_DISABLE)
#define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
static void TestName()
#define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
namespace{ \
struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
void test(); \
}; \
} \
void TestName::test()
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
namespace{ \
namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
} \
} \
INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
#else
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
#endif
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
#else
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
#endif
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
#else
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
#endif
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
#else
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
#endif
#endif
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
static void TestName(); \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
static void TestName()
#define INTERNAL_CATCH_TESTCASE( ... ) \
INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
namespace{ \
struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
void test(); \
}; \
Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
} \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
void TestName::test()
#define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
namespace {\
namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
INTERNAL_CATCH_TYPE_GEN\
INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
template<typename...Types> \
struct TestName{\
TestName(){\
int index = 0; \
constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
using expander = int[];\
(void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
}\
};\
static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
return 0;\
}();\
}\
}\
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
#else
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
#endif
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
#else
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
#endif
#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
template<typename TestType> static void TestFuncName(); \
namespace {\
namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
INTERNAL_CATCH_TYPE_GEN \
INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
template<typename... Types> \
struct TestName { \
void reg_tests() { \
int index = 0; \
using expander = int[]; \
constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
(void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */\
} \
}; \
static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
TestInit t; \
t.reg_tests(); \
return 0; \
}(); \
} \
} \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
template<typename TestType> \
static void TestFuncName()
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__)
#else
#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) )
#endif
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__)
#else
#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
#endif
#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
template<typename TestType> static void TestFunc(); \
namespace {\
namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
INTERNAL_CATCH_TYPE_GEN\
template<typename... Types> \
struct TestName { \
void reg_tests() { \
int index = 0; \
using expander = int[]; \
(void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */\
} \
};\
static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
using TestInit = typename convert<TestName, TmplList>::type; \
TestInit t; \
t.reg_tests(); \
return 0; \
}(); \
}}\
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
template<typename TestType> \
static void TestFunc()
#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList )
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
namespace {\
namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
INTERNAL_CATCH_TYPE_GEN\
INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
template<typename...Types> \
struct TestNameClass{\
TestNameClass(){\
int index = 0; \
constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
using expander = int[];\
(void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
}\
};\
static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
return 0;\
}();\
}\
}\
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
#else
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
#endif
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
#else
#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
#endif
#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
template<typename TestType> \
struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
void test();\
};\
namespace {\
namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
INTERNAL_CATCH_TYPE_GEN \
INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
template<typename...Types>\
struct TestNameClass{\
void reg_tests(){\
int index = 0;\
using expander = int[];\
constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
(void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */ \
}\
};\
static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\
TestInit t;\
t.reg_tests();\
return 0;\
}(); \
}\
}\
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
template<typename TestType> \
void TestName<TestType>::test()
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ )
#else
#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) )
#endif
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ )
#else
#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) )
#endif
#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
template<typename TestType> \
struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
void test();\
};\
namespace {\
namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
INTERNAL_CATCH_TYPE_GEN\
template<typename...Types>\
struct TestNameClass{\
void reg_tests(){\
int index = 0;\
using expander = int[];\
(void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */ \
}\
};\
static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
using TestInit = typename convert<TestNameClass, TmplList>::type;\
TestInit t;\
t.reg_tests();\
return 0;\
}(); \
}}\
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
template<typename TestType> \
void TestName<TestType>::test()
#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList )
// end catch_test_registry.h
// start catch_capture.hpp
// start catch_assertionhandler.h
// start catch_assertioninfo.h
// start catch_result_type.h
namespace Catch {
// ResultWas::OfType enum
struct ResultWas { enum OfType {
Unknown = -1,
Ok = 0,
Info = 1,
Warning = 2,
FailureBit = 0x10,
ExpressionFailed = FailureBit | 1,
ExplicitFailure = FailureBit | 2,
Exception = 0x100 | FailureBit,
ThrewException = Exception | 1,
DidntThrowException = Exception | 2,
FatalErrorCondition = 0x200 | FailureBit
}; };
bool isOk( ResultWas::OfType resultType );
bool isJustInfo( int flags );
// ResultDisposition::Flags enum
struct ResultDisposition { enum Flags {
Normal = 0x01,
ContinueOnFailure = 0x02, // Failures fail test, but execution continues
FalseTest = 0x04, // Prefix expression with !
SuppressFail = 0x08 // Failures are reported but do not fail the test
}; };
ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
bool shouldContinueOnFailure( int flags );
inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
bool shouldSuppressFailure( int flags );
} // end namespace Catch
// end catch_result_type.h
namespace Catch {
struct AssertionInfo
{
StringRef macroName;
SourceLineInfo lineInfo;
StringRef capturedExpression;
ResultDisposition::Flags resultDisposition;
// We want to delete this constructor but a compiler bug in 4.8 means
// the struct is then treated as non-aggregate
//AssertionInfo() = delete;
};
} // end namespace Catch
// end catch_assertioninfo.h
// start catch_decomposer.h
// start catch_tostring.h
#include <vector>
#include <cstddef>
#include <type_traits>
#include <string>
// start catch_stream.h
#include <iosfwd>
#include <cstddef>
#include <ostream>
namespace Catch {
std::ostream& cout();
std::ostream& cerr();
std::ostream& clog();
class StringRef;
struct IStream {
virtual ~IStream();
virtual std::ostream& stream() const = 0;
};
auto makeStream( StringRef const &filename ) -> IStream const*;
class ReusableStringStream : NonCopyable {
std::size_t m_index;
std::ostream* m_oss;
public:
ReusableStringStream();
~ReusableStringStream();
auto str() const -> std::string;
template<typename T>
auto operator << ( T const& value ) -> ReusableStringStream& {
*m_oss << value;
return *this;
}
auto get() -> std::ostream& { return *m_oss; }
};
}
// end catch_stream.h
// start catch_interfaces_enum_values_registry.h
#include <vector>
namespace Catch {
namespace Detail {
struct EnumInfo {
StringRef m_name;
std::vector<std::pair<int, StringRef>> m_values;
~EnumInfo();
StringRef lookup( int value ) const;
};
} // namespace Detail
struct IMutableEnumValuesRegistry {
virtual ~IMutableEnumValuesRegistry();
virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
template<typename E>
Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
std::vector<int> intValues;
intValues.reserve( values.size() );
for( auto enumValue : values )
intValues.push_back( static_cast<int>( enumValue ) );
return registerEnum( enumName, allEnums, intValues );
}
};
} // Catch
// end catch_interfaces_enum_values_registry.h
#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
#include <string_view>
#endif
#ifdef __OBJC__
// start catch_objc_arc.hpp
#import <Foundation/Foundation.h>
#ifdef __has_feature
#define CATCH_ARC_ENABLED __has_feature(objc_arc)
#else
#define CATCH_ARC_ENABLED 0
#endif
void arcSafeRelease( NSObject* obj );
id performOptionalSelector( id obj, SEL sel );
#if !CATCH_ARC_ENABLED
inline void arcSafeRelease( NSObject* obj ) {
[obj release];
}
inline id performOptionalSelector( id obj, SEL sel ) {
if( [obj respondsToSelector: sel] )
return [obj performSelector: sel];
return nil;
}
#define CATCH_UNSAFE_UNRETAINED
#define CATCH_ARC_STRONG
#else
inline void arcSafeRelease( NSObject* ){}
inline id performOptionalSelector( id obj, SEL sel ) {
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
#endif
if( [obj respondsToSelector: sel] )
return [obj performSelector: sel];
#ifdef __clang__
#pragma clang diagnostic pop
#endif
return nil;
}
#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
#define CATCH_ARC_STRONG __strong
#endif
// end catch_objc_arc.hpp
#endif
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
#endif
namespace Catch {
namespace Detail {
extern const std::string unprintableString;
std::string rawMemoryToString( const void *object, std::size_t size );
template<typename T>
std::string rawMemoryToString( const T& object ) {
return rawMemoryToString( &object, sizeof(object) );
}
template<typename T>
class IsStreamInsertable {
template<typename Stream, typename U>
static auto test(int)
-> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
template<typename, typename>
static auto test(...)->std::false_type;
public:
static const bool value = decltype(test<std::ostream, const T&>(0))::value;
};
template<typename E>
std::string convertUnknownEnumToString( E e );
template<typename T>
typename std::enable_if<
!std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
std::string>::type convertUnstreamable( T const& ) {
return Detail::unprintableString;
}
template<typename T>
typename std::enable_if<
!std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
std::string>::type convertUnstreamable(T const& ex) {
return ex.what();
}
template<typename T>
typename std::enable_if<
std::is_enum<T>::value
, std::string>::type convertUnstreamable( T const& value ) {
return convertUnknownEnumToString( value );
}
#if defined(_MANAGED)
//! Convert a CLR string to a utf8 std::string
template<typename T>
std::string clrReferenceToString( T^ ref ) {
if (ref == nullptr)
return std::string("null");
auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
cli::pin_ptr<System::Byte> p = &bytes[0];
return std::string(reinterpret_cast<char const *>(p), bytes->Length);
}
#endif
} // namespace Detail
// If we decide for C++14, change these to enable_if_ts
template <typename T, typename = void>
struct StringMaker {
template <typename Fake = T>
static
typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
convert(const Fake& value) {
ReusableStringStream rss;
// NB: call using the function-like syntax to avoid ambiguity with
// user-defined templated operator<< under clang.
rss.operator<<(value);
return rss.str();
}
template <typename Fake = T>
static
typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
convert( const Fake& value ) {
#if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
return Detail::convertUnstreamable(value);
#else
return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
#endif
}
};
namespace Detail {
// This function dispatches all stringification requests inside of Catch.
// Should be preferably called fully qualified, like ::Catch::Detail::stringify
template <typename T>
std::string stringify(const T& e) {
return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
}
template<typename E>
std::string convertUnknownEnumToString( E e ) {
return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
}
#if defined(_MANAGED)
template <typename T>
std::string stringify( T^ e ) {
return ::Catch::StringMaker<T^>::convert(e);
}
#endif
} // namespace Detail
// Some predefined specializations
template<>
struct StringMaker<std::string> {
static std::string convert(const std::string& str);
};
#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
template<>
struct StringMaker<std::string_view> {
static std::string convert(std::string_view str);
};
#endif
template<>
struct StringMaker<char const *> {
static std::string convert(char const * str);
};
template<>
struct StringMaker<char *> {
static std::string convert(char * str);
};
#ifdef CATCH_CONFIG_WCHAR
template<>
struct StringMaker<std::wstring> {
static std::string convert(const std::wstring& wstr);
};
# ifdef CATCH_CONFIG_CPP17_STRING_VIEW
template<>
struct StringMaker<std::wstring_view> {
static std::string convert(std::wstring_view str);
};
# endif
template<>
struct StringMaker<wchar_t const *> {
static std::string convert(wchar_t const * str);
};
template<>
struct StringMaker<wchar_t *> {
static std::string convert(wchar_t * str);
};
#endif
// TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
// while keeping string semantics?
template<int SZ>
struct StringMaker<char[SZ]> {
static std::string convert(char const* str) {
return ::Catch::Detail::stringify(std::string{ str });
}
};
template<int SZ>
struct StringMaker<signed char[SZ]> {
static std::string convert(signed char const* str) {
return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
}
};
template<int SZ>
struct StringMaker<unsigned char[SZ]> {
static std::string convert(unsigned char const* str) {
return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
}
};
#if defined(CATCH_CONFIG_CPP17_BYTE)
template<>
struct StringMaker<std::byte> {
static std::string convert(std::byte value);
};
#endif // defined(CATCH_CONFIG_CPP17_BYTE)
template<>
struct StringMaker<int> {
static std::string convert(int value);
};
template<>
struct StringMaker<long> {
static std::string convert(long value);
};
template<>
struct StringMaker<long long> {
static std::string convert(long long value);
};
template<>
struct StringMaker<unsigned int> {
static std::string convert(unsigned int value);
};
template<>
struct StringMaker<unsigned long> {
static std::string convert(unsigned long value);
};
template<>
struct StringMaker<unsigned long long> {
static std::string convert(unsigned long long value);
};
template<>
struct StringMaker<bool> {
static std::string convert(bool b);
};
template<>
struct StringMaker<char> {
static std::string convert(char c);
};
template<>
struct StringMaker<signed char> {
static std::string convert(signed char c);
};
template<>
struct StringMaker<unsigned char> {
static std::string convert(unsigned char c);
};
template<>
struct StringMaker<std::nullptr_t> {
static std::string convert(std::nullptr_t);
};
template<>
struct StringMaker<float> {
static std::string convert(float value);
static int precision;
};
template<>
struct StringMaker<double> {
static std::string convert(double value);
static int precision;
};
template <typename T>
struct StringMaker<T*> {
template <typename U>
static std::string convert(U* p) {
if (p) {
return ::Catch::Detail::rawMemoryToString(p);
} else {
return "nullptr";
}
}
};
template <typename R, typename C>
struct StringMaker<R C::*> {
static std::string convert(R C::* p) {
if (p) {
return ::Catch::Detail::rawMemoryToString(p);
} else {
return "nullptr";
}
}
};
#if defined(_MANAGED)
template <typename T>
struct StringMaker<T^> {
static std::string convert( T^ ref ) {
return ::Catch::Detail::clrReferenceToString(ref);
}
};
#endif
namespace Detail {
template<typename InputIterator, typename Sentinel = InputIterator>
std::string rangeToString(InputIterator first, Sentinel last) {
ReusableStringStream rss;
rss << "{ ";
if (first != last) {
rss << ::Catch::Detail::stringify(*first);
for (++first; first != last; ++first)
rss << ", " << ::Catch::Detail::stringify(*first);
}
rss << " }";
return rss.str();
}
}
#ifdef __OBJC__
template<>
struct StringMaker<NSString*> {
static std::string convert(NSString * nsstring) {
if (!nsstring)
return "nil";
return std::string("@") + [nsstring UTF8String];
}
};
template<>
struct StringMaker<NSObject*> {
static std::string convert(NSObject* nsObject) {
return ::Catch::Detail::stringify([nsObject description]);
}
};
namespace Detail {
inline std::string stringify( NSString* nsstring ) {
return StringMaker<NSString*>::convert( nsstring );
}
} // namespace Detail
#endif // __OBJC__
} // namespace Catch
//////////////////////////////////////////////////////
// Separate std-lib types stringification, so it can be selectively enabled
// This means that we do not bring in
#if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
# define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
# define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
# define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
# define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
#endif
// Separate std::pair specialization
#if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
#include <utility>
namespace Catch {
template<typename T1, typename T2>
struct StringMaker<std::pair<T1, T2> > {
static std::string convert(const std::pair<T1, T2>& pair) {
ReusableStringStream rss;
rss << "{ "
<< ::Catch::Detail::stringify(pair.first)
<< ", "
<< ::Catch::Detail::stringify(pair.second)
<< " }";
return rss.str();
}
};
}
#endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
#if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
#include <optional>
namespace Catch {
template<typename T>
struct StringMaker<std::optional<T> > {
static std::string convert(const std::optional<T>& optional) {
ReusableStringStream rss;
if (optional.has_value()) {
rss << ::Catch::Detail::stringify(*optional);
} else {
rss << "{ }";
}
return rss.str();
}
};
}
#endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
// Separate std::tuple specialization
#if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
#include <tuple>
namespace Catch {
namespace Detail {
template<
typename Tuple,
std::size_t N = 0,
bool = (N < std::tuple_size<Tuple>::value)
>
struct TupleElementPrinter {
static void print(const Tuple& tuple, std::ostream& os) {
os << (N ? ", " : " ")
<< ::Catch::Detail::stringify(std::get<N>(tuple));
TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
}
};
template<
typename Tuple,
std::size_t N
>
struct TupleElementPrinter<Tuple, N, false> {
static void print(const Tuple&, std::ostream&) {}
};
}
template<typename ...Types>
struct StringMaker<std::tuple<Types...>> {
static std::string convert(const std::tuple<Types...>& tuple) {
ReusableStringStream rss;
rss << '{';
Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
rss << " }";
return rss.str();
}
};
}
#endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
#if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
#include <variant>
namespace Catch {
template<>
struct StringMaker<std::monostate> {
static std::string convert(const std::monostate&) {
return "{ }";
}
};
template<typename... Elements>
struct StringMaker<std::variant<Elements...>> {
static std::string convert(const std::variant<Elements...>& variant) {
if (variant.valueless_by_exception()) {
return "{valueless variant}";
} else {
return std::visit(
[](const auto& value) {
return ::Catch::Detail::stringify(value);
},
variant
);
}
}
};
}
#endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
namespace Catch {
// Import begin/ end from std here
using std::begin;
using std::end;
namespace detail {
template <typename...>
struct void_type {
using type = void;
};
template <typename T, typename = void>
struct is_range_impl : std::false_type {
};
template <typename T>
struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type> : std::true_type {
};
} // namespace detail
template <typename T>
struct is_range : detail::is_range_impl<T> {
};
#if defined(_MANAGED) // Managed types are never ranges
template <typename T>
struct is_range<T^> {
static const bool value = false;
};
#endif
template<typename Range>
std::string rangeToString( Range const& range ) {
return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
}
// Handle vector<bool> specially
template<typename Allocator>
std::string rangeToString( std::vector<bool, Allocator> const& v ) {
ReusableStringStream rss;
rss << "{ ";
bool first = true;
for( bool b : v ) {
if( first )
first = false;
else
rss << ", ";
rss << ::Catch::Detail::stringify( b );
}
rss << " }";
return rss.str();
}
template<typename R>
struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
static std::string convert( R const& range ) {
return rangeToString( range );
}
};
template <typename T, int SZ>
struct StringMaker<T[SZ]> {
static std::string convert(T const(&arr)[SZ]) {
return rangeToString(arr);
}
};
} // namespace Catch
// Separate std::chrono::duration specialization
#if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
#include <ctime>
#include <ratio>
#include <chrono>
namespace Catch {
template <class Ratio>
struct ratio_string {
static std::string symbol();
};
template <class Ratio>
std::string ratio_string<Ratio>::symbol() {
Catch::ReusableStringStream rss;
rss << '[' << Ratio::num << '/'
<< Ratio::den << ']';
return rss.str();
}
template <>
struct ratio_string<std::atto> {
static std::string symbol();
};
template <>
struct ratio_string<std::femto> {
static std::string symbol();
};
template <>
struct ratio_string<std::pico> {
static std::string symbol();
};
template <>
struct ratio_string<std::nano> {
static std::string symbol();
};
template <>
struct ratio_string<std::micro> {
static std::string symbol();
};
template <>
struct ratio_string<std::milli> {
static std::string symbol();
};
////////////
// std::chrono::duration specializations
template<typename Value, typename Ratio>
struct StringMaker<std::chrono::duration<Value, Ratio>> {
static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
ReusableStringStream rss;
rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
return rss.str();
}
};
template<typename Value>
struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
ReusableStringStream rss;
rss << duration.count() << " s";
return rss.str();
}
};
template<typename Value>
struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
ReusableStringStream rss;
rss << duration.count() << " m";
return rss.str();
}
};
template<typename Value>
struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
ReusableStringStream rss;
rss << duration.count() << " h";
return rss.str();
}
};
////////////
// std::chrono::time_point specialization
// Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
template<typename Clock, typename Duration>
struct StringMaker<std::chrono::time_point<Clock, Duration>> {
static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
}
};
// std::chrono::time_point<system_clock> specialization
template<typename Duration>
struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
auto converted = std::chrono::system_clock::to_time_t(time_point);
#ifdef _MSC_VER
std::tm timeInfo = {};
gmtime_s(&timeInfo, &converted);
#else
std::tm* timeInfo = std::gmtime(&converted);
#endif
auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
char timeStamp[timeStampSize];
const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
#ifdef _MSC_VER
std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
#else
std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
#endif
return std::string(timeStamp);
}
};
}
#endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
#define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
namespace Catch { \
template<> struct StringMaker<enumName> { \
static std::string convert( enumName value ) { \
static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
} \
}; \
}
#define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// end catch_tostring.h
#include <iosfwd>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4389) // '==' : signed/unsigned mismatch
#pragma warning(disable:4018) // more "signed/unsigned mismatch"
#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
#pragma warning(disable:4180) // qualifier applied to function type has no meaning
#pragma warning(disable:4800) // Forcing result to true or false
#endif
namespace Catch {
struct ITransientExpression {
auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
auto getResult() const -> bool { return m_result; }
virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
ITransientExpression( bool isBinaryExpression, bool result )
: m_isBinaryExpression( isBinaryExpression ),
m_result( result )
{}
// We don't actually need a virtual destructor, but many static analysers
// complain if it's not here :-(
virtual ~ITransientExpression();
bool m_isBinaryExpression;
bool m_result;
};
void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
template<typename LhsT, typename RhsT>
class BinaryExpr : public ITransientExpression {
LhsT m_lhs;
StringRef m_op;
RhsT m_rhs;
void streamReconstructedExpression( std::ostream &os ) const override {
formatReconstructedExpression
( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
}
public:
BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
: ITransientExpression{ true, comparisonResult },
m_lhs( lhs ),
m_op( op ),
m_rhs( rhs )
{}
template<typename T>
auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
static_assert(always_false<T>::value,
"chained comparisons are not supported inside assertions, "
"wrap the expression inside parentheses, or decompose it");
}
template<typename T>
auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
static_assert(always_false<T>::value,
"chained comparisons are not supported inside assertions, "
"wrap the expression inside parentheses, or decompose it");
}
template<typename T>
auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
static_assert(always_false<T>::value,
"chained comparisons are not supported inside assertions, "
"wrap the expression inside parentheses, or decompose it");
}
template<typename T>
auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
static_assert(always_false<T>::value,
"chained comparisons are not supported inside assertions, "
"wrap the expression inside parentheses, or decompose it");
}
template<typename T>
auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
static_assert(always_false<T>::value,
"chained comparisons are not supported inside assertions, "
"wrap the expression inside parentheses, or decompose it");
}
template<typename T>
auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
static_assert(always_false<T>::value,
"chained comparisons are not supported inside assertions, "
"wrap the expression inside parentheses, or decompose it");
}
template<typename T>
auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
static_assert(always_false<T>::value,
"chained comparisons are not supported inside assertions, "
"wrap the expression inside parentheses, or decompose it");
}
template<typename T>
auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
static_assert(always_false<T>::value,
"chained comparisons are not supported inside assertions, "
"wrap the expression inside parentheses, or decompose it");
}
};
template<typename LhsT>
class UnaryExpr : public ITransientExpression {
LhsT m_lhs;
void streamReconstructedExpression( std::ostream &os ) const override {
os << Catch::Detail::stringify( m_lhs );
}
public:
explicit UnaryExpr( LhsT lhs )
: ITransientExpression{ false, static_cast<bool>(lhs) },
m_lhs( lhs )
{}
};
// Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
template<typename LhsT, typename RhsT>
auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
template<typename T>
auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
template<typename T>
auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
template<typename T>
auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
template<typename T>
auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
template<typename LhsT, typename RhsT>
auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
template<typename T>
auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
template<typename T>
auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
template<typename T>
auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
template<typename T>
auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
template<typename LhsT>
class ExprLhs {
LhsT m_lhs;
public:
explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
template<typename RhsT>
auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
}
auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
return { m_lhs == rhs, m_lhs, "==", rhs };
}
template<typename RhsT>
auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
}
auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
return { m_lhs != rhs, m_lhs, "!=", rhs };
}
template<typename RhsT>
auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
}
template<typename RhsT>
auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
}
template<typename RhsT>
auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
}
template<typename RhsT>
auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
}
template <typename RhsT>
auto operator | (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
return { static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs };
}
template <typename RhsT>
auto operator & (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
return { static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs };
}
template <typename RhsT>
auto operator ^ (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
return { static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs };
}
template<typename RhsT>
auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
static_assert(always_false<RhsT>::value,
"operator&& is not supported inside assertions, "
"wrap the expression inside parentheses, or decompose it");
}
template<typename RhsT>
auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
static_assert(always_false<RhsT>::value,
"operator|| is not supported inside assertions, "
"wrap the expression inside parentheses, or decompose it");
}
auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
return UnaryExpr<LhsT>{ m_lhs };
}
};
void handleExpression( ITransientExpression const& expr );
template<typename T>
void handleExpression( ExprLhs<T> const& expr ) {
handleExpression( expr.makeUnaryExpr() );
}
struct Decomposer {
template<typename T>
auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
return ExprLhs<T const&>{ lhs };
}
auto operator <=( bool value ) -> ExprLhs<bool> {
return ExprLhs<bool>{ value };
}
};
} // end namespace Catch
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// end catch_decomposer.h
// start catch_interfaces_capture.h
#include <string>
#include <chrono>
namespace Catch {
class AssertionResult;
struct AssertionInfo;
struct SectionInfo;
struct SectionEndInfo;
struct MessageInfo;
struct MessageBuilder;
struct Counts;
struct AssertionReaction;
struct SourceLineInfo;
struct ITransientExpression;
struct IGeneratorTracker;
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
struct BenchmarkInfo;
template <typename Duration = std::chrono::duration<double, std::nano>>
struct BenchmarkStats;
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
struct IResultCapture {
virtual ~IResultCapture();
virtual bool sectionStarted( SectionInfo const& sectionInfo,
Counts& assertions ) = 0;
virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
virtual void benchmarkPreparing( std::string const& name ) = 0;
virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
virtual void benchmarkFailed( std::string const& error ) = 0;
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
virtual void pushScopedMessage( MessageInfo const& message ) = 0;
virtual void popScopedMessage( MessageInfo const& message ) = 0;
virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
virtual void handleFatalErrorCondition( StringRef message ) = 0;
virtual void handleExpr
( AssertionInfo const& info,
ITransientExpression const& expr,
AssertionReaction& reaction ) = 0;
virtual void handleMessage
( AssertionInfo const& info,
ResultWas::OfType resultType,
StringRef const& message,
AssertionReaction& reaction ) = 0;
virtual void handleUnexpectedExceptionNotThrown
( AssertionInfo const& info,
AssertionReaction& reaction ) = 0;
virtual void handleUnexpectedInflightException
( AssertionInfo const& info,
std::string const& message,
AssertionReaction& reaction ) = 0;
virtual void handleIncomplete
( AssertionInfo const& info ) = 0;
virtual void handleNonExpr
( AssertionInfo const &info,
ResultWas::OfType resultType,
AssertionReaction &reaction ) = 0;
virtual bool lastAssertionPassed() = 0;
virtual void assertionPassed() = 0;
// Deprecated, do not use:
virtual std::string getCurrentTestName() const = 0;
virtual const AssertionResult* getLastResult() const = 0;
virtual void exceptionEarlyReported() = 0;
};
IResultCapture& getResultCapture();
}
// end catch_interfaces_capture.h
namespace Catch {
struct TestFailureException{};
struct AssertionResultData;
struct IResultCapture;
class RunContext;
class LazyExpression {
friend class AssertionHandler;
friend struct AssertionStats;
friend class RunContext;
ITransientExpression const* m_transientExpression = nullptr;
bool m_isNegated;
public:
LazyExpression( bool isNegated );
LazyExpression( LazyExpression const& other );
LazyExpression& operator = ( LazyExpression const& ) = delete;
explicit operator bool() const;
friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
};
struct AssertionReaction {
bool shouldDebugBreak = false;
bool shouldThrow = false;
};
class AssertionHandler {
AssertionInfo m_assertionInfo;
AssertionReaction m_reaction;
bool m_completed = false;
IResultCapture& m_resultCapture;
public:
AssertionHandler
( StringRef const& macroName,
SourceLineInfo const& lineInfo,
StringRef capturedExpression,
ResultDisposition::Flags resultDisposition );
~AssertionHandler() {
if ( !m_completed ) {
m_resultCapture.handleIncomplete( m_assertionInfo );
}
}
template<typename T>
void handleExpr( ExprLhs<T> const& expr ) {
handleExpr( expr.makeUnaryExpr() );
}
void handleExpr( ITransientExpression const& expr );
void handleMessage(ResultWas::OfType resultType, StringRef const& message);
void handleExceptionThrownAsExpected();
void handleUnexpectedExceptionNotThrown();
void handleExceptionNotThrownAsExpected();
void handleThrowingCallSkipped();
void handleUnexpectedInflightException();
void complete();
void setCompleted();
// query
auto allowThrows() const -> bool;
};
void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
} // namespace Catch
// end catch_assertionhandler.h
// start catch_message.h
#include <string>
#include <vector>
namespace Catch {
struct MessageInfo {
MessageInfo( StringRef const& _macroName,
SourceLineInfo const& _lineInfo,
ResultWas::OfType _type );
StringRef macroName;
std::string message;
SourceLineInfo lineInfo;
ResultWas::OfType type;
unsigned int sequence;
bool operator == ( MessageInfo const& other ) const;
bool operator < ( MessageInfo const& other ) const;
private:
static unsigned int globalCount;
};
struct MessageStream {
template<typename T>
MessageStream& operator << ( T const& value ) {
m_stream << value;
return *this;
}
ReusableStringStream m_stream;
};
struct MessageBuilder : MessageStream {
MessageBuilder( StringRef const& macroName,
SourceLineInfo const& lineInfo,
ResultWas::OfType type );
template<typename T>
MessageBuilder& operator << ( T const& value ) {
m_stream << value;
return *this;
}
MessageInfo m_info;
};
class ScopedMessage {
public:
explicit ScopedMessage( MessageBuilder const& builder );
ScopedMessage( ScopedMessage& duplicate ) = delete;
ScopedMessage( ScopedMessage&& old );
~ScopedMessage();
MessageInfo m_info;
bool m_moved;
};
class Capturer {
std::vector<MessageInfo> m_messages;
IResultCapture& m_resultCapture = getResultCapture();
size_t m_captured = 0;
public:
Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
~Capturer();
void captureValue( size_t index, std::string const& value );
template<typename T>
void captureValues( size_t index, T const& value ) {
captureValue( index, Catch::Detail::stringify( value ) );
}
template<typename T, typename... Ts>
void captureValues( size_t index, T const& value, Ts const&... values ) {
captureValue( index, Catch::Detail::stringify(value) );
captureValues( index+1, values... );
}
};
} // end namespace Catch
// end catch_message.h
#if !defined(CATCH_CONFIG_DISABLE)
#if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
#define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
#else
#define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
#endif
#if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
///////////////////////////////////////////////////////////////////////////////
// Another way to speed-up compilation is to omit local try-catch for REQUIRE*
// macros.
#define INTERNAL_CATCH_TRY
#define INTERNAL_CATCH_CATCH( capturer )
#else // CATCH_CONFIG_FAST_COMPILE
#define INTERNAL_CATCH_TRY try
#define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
#endif
#define INTERNAL_CATCH_REACT( handler ) handler.complete();
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
do { \
CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
INTERNAL_CATCH_TRY { \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
} INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
} while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
if( Catch::getResultCapture().lastAssertionPassed() )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
if( !Catch::getResultCapture().lastAssertionPassed() )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
do { \
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
try { \
static_cast<void>(__VA_ARGS__); \
catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
} \
catch( ... ) { \
catchAssertionHandler.handleUnexpectedInflightException(); \
} \
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
} while( false )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
do { \
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
if( catchAssertionHandler.allowThrows() ) \
try { \
static_cast<void>(__VA_ARGS__); \
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
} \
catch( ... ) { \
catchAssertionHandler.handleExceptionThrownAsExpected(); \
} \
else \
catchAssertionHandler.handleThrowingCallSkipped(); \
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
} while( false )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
do { \
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
if( catchAssertionHandler.allowThrows() ) \
try { \
static_cast<void>(expr); \
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
} \
catch( exceptionType const& ) { \
catchAssertionHandler.handleExceptionThrownAsExpected(); \
} \
catch( ... ) { \
catchAssertionHandler.handleUnexpectedInflightException(); \
} \
else \
catchAssertionHandler.handleThrowingCallSkipped(); \
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
} while( false )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
do { \
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
} while( false )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
varName.captureValues( 0, __VA_ARGS__ )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_INFO( macroName, log ) \
Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
///////////////////////////////////////////////////////////////////////////////
// Although this is matcher-based, it can be used with just a string
#define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
do { \
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
if( catchAssertionHandler.allowThrows() ) \
try { \
static_cast<void>(__VA_ARGS__); \
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
} \
catch( ... ) { \
Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
} \
else \
catchAssertionHandler.handleThrowingCallSkipped(); \
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
} while( false )
#endif // CATCH_CONFIG_DISABLE
// end catch_capture.hpp
// start catch_section.h
// start catch_section_info.h
// start catch_totals.h
#include <cstddef>
namespace Catch {
struct Counts {
Counts operator - ( Counts const& other ) const;
Counts& operator += ( Counts const& other );
std::size_t total() const;
bool allPassed() const;
bool allOk() const;
std::size_t passed = 0;
std::size_t failed = 0;
std::size_t failedButOk = 0;
};
struct Totals {
Totals operator - ( Totals const& other ) const;
Totals& operator += ( Totals const& other );
Totals delta( Totals const& prevTotals ) const;
int error = 0;
Counts assertions;
Counts testCases;
};
}
// end catch_totals.h
#include <string>
namespace Catch {
struct SectionInfo {
SectionInfo
( SourceLineInfo const& _lineInfo,
std::string const& _name );
// Deprecated
SectionInfo
( SourceLineInfo const& _lineInfo,
std::string const& _name,
std::string const& ) : SectionInfo( _lineInfo, _name ) {}
std::string name;
std::string description; // !Deprecated: this will always be empty
SourceLineInfo lineInfo;
};
struct SectionEndInfo {
SectionInfo sectionInfo;
Counts prevAssertions;
double durationInSeconds;
};
} // end namespace Catch
// end catch_section_info.h
// start catch_timer.h
#include <cstdint>
namespace Catch {
auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
auto getEstimatedClockResolution() -> uint64_t;
class Timer {
uint64_t m_nanoseconds = 0;
public:
void start();
auto getElapsedNanoseconds() const -> uint64_t;
auto getElapsedMicroseconds() const -> uint64_t;
auto getElapsedMilliseconds() const -> unsigned int;
auto getElapsedSeconds() const -> double;
};
} // namespace Catch
// end catch_timer.h
#include <string>
namespace Catch {
class Section : NonCopyable {
public:
Section( SectionInfo const& info );
~Section();
// This indicates whether the section should be executed or not
explicit operator bool() const;
private:
SectionInfo m_info;
std::string m_name;
Counts m_assertions;
bool m_sectionIncluded;
Timer m_timer;
};
} // end namespace Catch
#define INTERNAL_CATCH_SECTION( ... ) \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
#define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
// end catch_section.h
// start catch_interfaces_exception.h
// start catch_interfaces_registry_hub.h
#include <string>
#include <memory>
namespace Catch {
class TestCase;
struct ITestCaseRegistry;
struct IExceptionTranslatorRegistry;
struct IExceptionTranslator;
struct IReporterRegistry;
struct IReporterFactory;
struct ITagAliasRegistry;
struct IMutableEnumValuesRegistry;
class StartupExceptionRegistry;
using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
struct IRegistryHub {
virtual ~IRegistryHub();
virtual IReporterRegistry const& getReporterRegistry() const = 0;
virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
};
struct IMutableRegistryHub {
virtual ~IMutableRegistryHub();
virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
virtual void registerTest( TestCase const& testInfo ) = 0;
virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
virtual void registerStartupException() noexcept = 0;
virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
};
IRegistryHub const& getRegistryHub();
IMutableRegistryHub& getMutableRegistryHub();
void cleanUp();
std::string translateActiveException();
}
// end catch_interfaces_registry_hub.h
#if defined(CATCH_CONFIG_DISABLE)
#define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
static std::string translatorName( signature )
#endif
#include <exception>
#include <string>
#include <vector>
namespace Catch {
using exceptionTranslateFunction = std::string(*)();
struct IExceptionTranslator;
using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
struct IExceptionTranslator {
virtual ~IExceptionTranslator();
virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
};
struct IExceptionTranslatorRegistry {
virtual ~IExceptionTranslatorRegistry();
virtual std::string translateActiveException() const = 0;
};
class ExceptionTranslatorRegistrar {
template<typename T>
class ExceptionTranslator : public IExceptionTranslator {
public:
ExceptionTranslator( std::string(*translateFunction)( T& ) )
: m_translateFunction( translateFunction )
{}
std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
return "";
#else
try {
if( it == itEnd )
std::rethrow_exception(std::current_exception());
else
return (*it)->translate( it+1, itEnd );
}
catch( T& ex ) {
return m_translateFunction( ex );
}
#endif
}
protected:
std::string(*m_translateFunction)( T& );
};
public:
template<typename T>
ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
getMutableRegistryHub().registerTranslator
( new ExceptionTranslator<T>( translateFunction ) );
}
};
}
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
static std::string translatorName( signature ); \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
static std::string translatorName( signature )
#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
// end catch_interfaces_exception.h
// start catch_approx.h
#include <type_traits>
namespace Catch {
namespace Detail {
class Approx {
private:
bool equalityComparisonImpl(double other) const;
// Validates the new margin (margin >= 0)
// out-of-line to avoid including stdexcept in the header
void setMargin(double margin);
// Validates the new epsilon (0 < epsilon < 1)
// out-of-line to avoid including stdexcept in the header
void setEpsilon(double epsilon);
public:
explicit Approx ( double value );
static Approx custom();
Approx operator-() const;
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx operator()( T const& value ) {
Approx approx( static_cast<double>(value) );
approx.m_epsilon = m_epsilon;
approx.m_margin = m_margin;
approx.m_scale = m_scale;
return approx;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
explicit Approx( T const& value ): Approx(static_cast<double>(value))
{}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator == ( const T& lhs, Approx const& rhs ) {
auto lhs_v = static_cast<double>(lhs);
return rhs.equalityComparisonImpl(lhs_v);
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator == ( Approx const& lhs, const T& rhs ) {
return operator==( rhs, lhs );
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator != ( T const& lhs, Approx const& rhs ) {
return !operator==( lhs, rhs );
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator != ( Approx const& lhs, T const& rhs ) {
return !operator==( rhs, lhs );
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator <= ( T const& lhs, Approx const& rhs ) {
return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator <= ( Approx const& lhs, T const& rhs ) {
return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator >= ( T const& lhs, Approx const& rhs ) {
return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator >= ( Approx const& lhs, T const& rhs ) {
return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx& epsilon( T const& newEpsilon ) {
double epsilonAsDouble = static_cast<double>(newEpsilon);
setEpsilon(epsilonAsDouble);
return *this;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx& margin( T const& newMargin ) {
double marginAsDouble = static_cast<double>(newMargin);
setMargin(marginAsDouble);
return *this;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx& scale( T const& newScale ) {
m_scale = static_cast<double>(newScale);
return *this;
}
std::string toString() const;
private:
double m_epsilon;
double m_margin;
double m_scale;
double m_value;
};
} // end namespace Detail
namespace literals {
Detail::Approx operator "" _a(long double val);
Detail::Approx operator "" _a(unsigned long long val);
} // end namespace literals
template<>
struct StringMaker<Catch::Detail::Approx> {
static std::string convert(Catch::Detail::Approx const& value);
};
} // end namespace Catch
// end catch_approx.h
// start catch_string_manip.h
#include <string>
#include <iosfwd>
#include <vector>
namespace Catch {
bool startsWith( std::string const& s, std::string const& prefix );
bool startsWith( std::string const& s, char prefix );
bool endsWith( std::string const& s, std::string const& suffix );
bool endsWith( std::string const& s, char suffix );
bool contains( std::string const& s, std::string const& infix );
void toLowerInPlace( std::string& s );
std::string toLower( std::string const& s );
//! Returns a new string without whitespace at the start/end
std::string trim( std::string const& str );
//! Returns a substring of the original ref without whitespace. Beware lifetimes!
StringRef trim(StringRef ref);
// !!! Be aware, returns refs into original string - make sure original string outlives them
std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
struct pluralise {
pluralise( std::size_t count, std::string const& label );
friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
std::size_t m_count;
std::string m_label;
};
}
// end catch_string_manip.h
#ifndef CATCH_CONFIG_DISABLE_MATCHERS
// start catch_capture_matchers.h
// start catch_matchers.h
#include <string>
#include <vector>
namespace Catch {
namespace Matchers {
namespace Impl {
template<typename ArgT> struct MatchAllOf;
template<typename ArgT> struct MatchAnyOf;
template<typename ArgT> struct MatchNotOf;
class MatcherUntypedBase {
public:
MatcherUntypedBase() = default;
MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
std::string toString() const;
protected:
virtual ~MatcherUntypedBase();
virtual std::string describe() const = 0;
mutable std::string m_cachedToString;
};
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wnon-virtual-dtor"
#endif
template<typename ObjectT>
struct MatcherMethod {
virtual bool match( ObjectT const& arg ) const = 0;
};
#if defined(__OBJC__)
// Hack to fix Catch GH issue #1661. Could use id for generic Object support.
// use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
template<>
struct MatcherMethod<NSString*> {
virtual bool match( NSString* arg ) const = 0;
};
#endif
#ifdef __clang__
# pragma clang diagnostic pop
#endif
template<typename T>
struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
MatchAllOf<T> operator && ( MatcherBase const& other ) const;
MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
MatchNotOf<T> operator ! () const;
};
template<typename ArgT>
struct MatchAllOf : MatcherBase<ArgT> {
bool match( ArgT const& arg ) const override {
for( auto matcher : m_matchers ) {
if (!matcher->match(arg))
return false;
}
return true;
}
std::string describe() const override {
std::string description;
description.reserve( 4 + m_matchers.size()*32 );
description += "( ";
bool first = true;
for( auto matcher : m_matchers ) {
if( first )
first = false;
else
description += " and ";
description += matcher->toString();
}
description += " )";
return description;
}
MatchAllOf<ArgT> operator && ( MatcherBase<ArgT> const& other ) {
auto copy(*this);
copy.m_matchers.push_back( &other );
return copy;
}
std::vector<MatcherBase<ArgT> const*> m_matchers;
};
template<typename ArgT>
struct MatchAnyOf : MatcherBase<ArgT> {
bool match( ArgT const& arg ) const override {
for( auto matcher : m_matchers ) {
if (matcher->match(arg))
return true;
}
return false;
}
std::string describe() const override {
std::string description;
description.reserve( 4 + m_matchers.size()*32 );
description += "( ";
bool first = true;
for( auto matcher : m_matchers ) {
if( first )
first = false;
else
description += " or ";
description += matcher->toString();
}
description += " )";
return description;
}
MatchAnyOf<ArgT> operator || ( MatcherBase<ArgT> const& other ) {
auto copy(*this);
copy.m_matchers.push_back( &other );
return copy;
}
std::vector<MatcherBase<ArgT> const*> m_matchers;
};
template<typename ArgT>
struct MatchNotOf : MatcherBase<ArgT> {
MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
bool match( ArgT const& arg ) const override {
return !m_underlyingMatcher.match( arg );
}
std::string describe() const override {
return "not " + m_underlyingMatcher.toString();
}
MatcherBase<ArgT> const& m_underlyingMatcher;
};
template<typename T>
MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
return MatchAllOf<T>() && *this && other;
}
template<typename T>
MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
return MatchAnyOf<T>() || *this || other;
}
template<typename T>
MatchNotOf<T> MatcherBase<T>::operator ! () const {
return MatchNotOf<T>( *this );
}
} // namespace Impl
} // namespace Matchers
using namespace Matchers;
using Matchers::Impl::MatcherBase;
} // namespace Catch
// end catch_matchers.h
// start catch_matchers_exception.hpp
namespace Catch {
namespace Matchers {
namespace Exception {
class ExceptionMessageMatcher : public MatcherBase<std::exception> {
std::string m_message;
public:
ExceptionMessageMatcher(std::string const& message):
m_message(message)
{}
bool match(std::exception const& ex) const override;
std::string describe() const override;
};
} // namespace Exception
Exception::ExceptionMessageMatcher Message(std::string const& message);
} // namespace Matchers
} // namespace Catch
// end catch_matchers_exception.hpp
// start catch_matchers_floating.h
namespace Catch {
namespace Matchers {
namespace Floating {
enum class FloatingPointKind : uint8_t;
struct WithinAbsMatcher : MatcherBase<double> {
WithinAbsMatcher(double target, double margin);
bool match(double const& matchee) const override;
std::string describe() const override;
private:
double m_target;
double m_margin;
};
struct WithinUlpsMatcher : MatcherBase<double> {
WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
bool match(double const& matchee) const override;
std::string describe() const override;
private:
double m_target;
uint64_t m_ulps;
FloatingPointKind m_type;
};
// Given IEEE-754 format for floats and doubles, we can assume
// that float -> double promotion is lossless. Given this, we can
// assume that if we do the standard relative comparison of
// |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
// the same result if we do this for floats, as if we do this for
// doubles that were promoted from floats.
struct WithinRelMatcher : MatcherBase<double> {
WithinRelMatcher(double target, double epsilon);
bool match(double const& matchee) const override;
std::string describe() const override;
private:
double m_target;
double m_epsilon;
};
} // namespace Floating
// The following functions create the actual matcher objects.
// This allows the types to be inferred
Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
Floating::WithinAbsMatcher WithinAbs(double target, double margin);
Floating::WithinRelMatcher WithinRel(double target, double eps);
// defaults epsilon to 100*numeric_limits<double>::epsilon()
Floating::WithinRelMatcher WithinRel(double target);
Floating::WithinRelMatcher WithinRel(float target, float eps);
// defaults epsilon to 100*numeric_limits<float>::epsilon()
Floating::WithinRelMatcher WithinRel(float target);
} // namespace Matchers
} // namespace Catch
// end catch_matchers_floating.h
// start catch_matchers_generic.hpp
#include <functional>
#include <string>
namespace Catch {
namespace Matchers {
namespace Generic {
namespace Detail {
std::string finalizeDescription(const std::string& desc);
}
template <typename T>
class PredicateMatcher : public MatcherBase<T> {
std::function<bool(T const&)> m_predicate;
std::string m_description;
public:
PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
:m_predicate(std::move(elem)),
m_description(Detail::finalizeDescription(descr))
{}
bool match( T const& item ) const override {
return m_predicate(item);
}
std::string describe() const override {
return m_description;
}
};
} // namespace Generic
// The following functions create the actual matcher objects.
// The user has to explicitly specify type to the function, because
// inferring std::function<bool(T const&)> is hard (but possible) and
// requires a lot of TMP.
template<typename T>
Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
return Generic::PredicateMatcher<T>(predicate, description);
}
} // namespace Matchers
} // namespace Catch
// end catch_matchers_generic.hpp
// start catch_matchers_string.h
#include <string>
namespace Catch {
namespace Matchers {
namespace StdString {
struct CasedString
{
CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
std::string adjustString( std::string const& str ) const;
std::string caseSensitivitySuffix() const;
CaseSensitive::Choice m_caseSensitivity;
std::string m_str;
};
struct StringMatcherBase : MatcherBase<std::string> {
StringMatcherBase( std::string const& operation, CasedString const& comparator );
std::string describe() const override;
CasedString m_comparator;
std::string m_operation;
};
struct EqualsMatcher : StringMatcherBase {
EqualsMatcher( CasedString const& comparator );
bool match( std::string const& source ) const override;
};
struct ContainsMatcher : StringMatcherBase {
ContainsMatcher( CasedString const& comparator );
bool match( std::string const& source ) const override;
};
struct StartsWithMatcher : StringMatcherBase {
StartsWithMatcher( CasedString const& comparator );
bool match( std::string const& source ) const override;
};
struct EndsWithMatcher : StringMatcherBase {
EndsWithMatcher( CasedString const& comparator );
bool match( std::string const& source ) const override;
};
struct RegexMatcher : MatcherBase<std::string> {
RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
bool match( std::string const& matchee ) const override;
std::string describe() const override;
private:
std::string m_regex;
CaseSensitive::Choice m_caseSensitivity;
};
} // namespace StdString
// The following functions create the actual matcher objects.
// This allows the types to be inferred
StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
} // namespace Matchers
} // namespace Catch
// end catch_matchers_string.h
// start catch_matchers_vector.h
#include <algorithm>
namespace Catch {
namespace Matchers {
namespace Vector {
template<typename T, typename Alloc>
struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
bool match(std::vector<T, Alloc> const &v) const override {
for (auto const& el : v) {
if (el == m_comparator) {
return true;
}
}
return false;
}
std::string describe() const override {
return "Contains: " + ::Catch::Detail::stringify( m_comparator );
}
T const& m_comparator;
};
template<typename T, typename AllocComp, typename AllocMatch>
struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
ContainsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
bool match(std::vector<T, AllocMatch> const &v) const override {
// !TBD: see note in EqualsMatcher
if (m_comparator.size() > v.size())
return false;
for (auto const& comparator : m_comparator) {
auto present = false;
for (const auto& el : v) {
if (el == comparator) {
present = true;
break;
}
}
if (!present) {
return false;
}
}
return true;
}
std::string describe() const override {
return "Contains: " + ::Catch::Detail::stringify( m_comparator );
}
std::vector<T, AllocComp> const& m_comparator;
};
template<typename T, typename AllocComp, typename AllocMatch>
struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
EqualsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
bool match(std::vector<T, AllocMatch> const &v) const override {
// !TBD: This currently works if all elements can be compared using !=
// - a more general approach would be via a compare template that defaults
// to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc
// - then just call that directly
if (m_comparator.size() != v.size())
return false;
for (std::size_t i = 0; i < v.size(); ++i)
if (m_comparator[i] != v[i])
return false;
return true;
}
std::string describe() const override {
return "Equals: " + ::Catch::Detail::stringify( m_comparator );
}
std::vector<T, AllocComp> const& m_comparator;
};
template<typename T, typename AllocComp, typename AllocMatch>
struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
ApproxMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator( comparator ) {}
bool match(std::vector<T, AllocMatch> const &v) const override {
if (m_comparator.size() != v.size())
return false;
for (std::size_t i = 0; i < v.size(); ++i)
if (m_comparator[i] != approx(v[i]))
return false;
return true;
}
std::string describe() const override {
return "is approx: " + ::Catch::Detail::stringify( m_comparator );
}
template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
ApproxMatcher& epsilon( T const& newEpsilon ) {
approx.epsilon(newEpsilon);
return *this;
}
template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
ApproxMatcher& margin( T const& newMargin ) {
approx.margin(newMargin);
return *this;
}
template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
ApproxMatcher& scale( T const& newScale ) {
approx.scale(newScale);
return *this;
}
std::vector<T, AllocComp> const& m_comparator;
mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
};
template<typename T, typename AllocComp, typename AllocMatch>
struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) : m_target(target) {}
bool match(std::vector<T, AllocMatch> const& vec) const override {
if (m_target.size() != vec.size()) {
return false;
}
return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
}
std::string describe() const override {
return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
}
private:
std::vector<T, AllocComp> const& m_target;
};
} // namespace Vector
// The following functions create the actual matcher objects.
// This allows the types to be inferred
template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
Vector::ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) {
return Vector::ContainsMatcher<T, AllocComp, AllocMatch>( comparator );
}
template<typename T, typename Alloc = std::allocator<T>>
Vector::ContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) {
return Vector::ContainsElementMatcher<T, Alloc>( comparator );
}
template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) {
return Vector::EqualsMatcher<T, AllocComp, AllocMatch>( comparator );
}
template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
Vector::ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) {
return Vector::ApproxMatcher<T, AllocComp, AllocMatch>( comparator );
}
template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) {
return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( target );
}
} // namespace Matchers
} // namespace Catch
// end catch_matchers_vector.h
namespace Catch {
template<typename ArgT, typename MatcherT>
class MatchExpr : public ITransientExpression {
ArgT const& m_arg;
MatcherT m_matcher;
StringRef m_matcherString;
public:
MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
: ITransientExpression{ true, matcher.match( arg ) },
m_arg( arg ),
m_matcher( matcher ),
m_matcherString( matcherString )
{}
void streamReconstructedExpression( std::ostream &os ) const override {
auto matcherAsString = m_matcher.toString();
os << Catch::Detail::stringify( m_arg ) << ' ';
if( matcherAsString == Detail::unprintableString )
os << m_matcherString;
else
os << matcherAsString;
}
};
using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
template<typename ArgT, typename MatcherT>
auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
}
} // namespace Catch
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
do { \
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
INTERNAL_CATCH_TRY { \
catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
} INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
} while( false )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
do { \
Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
if( catchAssertionHandler.allowThrows() ) \
try { \
static_cast<void>(__VA_ARGS__ ); \
catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
} \
catch( exceptionType const& ex ) { \
catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
} \
catch( ... ) { \
catchAssertionHandler.handleUnexpectedInflightException(); \
} \
else \
catchAssertionHandler.handleThrowingCallSkipped(); \
INTERNAL_CATCH_REACT( catchAssertionHandler ) \
} while( false )
// end catch_capture_matchers.h
#endif
// start catch_generators.hpp
// start catch_interfaces_generatortracker.h
#include <memory>
namespace Catch {
namespace Generators {
class GeneratorUntypedBase {
public:
GeneratorUntypedBase() = default;
virtual ~GeneratorUntypedBase();
// Attempts to move the generator to the next element
//
// Returns true iff the move succeeded (and a valid element
// can be retrieved).
virtual bool next() = 0;
};
using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
} // namespace Generators
struct IGeneratorTracker {
virtual ~IGeneratorTracker();
virtual auto hasGenerator() const -> bool = 0;
virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
};
} // namespace Catch
// end catch_interfaces_generatortracker.h
// start catch_enforce.h
#include <exception>
namespace Catch {
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
template <typename Ex>
[[noreturn]]
void throw_exception(Ex const& e) {
throw e;
}
#else // ^^ Exceptions are enabled // Exceptions are disabled vv
[[noreturn]]
void throw_exception(std::exception const& e);
#endif
[[noreturn]]
void throw_logic_error(std::string const& msg);
[[noreturn]]
void throw_domain_error(std::string const& msg);
[[noreturn]]
void throw_runtime_error(std::string const& msg);
} // namespace Catch;
#define CATCH_MAKE_MSG(...) \
(Catch::ReusableStringStream() << __VA_ARGS__).str()
#define CATCH_INTERNAL_ERROR(...) \
Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
#define CATCH_ERROR(...) \
Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
#define CATCH_RUNTIME_ERROR(...) \
Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
#define CATCH_ENFORCE( condition, ... ) \
do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
// end catch_enforce.h
#include <memory>
#include <vector>
#include <cassert>
#include <utility>
#include <exception>
namespace Catch {
class GeneratorException : public std::exception {
const char* const m_msg = "";
public:
GeneratorException(const char* msg):
m_msg(msg)
{}
const char* what() const noexcept override final;
};
namespace Generators {
// !TBD move this into its own location?
namespace pf{
template<typename T, typename... Args>
std::unique_ptr<T> make_unique( Args&&... args ) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
template<typename T>
struct IGenerator : GeneratorUntypedBase {
virtual ~IGenerator() = default;
// Returns the current element of the generator
//
// \Precondition The generator is either freshly constructed,
// or the last call to `next()` returned true
virtual T const& get() const = 0;
using type = T;
};
template<typename T>
class SingleValueGenerator final : public IGenerator<T> {
T m_value;
public:
SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
T const& get() const override {
return m_value;
}
bool next() override {
return false;
}
};
template<typename T>
class FixedValuesGenerator final : public IGenerator<T> {
static_assert(!std::is_same<T, bool>::value,
"FixedValuesGenerator does not support bools because of std::vector<bool>"
"specialization, use SingleValue Generator instead.");
std::vector<T> m_values;
size_t m_idx = 0;
public:
FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
T const& get() const override {
return m_values[m_idx];
}
bool next() override {
++m_idx;
return m_idx < m_values.size();
}
};
template <typename T>
class GeneratorWrapper final {
std::unique_ptr<IGenerator<T>> m_generator;
public:
GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
m_generator(std::move(generator))
{}
T const& get() const {
return m_generator->get();
}
bool next() {
return m_generator->next();
}
};
template <typename T>
GeneratorWrapper<T> value(T&& value) {
return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
}
template <typename T>
GeneratorWrapper<T> values(std::initializer_list<T> values) {
return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
}
template<typename T>
class Generators : public IGenerator<T> {
std::vector<GeneratorWrapper<T>> m_generators;
size_t m_current = 0;
void populate(GeneratorWrapper<T>&& generator) {
m_generators.emplace_back(std::move(generator));
}
void populate(T&& val) {
m_generators.emplace_back(value(std::forward<T>(val)));
}
template<typename U>
void populate(U&& val) {
populate(T(std::forward<U>(val)));
}
template<typename U, typename... Gs>
void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
populate(std::forward<U>(valueOrGenerator));
populate(std::forward<Gs>(moreGenerators)...);
}
public:
template <typename... Gs>
Generators(Gs &&... moreGenerators) {
m_generators.reserve(sizeof...(Gs));
populate(std::forward<Gs>(moreGenerators)...);
}
T const& get() const override {
return m_generators[m_current].get();
}
bool next() override {
if (m_current >= m_generators.size()) {
return false;
}
const bool current_status = m_generators[m_current].next();
if (!current_status) {
++m_current;
}
return m_current < m_generators.size();
}
};
template<typename... Ts>
GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
return values<std::tuple<Ts...>>( tuples );
}
// Tag type to signal that a generator sequence should convert arguments to a specific type
template <typename T>
struct as {};
template<typename T, typename... Gs>
auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> {
return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
}
template<typename T>
auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
return Generators<T>(std::move(generator));
}
template<typename T, typename... Gs>
auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> {
return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
}
template<typename T, typename U, typename... Gs>
auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
}
auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
template<typename L>
// Note: The type after -> is weird, because VS2015 cannot parse
// the expression used in the typedef inside, when it is in
// return type. Yeah.
auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
using UnderlyingType = typename decltype(generatorExpression())::type;
IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
if (!tracker.hasGenerator()) {
tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
}
auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
return generator.get();
}
} // namespace Generators
} // namespace Catch
#define GENERATE( ... ) \
Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
CATCH_INTERNAL_LINEINFO, \
[ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
#define GENERATE_COPY( ... ) \
Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
CATCH_INTERNAL_LINEINFO, \
[=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
#define GENERATE_REF( ... ) \
Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
CATCH_INTERNAL_LINEINFO, \
[&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
// end catch_generators.hpp
// start catch_generators_generic.hpp
namespace Catch {
namespace Generators {
template <typename T>
class TakeGenerator : public IGenerator<T> {
GeneratorWrapper<T> m_generator;
size_t m_returned = 0;
size_t m_target;
public:
TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
m_generator(std::move(generator)),
m_target(target)
{
assert(target != 0 && "Empty generators are not allowed");
}
T const& get() const override {
return m_generator.get();
}
bool next() override {
++m_returned;
if (m_returned >= m_target) {
return false;
}
const auto success = m_generator.next();
// If the underlying generator does not contain enough values
// then we cut short as well
if (!success) {
m_returned = m_target;
}
return success;
}
};
template <typename T>
GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
}
template <typename T, typename Predicate>
class FilterGenerator : public IGenerator<T> {
GeneratorWrapper<T> m_generator;
Predicate m_predicate;
public:
template <typename P = Predicate>
FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
m_generator(std::move(generator)),
m_predicate(std::forward<P>(pred))
{
if (!m_predicate(m_generator.get())) {
// It might happen that there are no values that pass the
// filter. In that case we throw an exception.
auto has_initial_value = next();
if (!has_initial_value) {
Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
}
}
}
T const& get() const override {
return m_generator.get();
}
bool next() override {
bool success = m_generator.next();
if (!success) {
return false;
}
while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
return success;
}
};
template <typename T, typename Predicate>
GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
}
template <typename T>
class RepeatGenerator : public IGenerator<T> {
static_assert(!std::is_same<T, bool>::value,
"RepeatGenerator currently does not support bools"
"because of std::vector<bool> specialization");
GeneratorWrapper<T> m_generator;
mutable std::vector<T> m_returned;
size_t m_target_repeats;
size_t m_current_repeat = 0;
size_t m_repeat_index = 0;
public:
RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
m_generator(std::move(generator)),
m_target_repeats(repeats)
{
assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
}
T const& get() const override {
if (m_current_repeat == 0) {
m_returned.push_back(m_generator.get());
return m_returned.back();
}
return m_returned[m_repeat_index];
}
bool next() override {
// There are 2 basic cases:
// 1) We are still reading the generator
// 2) We are reading our own cache
// In the first case, we need to poke the underlying generator.
// If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
if (m_current_repeat == 0) {
const auto success = m_generator.next();
if (!success) {
++m_current_repeat;
}
return m_current_repeat < m_target_repeats;
}
// In the second case, we need to move indices forward and check that we haven't run up against the end
++m_repeat_index;
if (m_repeat_index == m_returned.size()) {
m_repeat_index = 0;
++m_current_repeat;
}
return m_current_repeat < m_target_repeats;
}
};
template <typename T>
GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
}
template <typename T, typename U, typename Func>
class MapGenerator : public IGenerator<T> {
// TBD: provide static assert for mapping function, for friendly error message
GeneratorWrapper<U> m_generator;
Func m_function;
// To avoid returning dangling reference, we have to save the values
T m_cache;
public:
template <typename F2 = Func>
MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
m_generator(std::move(generator)),
m_function(std::forward<F2>(function)),
m_cache(m_function(m_generator.get()))
{}
T const& get() const override {
return m_cache;
}
bool next() override {
const auto success = m_generator.next();
if (success) {
m_cache = m_function(m_generator.get());
}
return success;
}
};
template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
return GeneratorWrapper<T>(
pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
);
}
template <typename T, typename U, typename Func>
GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
return GeneratorWrapper<T>(
pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
);
}
template <typename T>
class ChunkGenerator final : public IGenerator<std::vector<T>> {
std::vector<T> m_chunk;
size_t m_chunk_size;
GeneratorWrapper<T> m_generator;
bool m_used_up = false;
public:
ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
m_chunk_size(size), m_generator(std::move(generator))
{
m_chunk.reserve(m_chunk_size);
if (m_chunk_size != 0) {
m_chunk.push_back(m_generator.get());
for (size_t i = 1; i < m_chunk_size; ++i) {
if (!m_generator.next()) {
Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
}
m_chunk.push_back(m_generator.get());
}
}
}
std::vector<T> const& get() const override {
return m_chunk;
}
bool next() override {
m_chunk.clear();
for (size_t idx = 0; idx < m_chunk_size; ++idx) {
if (!m_generator.next()) {
return false;
}
m_chunk.push_back(m_generator.get());
}
return true;
}
};
template <typename T>
GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
return GeneratorWrapper<std::vector<T>>(
pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
);
}
} // namespace Generators
} // namespace Catch
// end catch_generators_generic.hpp
// start catch_generators_specific.hpp
// start catch_context.h
#include <memory>
namespace Catch {
struct IResultCapture;
struct IRunner;
struct IConfig;
struct IMutableContext;
using IConfigPtr = std::shared_ptr<IConfig const>;
struct IContext
{
virtual ~IContext();
virtual IResultCapture* getResultCapture() = 0;
virtual IRunner* getRunner() = 0;
virtual IConfigPtr const& getConfig() const = 0;
};
struct IMutableContext : IContext
{
virtual ~IMutableContext();
virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
virtual void setRunner( IRunner* runner ) = 0;
virtual void setConfig( IConfigPtr const& config ) = 0;
private:
static IMutableContext *currentContext;
friend IMutableContext& getCurrentMutableContext();
friend void cleanUpContext();
static void createContext();
};
inline IMutableContext& getCurrentMutableContext()
{
if( !IMutableContext::currentContext )
IMutableContext::createContext();
// NOLINTNEXTLINE(clang-analyzer.uninitialized.UndefReturn)
return *IMutableContext::currentContext;
}
inline IContext& getCurrentContext()
{
return getCurrentMutableContext();
}
void cleanUpContext();
class SimplePcg32;
SimplePcg32& rng();
}
// end catch_context.h
// start catch_interfaces_config.h
// start catch_option.hpp
namespace Catch {
// An optional type
template<typename T>
class Option {
public:
Option() : nullableValue( nullptr ) {}
Option( T const& _value )
: nullableValue( new( storage ) T( _value ) )
{}
Option( Option const& _other )
: nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
{}
~Option() {
reset();
}
Option& operator= ( Option const& _other ) {
if( &_other != this ) {
reset();
if( _other )
nullableValue = new( storage ) T( *_other );
}
return *this;
}
Option& operator = ( T const& _value ) {
reset();
nullableValue = new( storage ) T( _value );
return *this;
}
void reset() {
if( nullableValue )
nullableValue->~T();
nullableValue = nullptr;
}
T& operator*() { return *nullableValue; }
T const& operator*() const { return *nullableValue; }
T* operator->() { return nullableValue; }
const T* operator->() const { return nullableValue; }
T valueOr( T const& defaultValue ) const {
return nullableValue ? *nullableValue : defaultValue;
}
bool some() const { return nullableValue != nullptr; }
bool none() const { return nullableValue == nullptr; }
bool operator !() const { return nullableValue == nullptr; }
explicit operator bool() const {
return some();
}
private:
T *nullableValue;
alignas(alignof(T)) char storage[sizeof(T)];
};
} // end namespace Catch
// end catch_option.hpp
#include <chrono>
#include <iosfwd>
#include <string>
#include <vector>
#include <memory>
namespace Catch {
enum class Verbosity {
Quiet = 0,
Normal,
High
};
struct WarnAbout { enum What {
Nothing = 0x00,
NoAssertions = 0x01,
NoTests = 0x02
}; };
struct ShowDurations { enum OrNot {
DefaultForReporter,
Always,
Never
}; };
struct RunTests { enum InWhatOrder {
InDeclarationOrder,
InLexicographicalOrder,
InRandomOrder
}; };
struct UseColour { enum YesOrNo {
Auto,
Yes,
No
}; };
struct WaitForKeypress { enum When {
Never,
BeforeStart = 1,
BeforeExit = 2,
BeforeStartAndExit = BeforeStart | BeforeExit
}; };
class TestSpec;
struct IConfig : NonCopyable {
virtual ~IConfig();
virtual bool allowThrows() const = 0;
virtual std::ostream& stream() const = 0;
virtual std::string name() const = 0;
virtual bool includeSuccessfulResults() const = 0;
virtual bool shouldDebugBreak() const = 0;
virtual bool warnAboutMissingAssertions() const = 0;
virtual bool warnAboutNoTests() const = 0;
virtual int abortAfter() const = 0;
virtual bool showInvisibles() const = 0;
virtual ShowDurations::OrNot showDurations() const = 0;
virtual double minDuration() const = 0;
virtual TestSpec const& testSpec() const = 0;
virtual bool hasTestFilters() const = 0;
virtual std::vector<std::string> const& getTestsOrTags() const = 0;
virtual RunTests::InWhatOrder runOrder() const = 0;
virtual unsigned int rngSeed() const = 0;
virtual UseColour::YesOrNo useColour() const = 0;
virtual std::vector<std::string> const& getSectionsToRun() const = 0;
virtual Verbosity verbosity() const = 0;
virtual bool benchmarkNoAnalysis() const = 0;
virtual int benchmarkSamples() const = 0;
virtual double benchmarkConfidenceInterval() const = 0;
virtual unsigned int benchmarkResamples() const = 0;
virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
};
using IConfigPtr = std::shared_ptr<IConfig const>;
}
// end catch_interfaces_config.h
// start catch_random_number_generator.h
#include <cstdint>
namespace Catch {
// This is a simple implementation of C++11 Uniform Random Number
// Generator. It does not provide all operators, because Catch2
// does not use it, but it should behave as expected inside stdlib's
// distributions.
// The implementation is based on the PCG family (http://pcg-random.org)
class SimplePcg32 {
using state_type = std::uint64_t;
public:
using result_type = std::uint32_t;
static constexpr result_type (min)() {
return 0;
}
static constexpr result_type (max)() {
return static_cast<result_type>(-1);
}
// Provide some default initial state for the default constructor
SimplePcg32():SimplePcg32(0xed743cc4U) {}
explicit SimplePcg32(result_type seed_);
void seed(result_type seed_);
void discard(uint64_t skip);
result_type operator()();
private:
friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
// In theory we also need operator<< and operator>>
// In practice we do not use them, so we will skip them for now
std::uint64_t m_state;
// This part of the state determines which "stream" of the numbers
// is chosen -- we take it as a constant for Catch2, so we only
// need to deal with seeding the main state.
// Picked by reading 8 bytes from `/dev/random` :-)
static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
};
} // end namespace Catch
// end catch_random_number_generator.h
#include <random>
namespace Catch {
namespace Generators {
template <typename Float>
class RandomFloatingGenerator final : public IGenerator<Float> {
Catch::SimplePcg32& m_rng;
std::uniform_real_distribution<Float> m_dist;
Float m_current_number;
public:
RandomFloatingGenerator(Float a, Float b):
m_rng(rng()),
m_dist(a, b) {
static_cast<void>(next());
}
Float const& get() const override {
return m_current_number;
}
bool next() override {
m_current_number = m_dist(m_rng);
return true;
}
};
template <typename Integer>
class RandomIntegerGenerator final : public IGenerator<Integer> {
Catch::SimplePcg32& m_rng;
std::uniform_int_distribution<Integer> m_dist;
Integer m_current_number;
public:
RandomIntegerGenerator(Integer a, Integer b):
m_rng(rng()),
m_dist(a, b) {
static_cast<void>(next());
}
Integer const& get() const override {
return m_current_number;
}
bool next() override {
m_current_number = m_dist(m_rng);
return true;
}
};
// TODO: Ideally this would be also constrained against the various char types,
// but I don't expect users to run into that in practice.
template <typename T>
typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
GeneratorWrapper<T>>::type
random(T a, T b) {
return GeneratorWrapper<T>(
pf::make_unique<RandomIntegerGenerator<T>>(a, b)
);
}
template <typename T>
typename std::enable_if<std::is_floating_point<T>::value,
GeneratorWrapper<T>>::type
random(T a, T b) {
return GeneratorWrapper<T>(
pf::make_unique<RandomFloatingGenerator<T>>(a, b)
);
}
template <typename T>
class RangeGenerator final : public IGenerator<T> {
T m_current;
T m_end;
T m_step;
bool m_positive;
public:
RangeGenerator(T const& start, T const& end, T const& step):
m_current(start),
m_end(end),
m_step(step),
m_positive(m_step > T(0))
{
assert(m_current != m_end && "Range start and end cannot be equal");
assert(m_step != T(0) && "Step size cannot be zero");
assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
}
RangeGenerator(T const& start, T const& end):
RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
{}
T const& get() const override {
return m_current;
}
bool next() override {
m_current += m_step;
return (m_positive) ? (m_current < m_end) : (m_current > m_end);
}
};
template <typename T>
GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric");
return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
}
template <typename T>
GeneratorWrapper<T> range(T const& start, T const& end) {
static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
}
template <typename T>
class IteratorGenerator final : public IGenerator<T> {
static_assert(!std::is_same<T, bool>::value,
"IteratorGenerator currently does not support bools"
"because of std::vector<bool> specialization");
std::vector<T> m_elems;
size_t m_current = 0;
public:
template <typename InputIterator, typename InputSentinel>
IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
if (m_elems.empty()) {
Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values"));
}
}
T const& get() const override {
return m_elems[m_current];
}
bool next() override {
++m_current;
return m_current != m_elems.size();
}
};
template <typename InputIterator,
typename InputSentinel,
typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
}
template <typename Container,
typename ResultType = typename Container::value_type>
GeneratorWrapper<ResultType> from_range(Container const& cnt) {
return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
}
} // namespace Generators
} // namespace Catch
// end catch_generators_specific.hpp
// These files are included here so the single_include script doesn't put them
// in the conditionally compiled sections
// start catch_test_case_info.h
#include <string>
#include <vector>
#include <memory>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#endif
namespace Catch {
struct ITestInvoker;
struct TestCaseInfo {
enum SpecialProperties{
None = 0,
IsHidden = 1 << 1,
ShouldFail = 1 << 2,
MayFail = 1 << 3,
Throws = 1 << 4,
NonPortable = 1 << 5,
Benchmark = 1 << 6
};
TestCaseInfo( std::string const& _name,
std::string const& _className,
std::string const& _description,
std::vector<std::string> const& _tags,
SourceLineInfo const& _lineInfo );
friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
bool isHidden() const;
bool throws() const;
bool okToFail() const;
bool expectedToFail() const;
std::string tagsAsString() const;
std::string name;
std::string className;
std::string description;
std::vector<std::string> tags;
std::vector<std::string> lcaseTags;
SourceLineInfo lineInfo;
SpecialProperties properties;
};
class TestCase : public TestCaseInfo {
public:
TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
TestCase withName( std::string const& _newName ) const;
void invoke() const;
TestCaseInfo const& getTestCaseInfo() const;
bool operator == ( TestCase const& other ) const;
bool operator < ( TestCase const& other ) const;
private:
std::shared_ptr<ITestInvoker> test;
};
TestCase makeTestCase( ITestInvoker* testCase,
std::string const& className,
NameAndTags const& nameAndTags,
SourceLineInfo const& lineInfo );
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// end catch_test_case_info.h
// start catch_interfaces_runner.h
namespace Catch {
struct IRunner {
virtual ~IRunner();
virtual bool aborting() const = 0;
};
}
// end catch_interfaces_runner.h
#ifdef __OBJC__
// start catch_objc.hpp
#import <objc/runtime.h>
#include <string>
// NB. Any general catch headers included here must be included
// in catch.hpp first to make sure they are included by the single
// header for non obj-usage
///////////////////////////////////////////////////////////////////////////////
// This protocol is really only here for (self) documenting purposes, since
// all its methods are optional.
@protocol OcFixture
@optional
-(void) setUp;
-(void) tearDown;
@end
namespace Catch {
class OcMethod : public ITestInvoker {
public:
OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
virtual void invoke() const {
id obj = [[m_cls alloc] init];
performOptionalSelector( obj, @selector(setUp) );
performOptionalSelector( obj, m_sel );
performOptionalSelector( obj, @selector(tearDown) );
arcSafeRelease( obj );
}
private:
virtual ~OcMethod() {}
Class m_cls;
SEL m_sel;
};
namespace Detail{
inline std::string getAnnotation( Class cls,
std::string const& annotationName,
std::string const& testCaseName ) {
NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
SEL sel = NSSelectorFromString( selStr );
arcSafeRelease( selStr );
id value = performOptionalSelector( cls, sel );
if( value )
return [(NSString*)value UTF8String];
return "";
}
}
inline std::size_t registerTestMethods() {
std::size_t noTestMethods = 0;
int noClasses = objc_getClassList( nullptr, 0 );
Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
objc_getClassList( classes, noClasses );
for( int c = 0; c < noClasses; c++ ) {
Class cls = classes[c];
{
u_int count;
Method* methods = class_copyMethodList( cls, &count );
for( u_int m = 0; m < count ; m++ ) {
SEL selector = method_getName(methods[m]);
std::string methodName = sel_getName(selector);
if( startsWith( methodName, "Catch_TestCase_" ) ) {
std::string testCaseName = methodName.substr( 15 );
std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
const char* className = class_getName( cls );
getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
noTestMethods++;
}
}
free(methods);
}
}
return noTestMethods;
}
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
namespace Matchers {
namespace Impl {
namespace NSStringMatchers {
struct StringHolder : MatcherBase<NSString*>{
StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
StringHolder() {
arcSafeRelease( m_substr );
}
bool match( NSString* str ) const override {
return false;
}
NSString* CATCH_ARC_STRONG m_substr;
};
struct Equals : StringHolder {
Equals( NSString* substr ) : StringHolder( substr ){}
bool match( NSString* str ) const override {
return (str != nil || m_substr == nil ) &&
[str isEqualToString:m_substr];
}
std::string describe() const override {
return "equals string: " + Catch::Detail::stringify( m_substr );
}
};
struct Contains : StringHolder {
Contains( NSString* substr ) : StringHolder( substr ){}
bool match( NSString* str ) const override {
return (str != nil || m_substr == nil ) &&
[str rangeOfString:m_substr].location != NSNotFound;
}
std::string describe() const override {
return "contains string: " + Catch::Detail::stringify( m_substr );
}
};
struct StartsWith : StringHolder {
StartsWith( NSString* substr ) : StringHolder( substr ){}
bool match( NSString* str ) const override {
return (str != nil || m_substr == nil ) &&
[str rangeOfString:m_substr].location == 0;
}
std::string describe() const override {
return "starts with: " + Catch::Detail::stringify( m_substr );
}
};
struct EndsWith : StringHolder {
EndsWith( NSString* substr ) : StringHolder( substr ){}
bool match( NSString* str ) const override {
return (str != nil || m_substr == nil ) &&
[str rangeOfString:m_substr].location == [str length] - [m_substr length];
}
std::string describe() const override {
return "ends with: " + Catch::Detail::stringify( m_substr );
}
};
} // namespace NSStringMatchers
} // namespace Impl
inline Impl::NSStringMatchers::Equals
Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
inline Impl::NSStringMatchers::Contains
Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
inline Impl::NSStringMatchers::StartsWith
StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
inline Impl::NSStringMatchers::EndsWith
EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
} // namespace Matchers
using namespace Matchers;
#endif // CATCH_CONFIG_DISABLE_MATCHERS
} // namespace Catch
///////////////////////////////////////////////////////////////////////////////
#define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
#define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
{ \
return @ name; \
} \
+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
{ \
return @ desc; \
} \
-(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
#define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
// end catch_objc.hpp
#endif
// Benchmarking needs the externally-facing parts of reporters to work
#if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
// start catch_external_interfaces.h
// start catch_reporter_bases.hpp
// start catch_interfaces_reporter.h
// start catch_config.hpp
// start catch_test_spec_parser.h
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#endif
// start catch_test_spec.h
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#endif
// start catch_wildcard_pattern.h
namespace Catch
{
class WildcardPattern {
enum WildcardPosition {
NoWildcard = 0,
WildcardAtStart = 1,
WildcardAtEnd = 2,
WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
};
public:
WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
virtual ~WildcardPattern() = default;
virtual bool matches( std::string const& str ) const;
private:
std::string normaliseString( std::string const& str ) const;
CaseSensitive::Choice m_caseSensitivity;
WildcardPosition m_wildcard = NoWildcard;
std::string m_pattern;
};
}
// end catch_wildcard_pattern.h
#include <string>
#include <vector>
#include <memory>
namespace Catch {
struct IConfig;
class TestSpec {
class Pattern {
public:
explicit Pattern( std::string const& name );
virtual ~Pattern();
virtual bool matches( TestCaseInfo const& testCase ) const = 0;
std::string const& name() const;
private:
std::string const m_name;
};
using PatternPtr = std::shared_ptr<Pattern>;
class NamePattern : public Pattern {
public:
explicit NamePattern( std::string const& name, std::string const& filterString );
bool matches( TestCaseInfo const& testCase ) const override;
private:
WildcardPattern m_wildcardPattern;
};
class TagPattern : public Pattern {
public:
explicit TagPattern( std::string const& tag, std::string const& filterString );
bool matches( TestCaseInfo const& testCase ) const override;
private:
std::string m_tag;
};
class ExcludedPattern : public Pattern {
public:
explicit ExcludedPattern( PatternPtr const& underlyingPattern );
bool matches( TestCaseInfo const& testCase ) const override;
private:
PatternPtr m_underlyingPattern;
};
struct Filter {
std::vector<PatternPtr> m_patterns;
bool matches( TestCaseInfo const& testCase ) const;
std::string name() const;
};
public:
struct FilterMatch {
std::string name;
std::vector<TestCase const*> tests;
};
using Matches = std::vector<FilterMatch>;
using vectorStrings = std::vector<std::string>;
bool hasFilters() const;
bool matches( TestCaseInfo const& testCase ) const;
Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
const vectorStrings & getInvalidArgs() const;
private:
std::vector<Filter> m_filters;
std::vector<std::string> m_invalidArgs;
friend class TestSpecParser;
};
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// end catch_test_spec.h
// start catch_interfaces_tag_alias_registry.h
#include <string>
namespace Catch {
struct TagAlias;
struct ITagAliasRegistry {
virtual ~ITagAliasRegistry();
// Nullptr if not present
virtual TagAlias const* find( std::string const& alias ) const = 0;
virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
static ITagAliasRegistry const& get();
};
} // end namespace Catch
// end catch_interfaces_tag_alias_registry.h
namespace Catch {
class TestSpecParser {
enum Mode{ None, Name, QuotedName, Tag, EscapedName };
Mode m_mode = None;
Mode lastMode = None;
bool m_exclusion = false;
std::size_t m_pos = 0;
std::size_t m_realPatternPos = 0;
std::string m_arg;
std::string m_substring;
std::string m_patternName;
std::vector<std::size_t> m_escapeChars;
TestSpec::Filter m_currentFilter;
TestSpec m_testSpec;
ITagAliasRegistry const* m_tagAliases = nullptr;
public:
TestSpecParser( ITagAliasRegistry const& tagAliases );
TestSpecParser& parse( std::string const& arg );
TestSpec testSpec();
private:
bool visitChar( char c );
void startNewMode( Mode mode );
bool processNoneChar( char c );
void processNameChar( char c );
bool processOtherChar( char c );
void endMode();
void escape();
bool isControlChar( char c ) const;
void saveLastMode();
void revertBackToLastMode();
void addFilter();
bool separate();
// Handles common preprocessing of the pattern for name/tag patterns
std::string preprocessPattern();
// Adds the current pattern as a test name
void addNamePattern();
// Adds the current pattern as a tag
void addTagPattern();
inline void addCharToPattern(char c) {
m_substring += c;
m_patternName += c;
m_realPatternPos++;
}
};
TestSpec parseTestSpec( std::string const& arg );
} // namespace Catch
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// end catch_test_spec_parser.h
// Libstdc++ doesn't like incomplete classes for unique_ptr
#include <memory>
#include <vector>
#include <string>
#ifndef CATCH_CONFIG_CONSOLE_WIDTH
#define CATCH_CONFIG_CONSOLE_WIDTH 80
#endif
namespace Catch {
struct IStream;
struct ConfigData {
bool listTests = false;
bool listTags = false;
bool listReporters = false;
bool listTestNamesOnly = false;
bool showSuccessfulTests = false;
bool shouldDebugBreak = false;
bool noThrow = false;
bool showHelp = false;
bool showInvisibles = false;
bool filenamesAsTags = false;
bool libIdentify = false;
int abortAfter = -1;
unsigned int rngSeed = 0;
bool benchmarkNoAnalysis = false;
unsigned int benchmarkSamples = 100;
double benchmarkConfidenceInterval = 0.95;
unsigned int benchmarkResamples = 100000;
std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
Verbosity verbosity = Verbosity::Normal;
WarnAbout::What warnings = WarnAbout::Nothing;
ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
double minDuration = -1;
RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
UseColour::YesOrNo useColour = UseColour::Auto;
WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
std::string outputFilename;
std::string name;
std::string processName;
#ifndef CATCH_CONFIG_DEFAULT_REPORTER
#define CATCH_CONFIG_DEFAULT_REPORTER "console"
#endif
std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
#undef CATCH_CONFIG_DEFAULT_REPORTER
std::vector<std::string> testsOrTags;
std::vector<std::string> sectionsToRun;
};
class Config : public IConfig {
public:
Config() = default;
Config( ConfigData const& data );
virtual ~Config() = default;
std::string const& getFilename() const;
bool listTests() const;
bool listTestNamesOnly() const;
bool listTags() const;
bool listReporters() const;
std::string getProcessName() const;
std::string const& getReporterName() const;
std::vector<std::string> const& getTestsOrTags() const override;
std::vector<std::string> const& getSectionsToRun() const override;
TestSpec const& testSpec() const override;
bool hasTestFilters() const override;
bool showHelp() const;
// IConfig interface
bool allowThrows() const override;
std::ostream& stream() const override;
std::string name() const override;
bool includeSuccessfulResults() const override;
bool warnAboutMissingAssertions() const override;
bool warnAboutNoTests() const override;
ShowDurations::OrNot showDurations() const override;
double minDuration() const override;
RunTests::InWhatOrder runOrder() const override;
unsigned int rngSeed() const override;
UseColour::YesOrNo useColour() const override;
bool shouldDebugBreak() const override;
int abortAfter() const override;
bool showInvisibles() const override;
Verbosity verbosity() const override;
bool benchmarkNoAnalysis() const override;
int benchmarkSamples() const override;
double benchmarkConfidenceInterval() const override;
unsigned int benchmarkResamples() const override;
std::chrono::milliseconds benchmarkWarmupTime() const override;
private:
IStream const* openStream();
ConfigData m_data;
std::unique_ptr<IStream const> m_stream;
TestSpec m_testSpec;
bool m_hasTestFilters = false;
};
} // end namespace Catch
// end catch_config.hpp
// start catch_assertionresult.h
#include <string>
namespace Catch {
struct AssertionResultData
{
AssertionResultData() = delete;
AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
std::string message;
mutable std::string reconstructedExpression;
LazyExpression lazyExpression;
ResultWas::OfType resultType;
std::string reconstructExpression() const;
};
class AssertionResult {
public:
AssertionResult() = delete;
AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
bool isOk() const;
bool succeeded() const;
ResultWas::OfType getResultType() const;
bool hasExpression() const;
bool hasMessage() const;
std::string getExpression() const;
std::string getExpressionInMacro() const;
bool hasExpandedExpression() const;
std::string getExpandedExpression() const;
std::string getMessage() const;
SourceLineInfo getSourceInfo() const;
StringRef getTestMacroName() const;
//protected:
AssertionInfo m_info;
AssertionResultData m_resultData;
};
} // end namespace Catch
// end catch_assertionresult.h
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
// start catch_estimate.hpp
// Statistics estimates
namespace Catch {
namespace Benchmark {
template <typename Duration>
struct Estimate {
Duration point;
Duration lower_bound;
Duration upper_bound;
double confidence_interval;
template <typename Duration2>
operator Estimate<Duration2>() const {
return { point, lower_bound, upper_bound, confidence_interval };
}
};
} // namespace Benchmark
} // namespace Catch
// end catch_estimate.hpp
// start catch_outlier_classification.hpp
// Outlier information
namespace Catch {
namespace Benchmark {
struct OutlierClassification {
int samples_seen = 0;
int low_severe = 0; // more than 3 times IQR below Q1
int low_mild = 0; // 1.5 to 3 times IQR below Q1
int high_mild = 0; // 1.5 to 3 times IQR above Q3
int high_severe = 0; // more than 3 times IQR above Q3
int total() const {
return low_severe + low_mild + high_mild + high_severe;
}
};
} // namespace Benchmark
} // namespace Catch
// end catch_outlier_classification.hpp
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
#include <string>
#include <iosfwd>
#include <map>
#include <set>
#include <memory>
#include <algorithm>
namespace Catch {
struct ReporterConfig {
explicit ReporterConfig( IConfigPtr const& _fullConfig );
ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
std::ostream& stream() const;
IConfigPtr fullConfig() const;
private:
std::ostream* m_stream;
IConfigPtr m_fullConfig;
};
struct ReporterPreferences {
bool shouldRedirectStdOut = false;
bool shouldReportAllAssertions = false;
};
template<typename T>
struct LazyStat : Option<T> {
LazyStat& operator=( T const& _value ) {
Option<T>::operator=( _value );
used = false;
return *this;
}
void reset() {
Option<T>::reset();
used = false;
}
bool used = false;
};
struct TestRunInfo {
TestRunInfo( std::string const& _name );
std::string name;
};
struct GroupInfo {
GroupInfo( std::string const& _name,
std::size_t _groupIndex,
std::size_t _groupsCount );
std::string name;
std::size_t groupIndex;
std::size_t groupsCounts;
};
struct AssertionStats {
AssertionStats( AssertionResult const& _assertionResult,
std::vector<MessageInfo> const& _infoMessages,
Totals const& _totals );
AssertionStats( AssertionStats const& ) = default;
AssertionStats( AssertionStats && ) = default;
AssertionStats& operator = ( AssertionStats const& ) = delete;
AssertionStats& operator = ( AssertionStats && ) = delete;
virtual ~AssertionStats();
AssertionResult assertionResult;
std::vector<MessageInfo> infoMessages;
Totals totals;
};
struct SectionStats {
SectionStats( SectionInfo const& _sectionInfo,
Counts const& _assertions,
double _durationInSeconds,
bool _missingAssertions );
SectionStats( SectionStats const& ) = default;
SectionStats( SectionStats && ) = default;
SectionStats& operator = ( SectionStats const& ) = default;
SectionStats& operator = ( SectionStats && ) = default;
virtual ~SectionStats();
SectionInfo sectionInfo;
Counts assertions;
double durationInSeconds;
bool missingAssertions;
};
struct TestCaseStats {
TestCaseStats( TestCaseInfo const& _testInfo,
Totals const& _totals,
std::string const& _stdOut,
std::string const& _stdErr,
bool _aborting );
TestCaseStats( TestCaseStats const& ) = default;
TestCaseStats( TestCaseStats && ) = default;
TestCaseStats& operator = ( TestCaseStats const& ) = default;
TestCaseStats& operator = ( TestCaseStats && ) = default;
virtual ~TestCaseStats();
TestCaseInfo testInfo;
Totals totals;
std::string stdOut;
std::string stdErr;
bool aborting;
};
struct TestGroupStats {
TestGroupStats( GroupInfo const& _groupInfo,
Totals const& _totals,
bool _aborting );
TestGroupStats( GroupInfo const& _groupInfo );
TestGroupStats( TestGroupStats const& ) = default;
TestGroupStats( TestGroupStats && ) = default;
TestGroupStats& operator = ( TestGroupStats const& ) = default;
TestGroupStats& operator = ( TestGroupStats && ) = default;
virtual ~TestGroupStats();
GroupInfo groupInfo;
Totals totals;
bool aborting;
};
struct TestRunStats {
TestRunStats( TestRunInfo const& _runInfo,
Totals const& _totals,
bool _aborting );
TestRunStats( TestRunStats const& ) = default;
TestRunStats( TestRunStats && ) = default;
TestRunStats& operator = ( TestRunStats const& ) = default;
TestRunStats& operator = ( TestRunStats && ) = default;
virtual ~TestRunStats();
TestRunInfo runInfo;
Totals totals;
bool aborting;
};
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
struct BenchmarkInfo {
std::string name;
double estimatedDuration;
int iterations;
int samples;
unsigned int resamples;
double clockResolution;
double clockCost;
};
template <class Duration>
struct BenchmarkStats {
BenchmarkInfo info;
std::vector<Duration> samples;
Benchmark::Estimate<Duration> mean;
Benchmark::Estimate<Duration> standardDeviation;
Benchmark::OutlierClassification outliers;
double outlierVariance;
template <typename Duration2>
operator BenchmarkStats<Duration2>() const {
std::vector<Duration2> samples2;
samples2.reserve(samples.size());
std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
return {
info,
std::move(samples2),
mean,
standardDeviation,
outliers,
outlierVariance,
};
}
};
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
struct IStreamingReporter {
virtual ~IStreamingReporter() = default;
// Implementing class must also provide the following static methods:
// static std::string getDescription();
// static std::set<Verbosity> getSupportedVerbosities()
virtual ReporterPreferences getPreferences() const = 0;
virtual void noMatchingTestCases( std::string const& spec ) = 0;
virtual void reportInvalidArguments(std::string const&) {}
virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
virtual void benchmarkPreparing( std::string const& ) {}
virtual void benchmarkStarting( BenchmarkInfo const& ) {}
virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
virtual void benchmarkFailed( std::string const& ) {}
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
// The return value indicates if the messages buffer should be cleared:
virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
// Default empty implementation provided
virtual void fatalErrorEncountered( StringRef name );
virtual bool isMulti() const;
};
using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
struct IReporterFactory {
virtual ~IReporterFactory();
virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
virtual std::string getDescription() const = 0;
};
using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
struct IReporterRegistry {
using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
using Listeners = std::vector<IReporterFactoryPtr>;
virtual ~IReporterRegistry();
virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
virtual FactoryMap const& getFactories() const = 0;
virtual Listeners const& getListeners() const = 0;
};
} // end namespace Catch
// end catch_interfaces_reporter.h
#include <algorithm>
#include <cstring>
#include <cfloat>
#include <cstdio>
#include <cassert>
#include <memory>
#include <ostream>
namespace Catch {
void prepareExpandedExpression(AssertionResult& result);
// Returns double formatted as %.3f (format expected on output)
std::string getFormattedDuration( double duration );
//! Should the reporter show
bool shouldShowDuration( IConfig const& config, double duration );
std::string serializeFilters( std::vector<std::string> const& container );
template<typename DerivedT>
struct StreamingReporterBase : IStreamingReporter {
StreamingReporterBase( ReporterConfig const& _config )
: m_config( _config.fullConfig() ),
stream( _config.stream() )
{
m_reporterPrefs.shouldRedirectStdOut = false;
if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
CATCH_ERROR( "Verbosity level not supported by this reporter" );
}
ReporterPreferences getPreferences() const override {
return m_reporterPrefs;
}
static std::set<Verbosity> getSupportedVerbosities() {
return { Verbosity::Normal };
}
~StreamingReporterBase() override = default;
void noMatchingTestCases(std::string const&) override {}
void reportInvalidArguments(std::string const&) override {}
void testRunStarting(TestRunInfo const& _testRunInfo) override {
currentTestRunInfo = _testRunInfo;
}
void testGroupStarting(GroupInfo const& _groupInfo) override {
currentGroupInfo = _groupInfo;
}
void testCaseStarting(TestCaseInfo const& _testInfo) override {
currentTestCaseInfo = _testInfo;
}
void sectionStarting(SectionInfo const& _sectionInfo) override {
m_sectionStack.push_back(_sectionInfo);
}
void sectionEnded(SectionStats const& /* _sectionStats */) override {
m_sectionStack.pop_back();
}
void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
currentTestCaseInfo.reset();
}
void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
currentGroupInfo.reset();
}
void testRunEnded(TestRunStats const& /* _testRunStats */) override {
currentTestCaseInfo.reset();
currentGroupInfo.reset();
currentTestRunInfo.reset();
}
void skipTest(TestCaseInfo const&) override {
// Don't do anything with this by default.
// It can optionally be overridden in the derived class.
}
IConfigPtr m_config;
std::ostream& stream;
LazyStat<TestRunInfo> currentTestRunInfo;
LazyStat<GroupInfo> currentGroupInfo;
LazyStat<TestCaseInfo> currentTestCaseInfo;
std::vector<SectionInfo> m_sectionStack;
ReporterPreferences m_reporterPrefs;
};
template<typename DerivedT>
struct CumulativeReporterBase : IStreamingReporter {
template<typename T, typename ChildNodeT>
struct Node {
explicit Node( T const& _value ) : value( _value ) {}
virtual ~Node() {}
using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
T value;
ChildNodes children;
};
struct SectionNode {
explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
virtual ~SectionNode() = default;
bool operator == (SectionNode const& other) const {
return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
}
bool operator == (std::shared_ptr<SectionNode> const& other) const {
return operator==(*other);
}
SectionStats stats;
using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
using Assertions = std::vector<AssertionStats>;
ChildSections childSections;
Assertions assertions;
std::string stdOut;
std::string stdErr;
};
struct BySectionInfo {
BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
bool operator() (std::shared_ptr<SectionNode> const& node) const {
return ((node->stats.sectionInfo.name == m_other.name) &&
(node->stats.sectionInfo.lineInfo == m_other.lineInfo));
}
void operator=(BySectionInfo const&) = delete;
private:
SectionInfo const& m_other;
};
using TestCaseNode = Node<TestCaseStats, SectionNode>;
using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
using TestRunNode = Node<TestRunStats, TestGroupNode>;
CumulativeReporterBase( ReporterConfig const& _config )
: m_config( _config.fullConfig() ),
stream( _config.stream() )
{
m_reporterPrefs.shouldRedirectStdOut = false;
if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
CATCH_ERROR( "Verbosity level not supported by this reporter" );
}
~CumulativeReporterBase() override = default;
ReporterPreferences getPreferences() const override {
return m_reporterPrefs;
}
static std::set<Verbosity> getSupportedVerbosities() {
return { Verbosity::Normal };
}
void testRunStarting( TestRunInfo const& ) override {}
void testGroupStarting( GroupInfo const& ) override {}
void testCaseStarting( TestCaseInfo const& ) override {}
void sectionStarting( SectionInfo const& sectionInfo ) override {
SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
std::shared_ptr<SectionNode> node;
if( m_sectionStack.empty() ) {
if( !m_rootSection )
m_rootSection = std::make_shared<SectionNode>( incompleteStats );
node = m_rootSection;
}
else {
SectionNode& parentNode = *m_sectionStack.back();
auto it =
std::find_if( parentNode.childSections.begin(),
parentNode.childSections.end(),
BySectionInfo( sectionInfo ) );
if( it == parentNode.childSections.end() ) {
node = std::make_shared<SectionNode>( incompleteStats );
parentNode.childSections.push_back( node );
}
else
node = *it;
}
m_sectionStack.push_back( node );
m_deepestSection = std::move(node);
}
void assertionStarting(AssertionInfo const&) override {}
bool assertionEnded(AssertionStats const& assertionStats) override {
assert(!m_sectionStack.empty());
// AssertionResult holds a pointer to a temporary DecomposedExpression,
// which getExpandedExpression() calls to build the expression string.
// Our section stack copy of the assertionResult will likely outlive the
// temporary, so it must be expanded or discarded now to avoid calling
// a destroyed object later.
prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
SectionNode& sectionNode = *m_sectionStack.back();
sectionNode.assertions.push_back(assertionStats);
return true;
}
void sectionEnded(SectionStats const& sectionStats) override {
assert(!m_sectionStack.empty());
SectionNode& node = *m_sectionStack.back();
node.stats = sectionStats;
m_sectionStack.pop_back();
}
void testCaseEnded(TestCaseStats const& testCaseStats) override {
auto node = std::make_shared<TestCaseNode>(testCaseStats);
assert(m_sectionStack.size() == 0);
node->children.push_back(m_rootSection);
m_testCases.push_back(node);
m_rootSection.reset();
assert(m_deepestSection);
m_deepestSection->stdOut = testCaseStats.stdOut;
m_deepestSection->stdErr = testCaseStats.stdErr;
}
void testGroupEnded(TestGroupStats const& testGroupStats) override {
auto node = std::make_shared<TestGroupNode>(testGroupStats);
node->children.swap(m_testCases);
m_testGroups.push_back(node);
}
void testRunEnded(TestRunStats const& testRunStats) override {
auto node = std::make_shared<TestRunNode>(testRunStats);
node->children.swap(m_testGroups);
m_testRuns.push_back(node);
testRunEndedCumulative();
}
virtual void testRunEndedCumulative() = 0;
void skipTest(TestCaseInfo const&) override {}
IConfigPtr m_config;
std::ostream& stream;
std::vector<AssertionStats> m_assertions;
std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
std::shared_ptr<SectionNode> m_rootSection;
std::shared_ptr<SectionNode> m_deepestSection;
std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
ReporterPreferences m_reporterPrefs;
};
template<char C>
char const* getLineOfChars() {
static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
if( !*line ) {
std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
}
return line;
}
struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
TestEventListenerBase( ReporterConfig const& _config );
static std::set<Verbosity> getSupportedVerbosities();
void assertionStarting(AssertionInfo const&) override;
bool assertionEnded(AssertionStats const&) override;
};
} // end namespace Catch
// end catch_reporter_bases.hpp
// start catch_console_colour.h
namespace Catch {
struct Colour {
enum Code {
None = 0,
White,
Red,
Green,
Blue,
Cyan,
Yellow,
Grey,
Bright = 0x10,
BrightRed = Bright | Red,
BrightGreen = Bright | Green,
LightGrey = Bright | Grey,
BrightWhite = Bright | White,
BrightYellow = Bright | Yellow,
// By intention
FileName = LightGrey,
Warning = BrightYellow,
ResultError = BrightRed,
ResultSuccess = BrightGreen,
ResultExpectedFailure = Warning,
Error = BrightRed,
Success = Green,
OriginalExpression = Cyan,
ReconstructedExpression = BrightYellow,
SecondaryText = LightGrey,
Headers = White
};
// Use constructed object for RAII guard
Colour( Code _colourCode );
Colour( Colour&& other ) noexcept;
Colour& operator=( Colour&& other ) noexcept;
~Colour();
// Use static method for one-shot changes
static void use( Code _colourCode );
private:
bool m_moved = false;
};
std::ostream& operator << ( std::ostream& os, Colour const& );
} // end namespace Catch
// end catch_console_colour.h
// start catch_reporter_registrars.hpp
namespace Catch {
template<typename T>
class ReporterRegistrar {
class ReporterFactory : public IReporterFactory {
IStreamingReporterPtr create( ReporterConfig const& config ) const override {
return std::unique_ptr<T>( new T( config ) );
}
std::string getDescription() const override {
return T::getDescription();
}
};
public:
explicit ReporterRegistrar( std::string const& name ) {
getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
}
};
template<typename T>
class ListenerRegistrar {
class ListenerFactory : public IReporterFactory {
IStreamingReporterPtr create( ReporterConfig const& config ) const override {
return std::unique_ptr<T>( new T( config ) );
}
std::string getDescription() const override {
return std::string();
}
};
public:
ListenerRegistrar() {
getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
}
};
}
#if !defined(CATCH_CONFIG_DISABLE)
#define CATCH_REGISTER_REPORTER( name, reporterType ) \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
#define CATCH_REGISTER_LISTENER( listenerType ) \
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
#else // CATCH_CONFIG_DISABLE
#define CATCH_REGISTER_REPORTER(name, reporterType)
#define CATCH_REGISTER_LISTENER(listenerType)
#endif // CATCH_CONFIG_DISABLE
// end catch_reporter_registrars.hpp
// Allow users to base their work off existing reporters
// start catch_reporter_compact.h
namespace Catch {
struct CompactReporter : StreamingReporterBase<CompactReporter> {
using StreamingReporterBase::StreamingReporterBase;
~CompactReporter() override;
static std::string getDescription();
void noMatchingTestCases(std::string const& spec) override;
void assertionStarting(AssertionInfo const&) override;
bool assertionEnded(AssertionStats const& _assertionStats) override;
void sectionEnded(SectionStats const& _sectionStats) override;
void testRunEnded(TestRunStats const& _testRunStats) override;
};
} // end namespace Catch
// end catch_reporter_compact.h
// start catch_reporter_console.h
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
// Note that 4062 (not all labels are handled
// and default is missing) is enabled
#endif
namespace Catch {
// Fwd decls
struct SummaryColumn;
class TablePrinter;
struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
std::unique_ptr<TablePrinter> m_tablePrinter;
ConsoleReporter(ReporterConfig const& config);
~ConsoleReporter() override;
static std::string getDescription();
void noMatchingTestCases(std::string const& spec) override;
void reportInvalidArguments(std::string const&arg) override;
void assertionStarting(AssertionInfo const&) override;
bool assertionEnded(AssertionStats const& _assertionStats) override;
void sectionStarting(SectionInfo const& _sectionInfo) override;
void sectionEnded(SectionStats const& _sectionStats) override;
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
void benchmarkPreparing(std::string const& name) override;
void benchmarkStarting(BenchmarkInfo const& info) override;
void benchmarkEnded(BenchmarkStats<> const& stats) override;
void benchmarkFailed(std::string const& error) override;
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
void testCaseEnded(TestCaseStats const& _testCaseStats) override;
void testGroupEnded(TestGroupStats const& _testGroupStats) override;
void testRunEnded(TestRunStats const& _testRunStats) override;
void testRunStarting(TestRunInfo const& _testRunInfo) override;
private:
void lazyPrint();
void lazyPrintWithoutClosingBenchmarkTable();
void lazyPrintRunInfo();
void lazyPrintGroupInfo();
void printTestCaseAndSectionHeader();
void printClosedHeader(std::string const& _name);
void printOpenHeader(std::string const& _name);
// if string has a : in first line will set indent to follow it on
// subsequent lines
void printHeaderString(std::string const& _string, std::size_t indent = 0);
void printTotals(Totals const& totals);
void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
void printTotalsDivider(Totals const& totals);
void printSummaryDivider();
void printTestFilters();
private:
bool m_headerPrinted = false;
};
} // end namespace Catch
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
// end catch_reporter_console.h
// start catch_reporter_junit.h
// start catch_xmlwriter.h
#include <vector>
namespace Catch {
enum class XmlFormatting {
None = 0x00,
Indent = 0x01,
Newline = 0x02,
};
XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
class XmlEncode {
public:
enum ForWhat { ForTextNodes, ForAttributes };
XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
void encodeTo( std::ostream& os ) const;
friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
private:
std::string m_str;
ForWhat m_forWhat;
};
class XmlWriter {
public:
class ScopedElement {
public:
ScopedElement( XmlWriter* writer, XmlFormatting fmt );
ScopedElement( ScopedElement&& other ) noexcept;
ScopedElement& operator=( ScopedElement&& other ) noexcept;
~ScopedElement();
ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
template<typename T>
ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
m_writer->writeAttribute( name, attribute );
return *this;
}
private:
mutable XmlWriter* m_writer = nullptr;
XmlFormatting m_fmt;
};
XmlWriter( std::ostream& os = Catch::cout() );
~XmlWriter();
XmlWriter( XmlWriter const& ) = delete;
XmlWriter& operator=( XmlWriter const& ) = delete;
XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
XmlWriter& writeAttribute( std::string const& name, bool attribute );
template<typename T>
XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
ReusableStringStream rss;
rss << attribute;
return writeAttribute( name, rss.str() );
}
XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
void writeStylesheetRef( std::string const& url );
XmlWriter& writeBlankLine();
void ensureTagClosed();
private:
void applyFormatting(XmlFormatting fmt);
void writeDeclaration();
void newlineIfNecessary();
bool m_tagIsOpen = false;
bool m_needsNewline = false;
std::vector<std::string> m_tags;
std::string m_indent;
std::ostream& m_os;
};
}
// end catch_xmlwriter.h
namespace Catch {
class JunitReporter : public CumulativeReporterBase<JunitReporter> {
public:
JunitReporter(ReporterConfig const& _config);
~JunitReporter() override;
static std::string getDescription();
void noMatchingTestCases(std::string const& /*spec*/) override;
void testRunStarting(TestRunInfo const& runInfo) override;
void testGroupStarting(GroupInfo const& groupInfo) override;
void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
bool assertionEnded(AssertionStats const& assertionStats) override;
void testCaseEnded(TestCaseStats const& testCaseStats) override;
void testGroupEnded(TestGroupStats const& testGroupStats) override;
void testRunEndedCumulative() override;
void writeGroup(TestGroupNode const& groupNode, double suiteTime);
void writeTestCase(TestCaseNode const& testCaseNode);
void writeSection(std::string const& className,
std::string const& rootName,
SectionNode const& sectionNode);
void writeAssertions(SectionNode const& sectionNode);
void writeAssertion(AssertionStats const& stats);
XmlWriter xml;
Timer suiteTimer;
std::string stdOutForSuite;
std::string stdErrForSuite;
unsigned int unexpectedExceptions = 0;
bool m_okToFail = false;
};
} // end namespace Catch
// end catch_reporter_junit.h
// start catch_reporter_xml.h
namespace Catch {
class XmlReporter : public StreamingReporterBase<XmlReporter> {
public:
XmlReporter(ReporterConfig const& _config);
~XmlReporter() override;
static std::string getDescription();
virtual std::string getStylesheetRef() const;
void writeSourceInfo(SourceLineInfo const& sourceInfo);
public: // StreamingReporterBase
void noMatchingTestCases(std::string const& s) override;
void testRunStarting(TestRunInfo const& testInfo) override;
void testGroupStarting(GroupInfo const& groupInfo) override;
void testCaseStarting(TestCaseInfo const& testInfo) override;
void sectionStarting(SectionInfo const& sectionInfo) override;
void assertionStarting(AssertionInfo const&) override;
bool assertionEnded(AssertionStats const& assertionStats) override;
void sectionEnded(SectionStats const& sectionStats) override;
void testCaseEnded(TestCaseStats const& testCaseStats) override;
void testGroupEnded(TestGroupStats const& testGroupStats) override;
void testRunEnded(TestRunStats const& testRunStats) override;
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
void benchmarkPreparing(std::string const& name) override;
void benchmarkStarting(BenchmarkInfo const&) override;
void benchmarkEnded(BenchmarkStats<> const&) override;
void benchmarkFailed(std::string const&) override;
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
private:
Timer m_testCaseTimer;
XmlWriter m_xml;
int m_sectionDepth = 0;
};
} // end namespace Catch
// end catch_reporter_xml.h
// end catch_external_interfaces.h
#endif
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
// start catch_benchmarking_all.hpp
// A proxy header that includes all of the benchmarking headers to allow
// concise include of the benchmarking features. You should prefer the
// individual includes in standard use.
// start catch_benchmark.hpp
// Benchmark
// start catch_chronometer.hpp
// User-facing chronometer
// start catch_clock.hpp
// Clocks
#include <chrono>
#include <ratio>
namespace Catch {
namespace Benchmark {
template <typename Clock>
using ClockDuration = typename Clock::duration;
template <typename Clock>
using FloatDuration = std::chrono::duration<double, typename Clock::period>;
template <typename Clock>
using TimePoint = typename Clock::time_point;
using default_clock = std::chrono::steady_clock;
template <typename Clock>
struct now {
TimePoint<Clock> operator()() const {
return Clock::now();
}
};
using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
} // namespace Benchmark
} // namespace Catch
// end catch_clock.hpp
// start catch_optimizer.hpp
// Hinting the optimizer
#if defined(_MSC_VER)
# include <atomic> // atomic_thread_fence
#endif
namespace Catch {
namespace Benchmark {
#if defined(__GNUC__) || defined(__clang__)
template <typename T>
inline void keep_memory(T* p) {
asm volatile("" : : "g"(p) : "memory");
}
inline void keep_memory() {
asm volatile("" : : : "memory");
}
namespace Detail {
inline void optimizer_barrier() { keep_memory(); }
} // namespace Detail
#elif defined(_MSC_VER)
#pragma optimize("", off)
template <typename T>
inline void keep_memory(T* p) {
// thanks @milleniumbug
*reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
}
// TODO equivalent keep_memory()
#pragma optimize("", on)
namespace Detail {
inline void optimizer_barrier() {
std::atomic_thread_fence(std::memory_order_seq_cst);
}
} // namespace Detail
#endif
template <typename T>
inline void deoptimize_value(T&& x) {
keep_memory(&x);
}
template <typename Fn, typename... Args>
inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
}
template <typename Fn, typename... Args>
inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
std::forward<Fn>(fn) (std::forward<Args...>(args...));
}
} // namespace Benchmark
} // namespace Catch
// end catch_optimizer.hpp
// start catch_complete_invoke.hpp
// Invoke with a special case for void
#include <type_traits>
#include <utility>
namespace Catch {
namespace Benchmark {
namespace Detail {
template <typename T>
struct CompleteType { using type = T; };
template <>
struct CompleteType<void> { struct type {}; };
template <typename T>
using CompleteType_t = typename CompleteType<T>::type;
template <typename Result>
struct CompleteInvoker {
template <typename Fun, typename... Args>
static Result invoke(Fun&& fun, Args&&... args) {
return std::forward<Fun>(fun)(std::forward<Args>(args)...);
}
};
template <>
struct CompleteInvoker<void> {
template <typename Fun, typename... Args>
static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
std::forward<Fun>(fun)(std::forward<Args>(args)...);
return {};
}
};
// invoke and not return void :(
template <typename Fun, typename... Args>
CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
}
const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
} // namespace Detail
template <typename Fun>
Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
CATCH_TRY{
return Detail::complete_invoke(std::forward<Fun>(fun));
} CATCH_CATCH_ALL{
getResultCapture().benchmarkFailed(translateActiveException());
CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
}
}
} // namespace Benchmark
} // namespace Catch
// end catch_complete_invoke.hpp
namespace Catch {
namespace Benchmark {
namespace Detail {
struct ChronometerConcept {
virtual void start() = 0;
virtual void finish() = 0;
virtual ~ChronometerConcept() = default;
};
template <typename Clock>
struct ChronometerModel final : public ChronometerConcept {
void start() override { started = Clock::now(); }
void finish() override { finished = Clock::now(); }
ClockDuration<Clock> elapsed() const { return finished - started; }
TimePoint<Clock> started;
TimePoint<Clock> finished;
};
} // namespace Detail
struct Chronometer {
public:
template <typename Fun>
void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
int runs() const { return k; }
Chronometer(Detail::ChronometerConcept& meter, int k)
: impl(&meter)
, k(k) {}
private:
template <typename Fun>
void measure(Fun&& fun, std::false_type) {
measure([&fun](int) { return fun(); }, std::true_type());
}
template <typename Fun>
void measure(Fun&& fun, std::true_type) {
Detail::optimizer_barrier();
impl->start();
for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
impl->finish();
Detail::optimizer_barrier();
}
Detail::ChronometerConcept* impl;
int k;
};
} // namespace Benchmark
} // namespace Catch
// end catch_chronometer.hpp
// start catch_environment.hpp
// Environment information
namespace Catch {
namespace Benchmark {
template <typename Duration>
struct EnvironmentEstimate {
Duration mean;
OutlierClassification outliers;
template <typename Duration2>
operator EnvironmentEstimate<Duration2>() const {
return { mean, outliers };
}
};
template <typename Clock>
struct Environment {
using clock_type = Clock;
EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
};
} // namespace Benchmark
} // namespace Catch
// end catch_environment.hpp
// start catch_execution_plan.hpp
// Execution plan
// start catch_benchmark_function.hpp
// Dumb std::function implementation for consistent call overhead
#include <cassert>
#include <type_traits>
#include <utility>
#include <memory>
namespace Catch {
namespace Benchmark {
namespace Detail {
template <typename T>
using Decay = typename std::decay<T>::type;
template <typename T, typename U>
struct is_related
: std::is_same<Decay<T>, Decay<U>> {};
/// We need to reinvent std::function because every piece of code that might add overhead
/// in a measurement context needs to have consistent performance characteristics so that we
/// can account for it in the measurement.
/// Implementations of std::function with optimizations that aren't always applicable, like
/// small buffer optimizations, are not uncommon.
/// This is effectively an implementation of std::function without any such optimizations;
/// it may be slow, but it is consistently slow.
struct BenchmarkFunction {
private:
struct callable {
virtual void call(Chronometer meter) const = 0;
virtual callable* clone() const = 0;
virtual ~callable() = default;
};
template <typename Fun>
struct model : public callable {
model(Fun&& fun) : fun(std::move(fun)) {}
model(Fun const& fun) : fun(fun) {}
model<Fun>* clone() const override { return new model<Fun>(*this); }
void call(Chronometer meter) const override {
call(meter, is_callable<Fun(Chronometer)>());
}
void call(Chronometer meter, std::true_type) const {
fun(meter);
}
void call(Chronometer meter, std::false_type) const {
meter.measure(fun);
}
Fun fun;
};
struct do_nothing { void operator()() const {} };
template <typename T>
BenchmarkFunction(model<T>* c) : f(c) {}
public:
BenchmarkFunction()
: f(new model<do_nothing>{ {} }) {}
template <typename Fun,
typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
BenchmarkFunction(Fun&& fun)
: f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
BenchmarkFunction(BenchmarkFunction&& that)
: f(std::move(that.f)) {}
BenchmarkFunction(BenchmarkFunction const& that)
: f(that.f->clone()) {}
BenchmarkFunction& operator=(BenchmarkFunction&& that) {
f = std::move(that.f);
return *this;
}
BenchmarkFunction& operator=(BenchmarkFunction const& that) {
f.reset(that.f->clone());
return *this;
}
void operator()(Chronometer meter) const { f->call(meter); }
private:
std::unique_ptr<callable> f;
};
} // namespace Detail
} // namespace Benchmark
} // namespace Catch
// end catch_benchmark_function.hpp
// start catch_repeat.hpp
// repeat algorithm
#include <type_traits>
#include <utility>
namespace Catch {
namespace Benchmark {
namespace Detail {
template <typename Fun>
struct repeater {
void operator()(int k) const {
for (int i = 0; i < k; ++i) {
fun();
}
}
Fun fun;
};
template <typename Fun>
repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
return { std::forward<Fun>(fun) };
}
} // namespace Detail
} // namespace Benchmark
} // namespace Catch
// end catch_repeat.hpp
// start catch_run_for_at_least.hpp
// Run a function for a minimum amount of time
// start catch_measure.hpp
// Measure
// start catch_timing.hpp
// Timing
#include <tuple>
#include <type_traits>
namespace Catch {
namespace Benchmark {
template <typename Duration, typename Result>
struct Timing {
Duration elapsed;
Result result;
int iterations;
};
template <typename Clock, typename Func, typename... Args>
using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
} // namespace Benchmark
} // namespace Catch
// end catch_timing.hpp
#include <utility>
namespace Catch {
namespace Benchmark {
namespace Detail {
template <typename Clock, typename Fun, typename... Args>
TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
auto start = Clock::now();
auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
auto end = Clock::now();
auto delta = end - start;
return { delta, std::forward<decltype(r)>(r), 1 };
}
} // namespace Detail
} // namespace Benchmark
} // namespace Catch
// end catch_measure.hpp
#include <utility>
#include <type_traits>
namespace Catch {
namespace Benchmark {
namespace Detail {
template <typename Clock, typename Fun>
TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
return Detail::measure<Clock>(fun, iters);
}
template <typename Clock, typename Fun>
TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
Detail::ChronometerModel<Clock> meter;
auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
return { meter.elapsed(), std::move(result), iters };
}
template <typename Clock, typename Fun>
using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
struct optimized_away_error : std::exception {
const char* what() const noexcept override {
return "could not measure benchmark, maybe it was optimized away";
}
};
template <typename Clock, typename Fun>
TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
auto iters = seed;
while (iters < (1 << 30)) {
auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
if (Timing.elapsed >= how_long) {
return { Timing.elapsed, std::move(Timing.result), iters };
}
iters *= 2;
}
throw optimized_away_error{};
}
} // namespace Detail
} // namespace Benchmark
} // namespace Catch
// end catch_run_for_at_least.hpp
#include <algorithm>
namespace Catch {
namespace Benchmark {
template <typename Duration>
struct ExecutionPlan {
int iterations_per_sample;
Duration estimated_duration;
Detail::BenchmarkFunction benchmark;
Duration warmup_time;
int warmup_iterations;
template <typename Duration2>
operator ExecutionPlan<Duration2>() const {
return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
}
template <typename Clock>
std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
// warmup a bit
Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
std::vector<FloatDuration<Clock>> times;
times.reserve(cfg.benchmarkSamples());
std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
Detail::ChronometerModel<Clock> model;
this->benchmark(Chronometer(model, iterations_per_sample));
auto sample_time = model.elapsed() - env.clock_cost.mean;
if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
return sample_time / iterations_per_sample;
});
return times;
}
};
} // namespace Benchmark
} // namespace Catch
// end catch_execution_plan.hpp
// start catch_estimate_clock.hpp
// Environment measurement
// start catch_stats.hpp
// Statistical analysis tools
#include <algorithm>
#include <functional>
#include <vector>
#include <iterator>
#include <numeric>
#include <tuple>
#include <cmath>
#include <utility>
#include <cstddef>
#include <random>
namespace Catch {
namespace Benchmark {
namespace Detail {
using sample = std::vector<double>;
double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
template <typename Iterator>
OutlierClassification classify_outliers(Iterator first, Iterator last) {
std::vector<double> copy(first, last);
auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
auto iqr = q3 - q1;
auto los = q1 - (iqr * 3.);
auto lom = q1 - (iqr * 1.5);
auto him = q3 + (iqr * 1.5);
auto his = q3 + (iqr * 3.);
OutlierClassification o;
for (; first != last; ++first) {
auto&& t = *first;
if (t < los) ++o.low_severe;
else if (t < lom) ++o.low_mild;
else if (t > his) ++o.high_severe;
else if (t > him) ++o.high_mild;
++o.samples_seen;
}
return o;
}
template <typename Iterator>
double mean(Iterator first, Iterator last) {
auto count = last - first;
double sum = std::accumulate(first, last, 0.);
return sum / count;
}
template <typename URng, typename Iterator, typename Estimator>
sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
auto n = last - first;
std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
sample out;
out.reserve(resamples);
std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
std::vector<double> resampled;
resampled.reserve(n);
std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
return estimator(resampled.begin(), resampled.end());
});
std::sort(out.begin(), out.end());
return out;
}
template <typename Estimator, typename Iterator>
sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
auto n = last - first;
auto second = std::next(first);
sample results;
results.reserve(n);
for (auto it = first; it != last; ++it) {
std::iter_swap(it, first);
results.push_back(estimator(second, last));
}
return results;
}
inline double normal_cdf(double x) {
return std::erfc(-x / std::sqrt(2.0)) / 2.0;
}
double erfc_inv(double x);
double normal_quantile(double p);
template <typename Iterator, typename Estimator>
Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
auto n_samples = last - first;
double point = estimator(first, last);
// Degenerate case with a single sample
if (n_samples == 1) return { point, point, point, confidence_level };
sample jack = jackknife(estimator, first, last);
double jack_mean = mean(jack.begin(), jack.end());
double sum_squares, sum_cubes;
std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
auto d = jack_mean - x;
auto d2 = d * d;
auto d3 = d2 * d;
return { sqcb.first + d2, sqcb.second + d3 };
});
double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
int n = static_cast<int>(resample.size());
double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
// degenerate case with uniform samples
if (prob_n == 0) return { point, point, point, confidence_level };
double bias = normal_quantile(prob_n);
double z1 = normal_quantile((1. - confidence_level) / 2.);
auto cumn = [n](double x) -> int {
return std::lround(normal_cdf(x) * n); };
auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
double b1 = bias + z1;
double b2 = bias - z1;
double a1 = a(b1);
double a2 = a(b2);
auto lo = std::max(cumn(a1), 0);
auto hi = std::min(cumn(a2), n - 1);
return { point, resample[lo], resample[hi], confidence_level };
}
double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
struct bootstrap_analysis {
Estimate<double> mean;
Estimate<double> standard_deviation;
double outlier_variance;
};
bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
} // namespace Detail
} // namespace Benchmark
} // namespace Catch
// end catch_stats.hpp
#include <algorithm>
#include <iterator>
#include <tuple>
#include <vector>
#include <cmath>
namespace Catch {
namespace Benchmark {
namespace Detail {
template <typename Clock>
std::vector<double> resolution(int k) {
std::vector<TimePoint<Clock>> times;
times.reserve(k + 1);
std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
std::vector<double> deltas;
deltas.reserve(k);
std::transform(std::next(times.begin()), times.end(), times.begin(),
std::back_inserter(deltas),
[](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
return deltas;
}
const auto warmup_iterations = 10000;
const auto warmup_time = std::chrono::milliseconds(100);
const auto minimum_ticks = 1000;
const auto warmup_seed = 10000;
const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
const auto clock_cost_estimation_tick_limit = 100000;
const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
const auto clock_cost_estimation_iterations = 10000;
template <typename Clock>
int warmup() {
return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
.iterations;
}
template <typename Clock>
EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
.result;
return {
FloatDuration<Clock>(mean(r.begin(), r.end())),
classify_outliers(r.begin(), r.end()),
};
}
template <typename Clock>
EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
auto time_clock = [](int k) {
return Detail::measure<Clock>([k] {
for (int i = 0; i < k; ++i) {
volatile auto ignored = Clock::now();
(void)ignored;
}
}).elapsed;
};
time_clock(1);
int iters = clock_cost_estimation_iterations;
auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
std::vector<double> times;
int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
times.reserve(nsamples);
std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
});
return {
FloatDuration<Clock>(mean(times.begin(), times.end())),
classify_outliers(times.begin(), times.end()),
};
}
template <typename Clock>
Environment<FloatDuration<Clock>> measure_environment() {
static Environment<FloatDuration<Clock>>* env = nullptr;
if (env) {
return *env;
}
auto iters = Detail::warmup<Clock>();
auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
env = new Environment<FloatDuration<Clock>>{ resolution, cost };
return *env;
}
} // namespace Detail
} // namespace Benchmark
} // namespace Catch
// end catch_estimate_clock.hpp
// start catch_analyse.hpp
// Run and analyse one benchmark
// start catch_sample_analysis.hpp
// Benchmark results
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
namespace Catch {
namespace Benchmark {
template <typename Duration>
struct SampleAnalysis {
std::vector<Duration> samples;
Estimate<Duration> mean;
Estimate<Duration> standard_deviation;
OutlierClassification outliers;
double outlier_variance;
template <typename Duration2>
operator SampleAnalysis<Duration2>() const {
std::vector<Duration2> samples2;
samples2.reserve(samples.size());
std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
return {
std::move(samples2),
mean,
standard_deviation,
outliers,
outlier_variance,
};
}
};
} // namespace Benchmark
} // namespace Catch
// end catch_sample_analysis.hpp
#include <algorithm>
#include <iterator>
#include <vector>
namespace Catch {
namespace Benchmark {
namespace Detail {
template <typename Duration, typename Iterator>
SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
if (!cfg.benchmarkNoAnalysis()) {
std::vector<double> samples;
samples.reserve(last - first);
std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
auto wrap_estimate = [](Estimate<double> e) {
return Estimate<Duration> {
Duration(e.point),
Duration(e.lower_bound),
Duration(e.upper_bound),
e.confidence_interval,
};
};
std::vector<Duration> samples2;
samples2.reserve(samples.size());
std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
return {
std::move(samples2),
wrap_estimate(analysis.mean),
wrap_estimate(analysis.standard_deviation),
outliers,
analysis.outlier_variance,
};
} else {
std::vector<Duration> samples;
samples.reserve(last - first);
Duration mean = Duration(0);
int i = 0;
for (auto it = first; it < last; ++it, ++i) {
samples.push_back(Duration(*it));
mean += Duration(*it);
}
mean /= i;
return {
std::move(samples),
Estimate<Duration>{mean, mean, mean, 0.0},
Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
OutlierClassification{},
0.0
};
}
}
} // namespace Detail
} // namespace Benchmark
} // namespace Catch
// end catch_analyse.hpp
#include <algorithm>
#include <functional>
#include <string>
#include <vector>
#include <cmath>
namespace Catch {
namespace Benchmark {
struct Benchmark {
Benchmark(std::string &&name)
: name(std::move(name)) {}
template <class FUN>
Benchmark(std::string &&name, FUN &&func)
: fun(std::move(func)), name(std::move(name)) {}
template <typename Clock>
ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
}
template <typename Clock = default_clock>
void run() {
IConfigPtr cfg = getCurrentContext().getConfig();
auto env = Detail::measure_environment<Clock>();
getResultCapture().benchmarkPreparing(name);
CATCH_TRY{
auto plan = user_code([&] {
return prepare<Clock>(*cfg, env);
});
BenchmarkInfo info {
name,
plan.estimated_duration.count(),
plan.iterations_per_sample,
cfg->benchmarkSamples(),
cfg->benchmarkResamples(),
env.clock_resolution.mean.count(),
env.clock_cost.mean.count()
};
getResultCapture().benchmarkStarting(info);
auto samples = user_code([&] {
return plan.template run<Clock>(*cfg, env);
});
auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
getResultCapture().benchmarkEnded(stats);
} CATCH_CATCH_ALL{
if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
std::rethrow_exception(std::current_exception());
}
}
// sets lambda to be used in fun *and* executes benchmark!
template <typename Fun,
typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
Benchmark & operator=(Fun func) {
fun = Detail::BenchmarkFunction(func);
run();
return *this;
}
explicit operator bool() {
return true;
}
private:
Detail::BenchmarkFunction fun;
std::string name;
};
}
} // namespace Catch
#define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
#define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
#define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
BenchmarkName = [&](int benchmarkIndex)
#define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
BenchmarkName = [&]
// end catch_benchmark.hpp
// start catch_constructor.hpp
// Constructor and destructor helpers
#include <type_traits>
namespace Catch {
namespace Benchmark {
namespace Detail {
template <typename T, bool Destruct>
struct ObjectStorage
{
using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
ObjectStorage() : data() {}
ObjectStorage(const ObjectStorage& other)
{
new(&data) T(other.stored_object());
}
ObjectStorage(ObjectStorage&& other)
{
new(&data) T(std::move(other.stored_object()));
}
~ObjectStorage() { destruct_on_exit<T>(); }
template <typename... Args>
void construct(Args&&... args)
{
new (&data) T(std::forward<Args>(args)...);
}
template <bool AllowManualDestruction = !Destruct>
typename std::enable_if<AllowManualDestruction>::type destruct()
{
stored_object().~T();
}
private:
// If this is a constructor benchmark, destruct the underlying object
template <typename U>
void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
// Otherwise, don't
template <typename U>
void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
T& stored_object() {
return *static_cast<T*>(static_cast<void*>(&data));
}
T const& stored_object() const {
return *static_cast<T*>(static_cast<void*>(&data));
}
TStorage data;
};
}
template <typename T>
using storage_for = Detail::ObjectStorage<T, true>;
template <typename T>
using destructable_object = Detail::ObjectStorage<T, false>;
}
}
// end catch_constructor.hpp
// end catch_benchmarking_all.hpp
#endif
#endif // ! CATCH_CONFIG_IMPL_ONLY
#ifdef CATCH_IMPL
// start catch_impl.hpp
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wweak-vtables"
#endif
// Keep these here for external reporters
// start catch_test_case_tracker.h
#include <string>
#include <vector>
#include <memory>
namespace Catch {
namespace TestCaseTracking {
struct NameAndLocation {
std::string name;
SourceLineInfo location;
NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
return lhs.name == rhs.name
&& lhs.location == rhs.location;
}
};
class ITracker;
using ITrackerPtr = std::shared_ptr<ITracker>;
class ITracker {
NameAndLocation m_nameAndLocation;
public:
ITracker(NameAndLocation const& nameAndLoc) :
m_nameAndLocation(nameAndLoc)
{}
// static queries
NameAndLocation const& nameAndLocation() const {
return m_nameAndLocation;
}
virtual ~ITracker();
// dynamic queries
virtual bool isComplete() const = 0; // Successfully completed or failed
virtual bool isSuccessfullyCompleted() const = 0;
virtual bool isOpen() const = 0; // Started but not complete
virtual bool hasChildren() const = 0;
virtual bool hasStarted() const = 0;
virtual ITracker& parent() = 0;
// actions
virtual void close() = 0; // Successfully complete
virtual void fail() = 0;
virtual void markAsNeedingAnotherRun() = 0;
virtual void addChild( ITrackerPtr const& child ) = 0;
virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
virtual void openChild() = 0;
// Debug/ checking
virtual bool isSectionTracker() const = 0;
virtual bool isGeneratorTracker() const = 0;
};
class TrackerContext {
enum RunState {
NotStarted,
Executing,
CompletedCycle
};
ITrackerPtr m_rootTracker;
ITracker* m_currentTracker = nullptr;
RunState m_runState = NotStarted;
public:
ITracker& startRun();
void endRun();
void startCycle();
void completeCycle();
bool completedCycle() const;
ITracker& currentTracker();
void setCurrentTracker( ITracker* tracker );
};
class TrackerBase : public ITracker {
protected:
enum CycleState {
NotStarted,
Executing,
ExecutingChildren,
NeedsAnotherRun,
CompletedSuccessfully,
Failed
};
using Children = std::vector<ITrackerPtr>;
TrackerContext& m_ctx;
ITracker* m_parent;
Children m_children;
CycleState m_runState = NotStarted;
public:
TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
bool isComplete() const override;
bool isSuccessfullyCompleted() const override;
bool isOpen() const override;
bool hasChildren() const override;
bool hasStarted() const override {
return m_runState != NotStarted;
}
void addChild( ITrackerPtr const& child ) override;
ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
ITracker& parent() override;
void openChild() override;
bool isSectionTracker() const override;
bool isGeneratorTracker() const override;
void open();
void close() override;
void fail() override;
void markAsNeedingAnotherRun() override;
private:
void moveToParent();
void moveToThis();
};
class SectionTracker : public TrackerBase {
std::vector<std::string> m_filters;
std::string m_trimmed_name;
public:
SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
bool isSectionTracker() const override;
bool isComplete() const override;
static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
void tryOpen();
void addInitialFilters( std::vector<std::string> const& filters );
void addNextFilters( std::vector<std::string> const& filters );
//! Returns filters active in this tracker
std::vector<std::string> const& getFilters() const;
//! Returns whitespace-trimmed name of the tracked section
std::string const& trimmedName() const;
};
} // namespace TestCaseTracking
using TestCaseTracking::ITracker;
using TestCaseTracking::TrackerContext;
using TestCaseTracking::SectionTracker;
} // namespace Catch
// end catch_test_case_tracker.h
// start catch_leak_detector.h
namespace Catch {
struct LeakDetector {
LeakDetector();
~LeakDetector();
};
}
// end catch_leak_detector.h
// Cpp files will be included in the single-header file here
// start catch_stats.cpp
// Statistical analysis tools
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
#include <cassert>
#include <random>
#if defined(CATCH_CONFIG_USE_ASYNC)
#include <future>
#endif
namespace {
double erf_inv(double x) {
// Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
double w, p;
w = -log((1.0 - x) * (1.0 + x));
if (w < 6.250000) {
w = w - 3.125000;
p = -3.6444120640178196996e-21;
p = -1.685059138182016589e-19 + p * w;
p = 1.2858480715256400167e-18 + p * w;
p = 1.115787767802518096e-17 + p * w;
p = -1.333171662854620906e-16 + p * w;
p = 2.0972767875968561637e-17 + p * w;
p = 6.6376381343583238325e-15 + p * w;
p = -4.0545662729752068639e-14 + p * w;
p = -8.1519341976054721522e-14 + p * w;
p = 2.6335093153082322977e-12 + p * w;
p = -1.2975133253453532498e-11 + p * w;
p = -5.4154120542946279317e-11 + p * w;
p = 1.051212273321532285e-09 + p * w;
p = -4.1126339803469836976e-09 + p * w;
p = -2.9070369957882005086e-08 + p * w;
p = 4.2347877827932403518e-07 + p * w;
p = -1.3654692000834678645e-06 + p * w;
p = -1.3882523362786468719e-05 + p * w;
p = 0.0001867342080340571352 + p * w;
p = -0.00074070253416626697512 + p * w;
p = -0.0060336708714301490533 + p * w;
p = 0.24015818242558961693 + p * w;
p = 1.6536545626831027356 + p * w;
} else if (w < 16.000000) {
w = sqrt(w) - 3.250000;
p = 2.2137376921775787049e-09;
p = 9.0756561938885390979e-08 + p * w;
p = -2.7517406297064545428e-07 + p * w;
p = 1.8239629214389227755e-08 + p * w;
p = 1.5027403968909827627e-06 + p * w;
p = -4.013867526981545969e-06 + p * w;
p = 2.9234449089955446044e-06 + p * w;
p = 1.2475304481671778723e-05 + p * w;
p = -4.7318229009055733981e-05 + p * w;
p = 6.8284851459573175448e-05 + p * w;
p = 2.4031110387097893999e-05 + p * w;
p = -0.0003550375203628474796 + p * w;
p = 0.00095328937973738049703 + p * w;
p = -0.0016882755560235047313 + p * w;
p = 0.0024914420961078508066 + p * w;
p = -0.0037512085075692412107 + p * w;
p = 0.005370914553590063617 + p * w;
p = 1.0052589676941592334 + p * w;
p = 3.0838856104922207635 + p * w;
} else {
w = sqrt(w) - 5.000000;
p = -2.7109920616438573243e-11;
p = -2.5556418169965252055e-10 + p * w;
p = 1.5076572693500548083e-09 + p * w;
p = -3.7894654401267369937e-09 + p * w;
p = 7.6157012080783393804e-09 + p * w;
p = -1.4960026627149240478e-08 + p * w;
p = 2.9147953450901080826e-08 + p * w;
p = -6.7711997758452339498e-08 + p * w;
p = 2.2900482228026654717e-07 + p * w;
p = -9.9298272942317002539e-07 + p * w;
p = 4.5260625972231537039e-06 + p * w;
p = -1.9681778105531670567e-05 + p * w;
p = 7.5995277030017761139e-05 + p * w;
p = -0.00021503011930044477347 + p * w;
p = -0.00013871931833623122026 + p * w;
p = 1.0103004648645343977 + p * w;
p = 4.8499064014085844221 + p * w;
}
return p * x;
}
double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
auto m = Catch::Benchmark::Detail::mean(first, last);
double variance = std::accumulate(first, last, 0., [m](double a, double b) {
double diff = b - m;
return a + diff * diff;
}) / (last - first);
return std::sqrt(variance);
}
}
namespace Catch {
namespace Benchmark {
namespace Detail {
double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
auto count = last - first;
double idx = (count - 1) * k / static_cast<double>(q);
int j = static_cast<int>(idx);
double g = idx - j;
std::nth_element(first, first + j, last);
auto xj = first[j];
if (g == 0) return xj;
auto xj1 = *std::min_element(first + (j + 1), last);
return xj + g * (xj1 - xj);
}
double erfc_inv(double x) {
return erf_inv(1.0 - x);
}
double normal_quantile(double p) {
static const double ROOT_TWO = std::sqrt(2.0);
double result = 0.0;
assert(p >= 0 && p <= 1);
if (p < 0 || p > 1) {
return result;
}
result = -erfc_inv(2.0 * p);
// result *= normal distribution standard deviation (1.0) * sqrt(2)
result *= /*sd * */ ROOT_TWO;
// result += normal disttribution mean (0)
return result;
}
double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
double sb = stddev.point;
double mn = mean.point / n;
double mg_min = mn / 2.;
double sg = std::min(mg_min / 4., sb / std::sqrt(n));
double sg2 = sg * sg;
double sb2 = sb * sb;
auto c_max = [n, mn, sb2, sg2](double x) -> double {
double k = mn - x;
double d = k * k;
double nd = n * d;
double k0 = -n * nd;
double k1 = sb2 - n * sg2 + nd;
double det = k1 * k1 - 4 * sg2 * k0;
return (int)(-2. * k0 / (k1 + std::sqrt(det)));
};
auto var_out = [n, sb2, sg2](double c) {
double nc = n - c;
return (nc / n) * (sb2 - nc * sg2);
};
return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
}
bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
static std::random_device entropy;
CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
auto mean = &Detail::mean<std::vector<double>::iterator>;
auto stddev = &standard_deviation;
#if defined(CATCH_CONFIG_USE_ASYNC)
auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
auto seed = entropy();
return std::async(std::launch::async, [=] {
std::mt19937 rng(seed);
auto resampled = resample(rng, n_resamples, first, last, f);
return bootstrap(confidence_level, first, last, resampled, f);
});
};
auto mean_future = Estimate(mean);
auto stddev_future = Estimate(stddev);
auto mean_estimate = mean_future.get();
auto stddev_estimate = stddev_future.get();
#else
auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
auto seed = entropy();
std::mt19937 rng(seed);
auto resampled = resample(rng, n_resamples, first, last, f);
return bootstrap(confidence_level, first, last, resampled, f);
};
auto mean_estimate = Estimate(mean);
auto stddev_estimate = Estimate(stddev);
#endif // CATCH_USE_ASYNC
double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
return { mean_estimate, stddev_estimate, outlier_variance };
}
} // namespace Detail
} // namespace Benchmark
} // namespace Catch
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
// end catch_stats.cpp
// start catch_approx.cpp
#include <cmath>
#include <limits>
namespace {
// Performs equivalent check of std::fabs(lhs - rhs) <= margin
// But without the subtraction to allow for INFINITY in comparison
bool marginComparison(double lhs, double rhs, double margin) {
return (lhs + margin >= rhs) && (rhs + margin >= lhs);
}
}
namespace Catch {
namespace Detail {
Approx::Approx ( double value )
: m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
m_margin( 0.0 ),
m_scale( 0.0 ),
m_value( value )
{}
Approx Approx::custom() {
return Approx( 0 );
}
Approx Approx::operator-() const {
auto temp(*this);
temp.m_value = -temp.m_value;
return temp;
}
std::string Approx::toString() const {
ReusableStringStream rss;
rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
return rss.str();
}
bool Approx::equalityComparisonImpl(const double other) const {
// First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
// Thanks to Richard Harris for his help refining the scaled margin value
return marginComparison(m_value, other, m_margin)
|| marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
}
void Approx::setMargin(double newMargin) {
CATCH_ENFORCE(newMargin >= 0,
"Invalid Approx::margin: " << newMargin << '.'
<< " Approx::Margin has to be non-negative.");
m_margin = newMargin;
}
void Approx::setEpsilon(double newEpsilon) {
CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
"Invalid Approx::epsilon: " << newEpsilon << '.'
<< " Approx::epsilon has to be in [0, 1]");
m_epsilon = newEpsilon;
}
} // end namespace Detail
namespace literals {
Detail::Approx operator "" _a(long double val) {
return Detail::Approx(val);
}
Detail::Approx operator "" _a(unsigned long long val) {
return Detail::Approx(val);
}
} // end namespace literals
std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
return value.toString();
}
} // end namespace Catch
// end catch_approx.cpp
// start catch_assertionhandler.cpp
// start catch_debugger.h
namespace Catch {
bool isDebuggerActive();
}
#ifdef CATCH_PLATFORM_MAC
#if defined(__i386__) || defined(__x86_64__)
#define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
#elif defined(__aarch64__)
#define CATCH_TRAP() __asm__(".inst 0xd4200000")
#endif
#elif defined(CATCH_PLATFORM_IPHONE)
// use inline assembler
#if defined(__i386__) || defined(__x86_64__)
#define CATCH_TRAP() __asm__("int $3")
#elif defined(__aarch64__)
#define CATCH_TRAP() __asm__(".inst 0xd4200000")
#elif defined(__arm__) && !defined(__thumb__)
#define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
#elif defined(__arm__) && defined(__thumb__)
#define CATCH_TRAP() __asm__(".inst 0xde01")
#endif
#elif defined(CATCH_PLATFORM_LINUX)
// If we can use inline assembler, do it because this allows us to break
// directly at the location of the failing check instead of breaking inside
// raise() called from it, i.e. one stack frame below.
#if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
#define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
#else // Fall back to the generic way.
#include <signal.h>
#define CATCH_TRAP() raise(SIGTRAP)
#endif
#elif defined(_MSC_VER)
#define CATCH_TRAP() __debugbreak()
#elif defined(__MINGW32__)
extern "C" __declspec(dllimport) void __stdcall DebugBreak();
#define CATCH_TRAP() DebugBreak()
#endif
#ifndef CATCH_BREAK_INTO_DEBUGGER
#ifdef CATCH_TRAP
#define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
#else
#define CATCH_BREAK_INTO_DEBUGGER() []{}()
#endif
#endif
// end catch_debugger.h
// start catch_run_context.h
// start catch_fatal_condition.h
// start catch_windows_h_proxy.h
#if defined(CATCH_PLATFORM_WINDOWS)
#if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
# define CATCH_DEFINED_NOMINMAX
# define NOMINMAX
#endif
#if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
# define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#ifdef __AFXDLL
#include <AfxWin.h>
#else
#include <windows.h>
#endif
#ifdef CATCH_DEFINED_NOMINMAX
# undef NOMINMAX
#endif
#ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
# undef WIN32_LEAN_AND_MEAN
#endif
#endif // defined(CATCH_PLATFORM_WINDOWS)
// end catch_windows_h_proxy.h
#if defined( CATCH_CONFIG_WINDOWS_SEH )
namespace Catch {
struct FatalConditionHandler {
static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
FatalConditionHandler();
static void reset();
~FatalConditionHandler();
private:
static bool isSet;
static ULONG guaranteeSize;
static PVOID exceptionHandlerHandle;
};
} // namespace Catch
#elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
#include <signal.h>
namespace Catch {
struct FatalConditionHandler {
static bool isSet;
static struct sigaction oldSigActions[];
static stack_t oldSigStack;
static char altStackMem[];
static void handleSignal( int sig );
FatalConditionHandler();
~FatalConditionHandler();
static void reset();
};
} // namespace Catch
#else
namespace Catch {
struct FatalConditionHandler {
void reset();
};
}
#endif
// end catch_fatal_condition.h
#include <string>
namespace Catch {
struct IMutableContext;
///////////////////////////////////////////////////////////////////////////
class RunContext : public IResultCapture, public IRunner {
public:
RunContext( RunContext const& ) = delete;
RunContext& operator =( RunContext const& ) = delete;
explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
~RunContext() override;
void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
Totals runTest(TestCase const& testCase);
IConfigPtr config() const;
IStreamingReporter& reporter() const;
public: // IResultCapture
// Assertion handlers
void handleExpr
( AssertionInfo const& info,
ITransientExpression const& expr,
AssertionReaction& reaction ) override;
void handleMessage
( AssertionInfo const& info,
ResultWas::OfType resultType,
StringRef const& message,
AssertionReaction& reaction ) override;
void handleUnexpectedExceptionNotThrown
( AssertionInfo const& info,
AssertionReaction& reaction ) override;
void handleUnexpectedInflightException
( AssertionInfo const& info,
std::string const& message,
AssertionReaction& reaction ) override;
void handleIncomplete
( AssertionInfo const& info ) override;
void handleNonExpr
( AssertionInfo const &info,
ResultWas::OfType resultType,
AssertionReaction &reaction ) override;
bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
void sectionEnded( SectionEndInfo const& endInfo ) override;
void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
void benchmarkPreparing( std::string const& name ) override;
void benchmarkStarting( BenchmarkInfo const& info ) override;
void benchmarkEnded( BenchmarkStats<> const& stats ) override;
void benchmarkFailed( std::string const& error ) override;
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
void pushScopedMessage( MessageInfo const& message ) override;
void popScopedMessage( MessageInfo const& message ) override;
void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
std::string getCurrentTestName() const override;
const AssertionResult* getLastResult() const override;
void exceptionEarlyReported() override;
void handleFatalErrorCondition( StringRef message ) override;
bool lastAssertionPassed() override;
void assertionPassed() override;
public:
// !TBD We need to do this another way!
bool aborting() const final;
private:
void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
void invokeActiveTestCase();
void resetAssertionInfo();
bool testForMissingAssertions( Counts& assertions );
void assertionEnded( AssertionResult const& result );
void reportExpr
( AssertionInfo const &info,
ResultWas::OfType resultType,
ITransientExpression const *expr,
bool negated );
void populateReaction( AssertionReaction& reaction );
private:
void handleUnfinishedSections();
TestRunInfo m_runInfo;
IMutableContext& m_context;
TestCase const* m_activeTestCase = nullptr;
ITracker* m_testCaseTracker = nullptr;
Option<AssertionResult> m_lastResult;
IConfigPtr m_config;
Totals m_totals;
IStreamingReporterPtr m_reporter;
std::vector<MessageInfo> m_messages;
std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
AssertionInfo m_lastAssertionInfo;
std::vector<SectionEndInfo> m_unfinishedSections;
std::vector<ITracker*> m_activeSections;
TrackerContext m_trackerContext;
bool m_lastAssertionPassed = false;
bool m_shouldReportUnexpected = true;
bool m_includeSuccessfulResults;
};
void seedRng(IConfig const& config);
unsigned int rngSeed();
} // end namespace Catch
// end catch_run_context.h
namespace Catch {
namespace {
auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
expr.streamReconstructedExpression( os );
return os;
}
}
LazyExpression::LazyExpression( bool isNegated )
: m_isNegated( isNegated )
{}
LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
LazyExpression::operator bool() const {
return m_transientExpression != nullptr;
}
auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
if( lazyExpr.m_isNegated )
os << "!";
if( lazyExpr ) {
if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
os << "(" << *lazyExpr.m_transientExpression << ")";
else
os << *lazyExpr.m_transientExpression;
}
else {
os << "{** error - unchecked empty expression requested **}";
}
return os;
}
AssertionHandler::AssertionHandler
( StringRef const& macroName,
SourceLineInfo const& lineInfo,
StringRef capturedExpression,
ResultDisposition::Flags resultDisposition )
: m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
m_resultCapture( getResultCapture() )
{}
void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
}
void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
}
auto AssertionHandler::allowThrows() const -> bool {
return getCurrentContext().getConfig()->allowThrows();
}
void AssertionHandler::complete() {
setCompleted();
if( m_reaction.shouldDebugBreak ) {
// If you find your debugger stopping you here then go one level up on the
// call-stack for the code that caused it (typically a failed assertion)
// (To go back to the test and change execution, jump over the throw, next)
CATCH_BREAK_INTO_DEBUGGER();
}
if (m_reaction.shouldThrow) {
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
throw Catch::TestFailureException();
#else
CATCH_ERROR( "Test failure requires aborting test!" );
#endif
}
}
void AssertionHandler::setCompleted() {
m_completed = true;
}
void AssertionHandler::handleUnexpectedInflightException() {
m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
}
void AssertionHandler::handleExceptionThrownAsExpected() {
m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
}
void AssertionHandler::handleExceptionNotThrownAsExpected() {
m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
}
void AssertionHandler::handleUnexpectedExceptionNotThrown() {
m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
}
void AssertionHandler::handleThrowingCallSkipped() {
m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
}
// This is the overload that takes a string and infers the Equals matcher from it
// The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
}
} // namespace Catch
// end catch_assertionhandler.cpp
// start catch_assertionresult.cpp
namespace Catch {
AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
lazyExpression(_lazyExpression),
resultType(_resultType) {}
std::string AssertionResultData::reconstructExpression() const {
if( reconstructedExpression.empty() ) {
if( lazyExpression ) {
ReusableStringStream rss;
rss << lazyExpression;
reconstructedExpression = rss.str();
}
}
return reconstructedExpression;
}
AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
: m_info( info ),
m_resultData( data )
{}
// Result was a success
bool AssertionResult::succeeded() const {
return Catch::isOk( m_resultData.resultType );
}
// Result was a success, or failure is suppressed
bool AssertionResult::isOk() const {
return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
}
ResultWas::OfType AssertionResult::getResultType() const {
return m_resultData.resultType;
}
bool AssertionResult::hasExpression() const {
return !m_info.capturedExpression.empty();
}
bool AssertionResult::hasMessage() const {
return !m_resultData.message.empty();
}
std::string AssertionResult::getExpression() const {
// Possibly overallocating by 3 characters should be basically free
std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
if (isFalseTest(m_info.resultDisposition)) {
expr += "!(";
}
expr += m_info.capturedExpression;
if (isFalseTest(m_info.resultDisposition)) {
expr += ')';
}
return expr;
}
std::string AssertionResult::getExpressionInMacro() const {
std::string expr;
if( m_info.macroName.empty() )
expr = static_cast<std::string>(m_info.capturedExpression);
else {
expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
expr += m_info.macroName;
expr += "( ";
expr += m_info.capturedExpression;
expr += " )";
}
return expr;
}
bool AssertionResult::hasExpandedExpression() const {
return hasExpression() && getExpandedExpression() != getExpression();
}
std::string AssertionResult::getExpandedExpression() const {
std::string expr = m_resultData.reconstructExpression();
return expr.empty()
? getExpression()
: expr;
}
std::string AssertionResult::getMessage() const {
return m_resultData.message;
}
SourceLineInfo AssertionResult::getSourceInfo() const {
return m_info.lineInfo;
}
StringRef AssertionResult::getTestMacroName() const {
return m_info.macroName;
}
} // end namespace Catch
// end catch_assertionresult.cpp
// start catch_capture_matchers.cpp
namespace Catch {
using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
// This is the general overload that takes a any string matcher
// There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
// the Equals matcher (so the header does not mention matchers)
void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
std::string exceptionMessage = Catch::translateActiveException();
MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
handler.handleExpr( expr );
}
} // namespace Catch
// end catch_capture_matchers.cpp
// start catch_commandline.cpp
// start catch_commandline.h
// start catch_clara.h
// Use Catch's value for console width (store Clara's off to the side, if present)
#ifdef CLARA_CONFIG_CONSOLE_WIDTH
#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
#undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
#endif
#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wweak-vtables"
#pragma clang diagnostic ignored "-Wexit-time-destructors"
#pragma clang diagnostic ignored "-Wshadow"
#endif
// start clara.hpp
// Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See https://github.com/philsquared/Clara for more details
// Clara v1.1.5
#ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
#define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
#endif
#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
#endif
#ifndef CLARA_CONFIG_OPTIONAL_TYPE
#ifdef __has_include
#if __has_include(<optional>) && __cplusplus >= 201703L
#include <optional>
#define CLARA_CONFIG_OPTIONAL_TYPE std::optional
#endif
#endif
#endif
// ----------- #included from clara_textflow.hpp -----------
// TextFlowCpp
//
// A single-header library for wrapping and laying out basic text, by Phil Nash
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// This project is hosted at https://github.com/philsquared/textflowcpp
#include <cassert>
#include <ostream>
#include <sstream>
#include <vector>
#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
#endif
namespace Catch {
namespace clara {
namespace TextFlow {
inline auto isWhitespace(char c) -> bool {
static std::string chars = " \t\n\r";
return chars.find(c) != std::string::npos;
}
inline auto isBreakableBefore(char c) -> bool {
static std::string chars = "[({<|";
return chars.find(c) != std::string::npos;
}
inline auto isBreakableAfter(char c) -> bool {
static std::string chars = "])}>.,:;*+-=&/\\";
return chars.find(c) != std::string::npos;
}
class Columns;
class Column {
std::vector<std::string> m_strings;
size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
size_t m_indent = 0;
size_t m_initialIndent = std::string::npos;
public:
class iterator {
friend Column;
Column const& m_column;
size_t m_stringIndex = 0;
size_t m_pos = 0;
size_t m_len = 0;
size_t m_end = 0;
bool m_suffix = false;
iterator(Column const& column, size_t stringIndex)
: m_column(column),
m_stringIndex(stringIndex) {}
auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
auto isBoundary(size_t at) const -> bool {
assert(at > 0);
assert(at <= line().size());
return at == line().size() ||
(isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
isBreakableBefore(line()[at]) ||
isBreakableAfter(line()[at - 1]);
}
void calcLength() {
assert(m_stringIndex < m_column.m_strings.size());
m_suffix = false;
auto width = m_column.m_width - indent();
m_end = m_pos;
if (line()[m_pos] == '\n') {
++m_end;
}
while (m_end < line().size() && line()[m_end] != '\n')
++m_end;
if (m_end < m_pos + width) {
m_len = m_end - m_pos;
} else {
size_t len = width;
while (len > 0 && !isBoundary(m_pos + len))
--len;
while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
--len;
if (len > 0) {
m_len = len;
} else {
m_suffix = true;
m_len = width - 1;
}
}
}
auto indent() const -> size_t {
auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
return initial == std::string::npos ? m_column.m_indent : initial;
}
auto addIndentAndSuffix(std::string const &plain) const -> std::string {
return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
}
public:
using difference_type = std::ptrdiff_t;
using value_type = std::string;
using pointer = value_type * ;
using reference = value_type & ;
using iterator_category = std::forward_iterator_tag;
explicit iterator(Column const& column) : m_column(column) {
assert(m_column.m_width > m_column.m_indent);
assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
calcLength();
if (m_len == 0)
m_stringIndex++; // Empty string
}
auto operator *() const -> std::string {
assert(m_stringIndex < m_column.m_strings.size());
assert(m_pos <= m_end);
return addIndentAndSuffix(line().substr(m_pos, m_len));
}
auto operator ++() -> iterator& {
m_pos += m_len;
if (m_pos < line().size() && line()[m_pos] == '\n')
m_pos += 1;
else
while (m_pos < line().size() && isWhitespace(line()[m_pos]))
++m_pos;
if (m_pos == line().size()) {
m_pos = 0;
++m_stringIndex;
}
if (m_stringIndex < m_column.m_strings.size())
calcLength();
return *this;
}
auto operator ++(int) -> iterator {
iterator prev(*this);
operator++();
return prev;
}
auto operator ==(iterator const& other) const -> bool {
return
m_pos == other.m_pos &&
m_stringIndex == other.m_stringIndex &&
&m_column == &other.m_column;
}
auto operator !=(iterator const& other) const -> bool {
return !operator==(other);
}
};
using const_iterator = iterator;
explicit Column(std::string const& text) { m_strings.push_back(text); }
auto width(size_t newWidth) -> Column& {
assert(newWidth > 0);
m_width = newWidth;
return *this;
}
auto indent(size_t newIndent) -> Column& {
m_indent = newIndent;
return *this;
}
auto initialIndent(size_t newIndent) -> Column& {
m_initialIndent = newIndent;
return *this;
}
auto width() const -> size_t { return m_width; }
auto begin() const -> iterator { return iterator(*this); }
auto end() const -> iterator { return { *this, m_strings.size() }; }
inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
bool first = true;
for (auto line : col) {
if (first)
first = false;
else
os << "\n";
os << line;
}
return os;
}
auto operator + (Column const& other)->Columns;
auto toString() const -> std::string {
std::ostringstream oss;
oss << *this;
return oss.str();
}
};
class Spacer : public Column {
public:
explicit Spacer(size_t spaceWidth) : Column("") {
width(spaceWidth);
}
};
class Columns {
std::vector<Column> m_columns;
public:
class iterator {
friend Columns;
struct EndTag {};
std::vector<Column> const& m_columns;
std::vector<Column::iterator> m_iterators;
size_t m_activeIterators;
iterator(Columns const& columns, EndTag)
: m_columns(columns.m_columns),
m_activeIterators(0) {
m_iterators.reserve(m_columns.size());
for (auto const& col : m_columns)
m_iterators.push_back(col.end());
}
public:
using difference_type = std::ptrdiff_t;
using value_type = std::string;
using pointer = value_type * ;
using reference = value_type & ;
using iterator_category = std::forward_iterator_tag;
explicit iterator(Columns const& columns)
: m_columns(columns.m_columns),
m_activeIterators(m_columns.size()) {
m_iterators.reserve(m_columns.size());
for (auto const& col : m_columns)
m_iterators.push_back(col.begin());
}
auto operator ==(iterator const& other) const -> bool {
return m_iterators == other.m_iterators;
}
auto operator !=(iterator const& other) const -> bool {
return m_iterators != other.m_iterators;
}
auto operator *() const -> std::string {
std::string row, padding;
for (size_t i = 0; i < m_columns.size(); ++i) {
auto width = m_columns[i].width();
if (m_iterators[i] != m_columns[i].end()) {
std::string col = *m_iterators[i];
row += padding + col;
if (col.size() < width)
padding = std::string(width - col.size(), ' ');
else
padding = "";
} else {
padding += std::string(width, ' ');
}
}
return row;
}
auto operator ++() -> iterator& {
for (size_t i = 0; i < m_columns.size(); ++i) {
if (m_iterators[i] != m_columns[i].end())
++m_iterators[i];
}
return *this;
}
auto operator ++(int) -> iterator {
iterator prev(*this);
operator++();
return prev;
}
};
using const_iterator = iterator;
auto begin() const -> iterator { return iterator(*this); }
auto end() const -> iterator { return { *this, iterator::EndTag() }; }
auto operator += (Column const& col) -> Columns& {
m_columns.push_back(col);
return *this;
}
auto operator + (Column const& col) -> Columns {
Columns combined = *this;
combined += col;
return combined;
}
inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
bool first = true;
for (auto line : cols) {
if (first)
first = false;
else
os << "\n";
os << line;
}
return os;
}
auto toString() const -> std::string {
std::ostringstream oss;
oss << *this;
return oss.str();
}
};
inline auto Column::operator + (Column const& other) -> Columns {
Columns cols;
cols += *this;
cols += other;
return cols;
}
}
}
}
// ----------- end of #include from clara_textflow.hpp -----------
// ........... back in clara.hpp
#include <cctype>
#include <string>
#include <memory>
#include <set>
#include <algorithm>
#if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
#define CATCH_PLATFORM_WINDOWS
#endif
namespace Catch { namespace clara {
namespace detail {
// Traits for extracting arg and return type of lambdas (for single argument lambdas)
template<typename L>
struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
template<typename ClassT, typename ReturnT, typename... Args>
struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
static const bool isValid = false;
};
template<typename ClassT, typename ReturnT, typename ArgT>
struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
static const bool isValid = true;
using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
using ReturnType = ReturnT;
};
class TokenStream;
// Transport for raw args (copied from main args, or supplied via init list for testing)
class Args {
friend TokenStream;
std::string m_exeName;
std::vector<std::string> m_args;
public:
Args( int argc, char const* const* argv )
: m_exeName(argv[0]),
m_args(argv + 1, argv + argc) {}
Args( std::initializer_list<std::string> args )
: m_exeName( *args.begin() ),
m_args( args.begin()+1, args.end() )
{}
auto exeName() const -> std::string {
return m_exeName;
}
};
// Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
// may encode an option + its argument if the : or = form is used
enum class TokenType {
Option, Argument
};
struct Token {
TokenType type;
std::string token;
};
inline auto isOptPrefix( char c ) -> bool {
return c == '-'
#ifdef CATCH_PLATFORM_WINDOWS
|| c == '/'
#endif
;
}
// Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
class TokenStream {
using Iterator = std::vector<std::string>::const_iterator;
Iterator it;
Iterator itEnd;
std::vector<Token> m_tokenBuffer;
void loadBuffer() {
m_tokenBuffer.resize( 0 );
// Skip any empty strings
while( it != itEnd && it->empty() )
++it;
if( it != itEnd ) {
auto const &next = *it;
if( isOptPrefix( next[0] ) ) {
auto delimiterPos = next.find_first_of( " :=" );
if( delimiterPos != std::string::npos ) {
m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
} else {
if( next[1] != '-' && next.size() > 2 ) {
std::string opt = "- ";
for( size_t i = 1; i < next.size(); ++i ) {
opt[1] = next[i];
m_tokenBuffer.push_back( { TokenType::Option, opt } );
}
} else {
m_tokenBuffer.push_back( { TokenType::Option, next } );
}
}
} else {
m_tokenBuffer.push_back( { TokenType::Argument, next } );
}
}
}
public:
explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
loadBuffer();
}
explicit operator bool() const {
return !m_tokenBuffer.empty() || it != itEnd;
}
auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
auto operator*() const -> Token {
assert( !m_tokenBuffer.empty() );
return m_tokenBuffer.front();
}
auto operator->() const -> Token const * {
assert( !m_tokenBuffer.empty() );
return &m_tokenBuffer.front();
}
auto operator++() -> TokenStream & {
if( m_tokenBuffer.size() >= 2 ) {
m_tokenBuffer.erase( m_tokenBuffer.begin() );
} else {
if( it != itEnd )
++it;
loadBuffer();
}
return *this;
}
};
class ResultBase {
public:
enum Type {
Ok, LogicError, RuntimeError
};
protected:
ResultBase( Type type ) : m_type( type ) {}
virtual ~ResultBase() = default;
virtual void enforceOk() const = 0;
Type m_type;
};
template<typename T>
class ResultValueBase : public ResultBase {
public:
auto value() const -> T const & {
enforceOk();
return m_value;
}
protected:
ResultValueBase( Type type ) : ResultBase( type ) {}
ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
if( m_type == ResultBase::Ok )
new( &m_value ) T( other.m_value );
}
ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
new( &m_value ) T( value );
}
auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
if( m_type == ResultBase::Ok )
m_value.~T();
ResultBase::operator=(other);
if( m_type == ResultBase::Ok )
new( &m_value ) T( other.m_value );
return *this;
}
~ResultValueBase() override {
if( m_type == Ok )
m_value.~T();
}
union {
T m_value;
};
};
template<>
class ResultValueBase<void> : public ResultBase {
protected:
using ResultBase::ResultBase;
};
template<typename T = void>
class BasicResult : public ResultValueBase<T> {
public:
template<typename U>
explicit BasicResult( BasicResult<U> const &other )
: ResultValueBase<T>( other.type() ),
m_errorMessage( other.errorMessage() )
{
assert( type() != ResultBase::Ok );
}
template<typename U>
static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
static auto ok() -> BasicResult { return { ResultBase::Ok }; }
static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
explicit operator bool() const { return m_type == ResultBase::Ok; }
auto type() const -> ResultBase::Type { return m_type; }
auto errorMessage() const -> std::string { return m_errorMessage; }
protected:
void enforceOk() const override {
// Errors shouldn't reach this point, but if they do
// the actual error message will be in m_errorMessage
assert( m_type != ResultBase::LogicError );
assert( m_type != ResultBase::RuntimeError );
if( m_type != ResultBase::Ok )
std::abort();
}
std::string m_errorMessage; // Only populated if resultType is an error
BasicResult( ResultBase::Type type, std::string const &message )
: ResultValueBase<T>(type),
m_errorMessage(message)
{
assert( m_type != ResultBase::Ok );
}
using ResultValueBase<T>::ResultValueBase;
using ResultBase::m_type;
};
enum class ParseResultType {
Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
};
class ParseState {
public:
ParseState( ParseResultType type, TokenStream const &remainingTokens )
: m_type(type),
m_remainingTokens( remainingTokens )
{}
auto type() const -> ParseResultType { return m_type; }
auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
private:
ParseResultType m_type;
TokenStream m_remainingTokens;
};
using Result = BasicResult<void>;
using ParserResult = BasicResult<ParseResultType>;
using InternalParseResult = BasicResult<ParseState>;
struct HelpColumns {
std::string left;
std::string right;
};
template<typename T>
inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
std::stringstream ss;
ss << source;
ss >> target;
if( ss.fail() )
return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
else
return ParserResult::ok( ParseResultType::Matched );
}
inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
target = source;
return ParserResult::ok( ParseResultType::Matched );
}
inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
std::string srcLC = source;
std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
target = true;
else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
target = false;
else
return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
return ParserResult::ok( ParseResultType::Matched );
}
#ifdef CLARA_CONFIG_OPTIONAL_TYPE
template<typename T>
inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
T temp;
auto result = convertInto( source, temp );
if( result )
target = std::move(temp);
return result;
}
#endif // CLARA_CONFIG_OPTIONAL_TYPE
struct NonCopyable {
NonCopyable() = default;
NonCopyable( NonCopyable const & ) = delete;
NonCopyable( NonCopyable && ) = delete;
NonCopyable &operator=( NonCopyable const & ) = delete;
NonCopyable &operator=( NonCopyable && ) = delete;
};
struct BoundRef : NonCopyable {
virtual ~BoundRef() = default;
virtual auto isContainer() const -> bool { return false; }
virtual auto isFlag() const -> bool { return false; }
};
struct BoundValueRefBase : BoundRef {
virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
};
struct BoundFlagRefBase : BoundRef {
virtual auto setFlag( bool flag ) -> ParserResult = 0;
virtual auto isFlag() const -> bool { return true; }
};
template<typename T>
struct BoundValueRef : BoundValueRefBase {
T &m_ref;
explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
auto setValue( std::string const &arg ) -> ParserResult override {
return convertInto( arg, m_ref );
}
};
template<typename T>
struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
std::vector<T> &m_ref;
explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
auto isContainer() const -> bool override { return true; }
auto setValue( std::string const &arg ) -> ParserResult override {
T temp;
auto result = convertInto( arg, temp );
if( result )
m_ref.push_back( temp );
return result;
}
};
struct BoundFlagRef : BoundFlagRefBase {
bool &m_ref;
explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
auto setFlag( bool flag ) -> ParserResult override {
m_ref = flag;
return ParserResult::ok( ParseResultType::Matched );
}
};
template<typename ReturnType>
struct LambdaInvoker {
static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
template<typename L, typename ArgType>
static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
return lambda( arg );
}
};
template<>
struct LambdaInvoker<void> {
template<typename L, typename ArgType>
static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
lambda( arg );
return ParserResult::ok( ParseResultType::Matched );
}
};
template<typename ArgType, typename L>
inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
ArgType temp{};
auto result = convertInto( arg, temp );
return !result
? result
: LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
}
template<typename L>
struct BoundLambda : BoundValueRefBase {
L m_lambda;
static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
auto setValue( std::string const &arg ) -> ParserResult override {
return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
}
};
template<typename L>
struct BoundFlagLambda : BoundFlagRefBase {
L m_lambda;
static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
auto setFlag( bool flag ) -> ParserResult override {
return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
}
};
enum class Optionality { Optional, Required };
struct Parser;
class ParserBase {
public:
virtual ~ParserBase() = default;
virtual auto validate() const -> Result { return Result::ok(); }
virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
virtual auto cardinality() const -> size_t { return 1; }
auto parse( Args const &args ) const -> InternalParseResult {
return parse( args.exeName(), TokenStream( args ) );
}
};
template<typename DerivedT>
class ComposableParserImpl : public ParserBase {
public:
template<typename T>
auto operator|( T const &other ) const -> Parser;
template<typename T>
auto operator+( T const &other ) const -> Parser;
};
// Common code and state for Args and Opts
template<typename DerivedT>
class ParserRefImpl : public ComposableParserImpl<DerivedT> {
protected:
Optionality m_optionality = Optionality::Optional;
std::shared_ptr<BoundRef> m_ref;
std::string m_hint;
std::string m_description;
explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
public:
template<typename T>
ParserRefImpl( T &ref, std::string const &hint )
: m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
m_hint( hint )
{}
template<typename LambdaT>
ParserRefImpl( LambdaT const &ref, std::string const &hint )
: m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
m_hint(hint)
{}
auto operator()( std::string const &description ) -> DerivedT & {
m_description = description;
return static_cast<DerivedT &>( *this );
}
auto optional() -> DerivedT & {
m_optionality = Optionality::Optional;
return static_cast<DerivedT &>( *this );
};
auto required() -> DerivedT & {
m_optionality = Optionality::Required;
return static_cast<DerivedT &>( *this );
};
auto isOptional() const -> bool {
return m_optionality == Optionality::Optional;
}
auto cardinality() const -> size_t override {
if( m_ref->isContainer() )
return 0;
else
return 1;
}
auto hint() const -> std::string { return m_hint; }
};
class ExeName : public ComposableParserImpl<ExeName> {
std::shared_ptr<std::string> m_name;
std::shared_ptr<BoundValueRefBase> m_ref;
template<typename LambdaT>
static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
}
public:
ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
explicit ExeName( std::string &ref ) : ExeName() {
m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
}
template<typename LambdaT>
explicit ExeName( LambdaT const& lambda ) : ExeName() {
m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
}
// The exe name is not parsed out of the normal tokens, but is handled specially
auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
}
auto name() const -> std::string { return *m_name; }
auto set( std::string const& newName ) -> ParserResult {
auto lastSlash = newName.find_last_of( "\\/" );
auto filename = ( lastSlash == std::string::npos )
? newName
: newName.substr( lastSlash+1 );
*m_name = filename;
if( m_ref )
return m_ref->setValue( filename );
else
return ParserResult::ok( ParseResultType::Matched );
}
};
class Arg : public ParserRefImpl<Arg> {
public:
using ParserRefImpl::ParserRefImpl;
auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
auto validationResult = validate();
if( !validationResult )
return InternalParseResult( validationResult );
auto remainingTokens = tokens;
auto const &token = *remainingTokens;
if( token.type != TokenType::Argument )
return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
assert( !m_ref->isFlag() );
auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
auto result = valueRef->setValue( remainingTokens->token );
if( !result )
return InternalParseResult( result );
else
return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
}
};
inline auto normaliseOpt( std::string const &optName ) -> std::string {
#ifdef CATCH_PLATFORM_WINDOWS
if( optName[0] == '/' )
return "-" + optName.substr( 1 );
else
#endif
return optName;
}
class Opt : public ParserRefImpl<Opt> {
protected:
std::vector<std::string> m_optNames;
public:
template<typename LambdaT>
explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
template<typename LambdaT>
Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
template<typename T>
Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
auto operator[]( std::string const &optName ) -> Opt & {
m_optNames.push_back( optName );
return *this;
}
auto getHelpColumns() const -> std::vector<HelpColumns> {
std::ostringstream oss;
bool first = true;
for( auto const &opt : m_optNames ) {
if (first)
first = false;
else
oss << ", ";
oss << opt;
}
if( !m_hint.empty() )
oss << " <" << m_hint << ">";
return { { oss.str(), m_description } };
}
auto isMatch( std::string const &optToken ) const -> bool {
auto normalisedToken = normaliseOpt( optToken );
for( auto const &name : m_optNames ) {
if( normaliseOpt( name ) == normalisedToken )
return true;
}
return false;
}
using ParserBase::parse;
auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
auto validationResult = validate();
if( !validationResult )
return InternalParseResult( validationResult );
auto remainingTokens = tokens;
if( remainingTokens && remainingTokens->type == TokenType::Option ) {
auto const &token = *remainingTokens;
if( isMatch(token.token ) ) {
if( m_ref->isFlag() ) {
auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
auto result = flagRef->setFlag( true );
if( !result )
return InternalParseResult( result );
if( result.value() == ParseResultType::ShortCircuitAll )
return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
} else {
auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
++remainingTokens;
if( !remainingTokens )
return InternalParseResult::runtimeError( "Expected argument following " + token.token );
auto const &argToken = *remainingTokens;
if( argToken.type != TokenType::Argument )
return InternalParseResult::runtimeError( "Expected argument following " + token.token );
auto result = valueRef->setValue( argToken.token );
if( !result )
return InternalParseResult( result );
if( result.value() == ParseResultType::ShortCircuitAll )
return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
}
return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
}
}
return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
}
auto validate() const -> Result override {
if( m_optNames.empty() )
return Result::logicError( "No options supplied to Opt" );
for( auto const &name : m_optNames ) {
if( name.empty() )
return Result::logicError( "Option name cannot be empty" );
#ifdef CATCH_PLATFORM_WINDOWS
if( name[0] != '-' && name[0] != '/' )
return Result::logicError( "Option name must begin with '-' or '/'" );
#else
if( name[0] != '-' )
return Result::logicError( "Option name must begin with '-'" );
#endif
}
return ParserRefImpl::validate();
}
};
struct Help : Opt {
Help( bool &showHelpFlag )
: Opt([&]( bool flag ) {
showHelpFlag = flag;
return ParserResult::ok( ParseResultType::ShortCircuitAll );
})
{
static_cast<Opt &>( *this )
("display usage information")
["-?"]["-h"]["--help"]
.optional();
}
};
struct Parser : ParserBase {
mutable ExeName m_exeName;
std::vector<Opt> m_options;
std::vector<Arg> m_args;
auto operator|=( ExeName const &exeName ) -> Parser & {
m_exeName = exeName;
return *this;
}
auto operator|=( Arg const &arg ) -> Parser & {
m_args.push_back(arg);
return *this;
}
auto operator|=( Opt const &opt ) -> Parser & {
m_options.push_back(opt);
return *this;
}
auto operator|=( Parser const &other ) -> Parser & {
m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
return *this;
}
template<typename T>
auto operator|( T const &other ) const -> Parser {
return Parser( *this ) |= other;
}
// Forward deprecated interface with '+' instead of '|'
template<typename T>
auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
template<typename T>
auto operator+( T const &other ) const -> Parser { return operator|( other ); }
auto getHelpColumns() const -> std::vector<HelpColumns> {
std::vector<HelpColumns> cols;
for (auto const &o : m_options) {
auto childCols = o.getHelpColumns();
cols.insert( cols.end(), childCols.begin(), childCols.end() );
}
return cols;
}
void writeToStream( std::ostream &os ) const {
if (!m_exeName.name().empty()) {
os << "usage:\n" << " " << m_exeName.name() << " ";
bool required = true, first = true;
for( auto const &arg : m_args ) {
if (first)
first = false;
else
os << " ";
if( arg.isOptional() && required ) {
os << "[";
required = false;
}
os << "<" << arg.hint() << ">";
if( arg.cardinality() == 0 )
os << " ... ";
}
if( !required )
os << "]";
if( !m_options.empty() )
os << " options";
os << "\n\nwhere options are:" << std::endl;
}
auto rows = getHelpColumns();
size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
size_t optWidth = 0;
for( auto const &cols : rows )
optWidth = (std::max)(optWidth, cols.left.size() + 2);
optWidth = (std::min)(optWidth, consoleWidth/2);
for( auto const &cols : rows ) {
auto row =
TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
TextFlow::Spacer(4) +
TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
os << row << std::endl;
}
}
friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
parser.writeToStream( os );
return os;
}
auto validate() const -> Result override {
for( auto const &opt : m_options ) {
auto result = opt.validate();
if( !result )
return result;
}
for( auto const &arg : m_args ) {
auto result = arg.validate();
if( !result )
return result;
}
return Result::ok();
}
using ParserBase::parse;
auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
struct ParserInfo {
ParserBase const* parser = nullptr;
size_t count = 0;
};
const size_t totalParsers = m_options.size() + m_args.size();
assert( totalParsers < 512 );
// ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
ParserInfo parseInfos[512];
{
size_t i = 0;
for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
}
m_exeName.set( exeName );
auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
while( result.value().remainingTokens() ) {
bool tokenParsed = false;
for( size_t i = 0; i < totalParsers; ++i ) {
auto& parseInfo = parseInfos[i];
if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
if (!result)
return result;
if (result.value().type() != ParseResultType::NoMatch) {
tokenParsed = true;
++parseInfo.count;
break;
}
}
}
if( result.value().type() == ParseResultType::ShortCircuitAll )
return result;
if( !tokenParsed )
return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
}
// !TBD Check missing required options
return result;
}
};
template<typename DerivedT>
template<typename T>
auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
return Parser() | static_cast<DerivedT const &>( *this ) | other;
}
} // namespace detail
// A Combined parser
using detail::Parser;
// A parser for options
using detail::Opt;
// A parser for arguments
using detail::Arg;
// Wrapper for argc, argv from main()
using detail::Args;
// Specifies the name of the executable
using detail::ExeName;
// Convenience wrapper for option parser that specifies the help option
using detail::Help;
// enum of result types from a parse
using detail::ParseResultType;
// Result type for parser operation
using detail::ParserResult;
}} // namespace Catch::clara
// end clara.hpp
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Restore Clara's value for console width, if present
#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
#endif
// end catch_clara.h
namespace Catch {
clara::Parser makeCommandLineParser( ConfigData& config );
} // end namespace Catch
// end catch_commandline.h
#include <fstream>
#include <ctime>
namespace Catch {
clara::Parser makeCommandLineParser( ConfigData& config ) {
using namespace clara;
auto const setWarning = [&]( std::string const& warning ) {
auto warningSet = [&]() {
if( warning == "NoAssertions" )
return WarnAbout::NoAssertions;
if ( warning == "NoTests" )
return WarnAbout::NoTests;
return WarnAbout::Nothing;
}();
if (warningSet == WarnAbout::Nothing)
return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
return ParserResult::ok( ParseResultType::Matched );
};
auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
std::ifstream f( filename.c_str() );
if( !f.is_open() )
return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
std::string line;
while( std::getline( f, line ) ) {
line = trim(line);
if( !line.empty() && !startsWith( line, '#' ) ) {
if( !startsWith( line, '"' ) )
line = '"' + line + '"';
config.testsOrTags.push_back( line );
config.testsOrTags.emplace_back( "," );
}
}
//Remove comma in the end
if(!config.testsOrTags.empty())
config.testsOrTags.erase( config.testsOrTags.end()-1 );
return ParserResult::ok( ParseResultType::Matched );
};
auto const setTestOrder = [&]( std::string const& order ) {
if( startsWith( "declared", order ) )
config.runOrder = RunTests::InDeclarationOrder;
else if( startsWith( "lexical", order ) )
config.runOrder = RunTests::InLexicographicalOrder;
else if( startsWith( "random", order ) )
config.runOrder = RunTests::InRandomOrder;
else
return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
return ParserResult::ok( ParseResultType::Matched );
};
auto const setRngSeed = [&]( std::string const& seed ) {
if( seed != "time" )
return clara::detail::convertInto( seed, config.rngSeed );
config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
return ParserResult::ok( ParseResultType::Matched );
};
auto const setColourUsage = [&]( std::string const& useColour ) {
auto mode = toLower( useColour );
if( mode == "yes" )
config.useColour = UseColour::Yes;
else if( mode == "no" )
config.useColour = UseColour::No;
else if( mode == "auto" )
config.useColour = UseColour::Auto;
else
return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
return ParserResult::ok( ParseResultType::Matched );
};
auto const setWaitForKeypress = [&]( std::string const& keypress ) {
auto keypressLc = toLower( keypress );
if (keypressLc == "never")
config.waitForKeypress = WaitForKeypress::Never;
else if( keypressLc == "start" )
config.waitForKeypress = WaitForKeypress::BeforeStart;
else if( keypressLc == "exit" )
config.waitForKeypress = WaitForKeypress::BeforeExit;
else if( keypressLc == "both" )
config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
else
return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
return ParserResult::ok( ParseResultType::Matched );
};
auto const setVerbosity = [&]( std::string const& verbosity ) {
auto lcVerbosity = toLower( verbosity );
if( lcVerbosity == "quiet" )
config.verbosity = Verbosity::Quiet;
else if( lcVerbosity == "normal" )
config.verbosity = Verbosity::Normal;
else if( lcVerbosity == "high" )
config.verbosity = Verbosity::High;
else
return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
return ParserResult::ok( ParseResultType::Matched );
};
auto const setReporter = [&]( std::string const& reporter ) {
IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
auto lcReporter = toLower( reporter );
auto result = factories.find( lcReporter );
if( factories.end() != result )
config.reporterName = lcReporter;
else
return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
return ParserResult::ok( ParseResultType::Matched );
};
auto cli
= ExeName( config.processName )
| Help( config.showHelp )
| Opt( config.listTests )
["-l"]["--list-tests"]
( "list all/matching test cases" )
| Opt( config.listTags )
["-t"]["--list-tags"]
( "list all/matching tags" )
| Opt( config.showSuccessfulTests )
["-s"]["--success"]
( "include successful tests in output" )
| Opt( config.shouldDebugBreak )
["-b"]["--break"]
( "break into debugger on failure" )
| Opt( config.noThrow )
["-e"]["--nothrow"]
( "skip exception tests" )
| Opt( config.showInvisibles )
["-i"]["--invisibles"]
( "show invisibles (tabs, newlines)" )
| Opt( config.outputFilename, "filename" )
["-o"]["--out"]
( "output filename" )
| Opt( setReporter, "name" )
["-r"]["--reporter"]
( "reporter to use (defaults to console)" )
| Opt( config.name, "name" )
["-n"]["--name"]
( "suite name" )
| Opt( [&]( bool ){ config.abortAfter = 1; } )
["-a"]["--abort"]
( "abort at first failure" )
| Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
["-x"]["--abortx"]
( "abort after x failures" )
| Opt( setWarning, "warning name" )
["-w"]["--warn"]
( "enable warnings" )
| Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
["-d"]["--durations"]
( "show test durations" )
| Opt( config.minDuration, "seconds" )
["-D"]["--min-duration"]
( "show test durations for tests taking at least the given number of seconds" )
| Opt( loadTestNamesFromFile, "filename" )
["-f"]["--input-file"]
( "load test names to run from a file" )
| Opt( config.filenamesAsTags )
["-#"]["--filenames-as-tags"]
( "adds a tag for the filename" )
| Opt( config.sectionsToRun, "section name" )
["-c"]["--section"]
( "specify section to run" )
| Opt( setVerbosity, "quiet|normal|high" )
["-v"]["--verbosity"]
( "set output verbosity" )
| Opt( config.listTestNamesOnly )
["--list-test-names-only"]
( "list all/matching test cases names only" )
| Opt( config.listReporters )
["--list-reporters"]
( "list all reporters" )
| Opt( setTestOrder, "decl|lex|rand" )
["--order"]
( "test case order (defaults to decl)" )
| Opt( setRngSeed, "'time'|number" )
["--rng-seed"]
( "set a specific seed for random numbers" )
| Opt( setColourUsage, "yes|no" )
["--use-colour"]
( "should output be colourised" )
| Opt( config.libIdentify )
["--libidentify"]
( "report name and version according to libidentify standard" )
| Opt( setWaitForKeypress, "never|start|exit|both" )
["--wait-for-keypress"]
( "waits for a keypress before exiting" )
| Opt( config.benchmarkSamples, "samples" )
["--benchmark-samples"]
( "number of samples to collect (default: 100)" )
| Opt( config.benchmarkResamples, "resamples" )
["--benchmark-resamples"]
( "number of resamples for the bootstrap (default: 100000)" )
| Opt( config.benchmarkConfidenceInterval, "confidence interval" )
["--benchmark-confidence-interval"]
( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
| Opt( config.benchmarkNoAnalysis )
["--benchmark-no-analysis"]
( "perform only measurements; do not perform any analysis" )
| Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
["--benchmark-warmup-time"]
( "amount of time in milliseconds spent on warming up each test (default: 100)" )
| Arg( config.testsOrTags, "test name|pattern|tags" )
( "which test or tests to use" );
return cli;
}
} // end namespace Catch
// end catch_commandline.cpp
// start catch_common.cpp
#include <cstring>
#include <ostream>
namespace Catch {
bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
}
bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
// We can assume that the same file will usually have the same pointer.
// Thus, if the pointers are the same, there is no point in calling the strcmp
return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
}
std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
#ifndef __GNUG__
os << info.file << '(' << info.line << ')';
#else
os << info.file << ':' << info.line;
#endif
return os;
}
std::string StreamEndStop::operator+() const {
return std::string();
}
NonCopyable::NonCopyable() = default;
NonCopyable::~NonCopyable() = default;
}
// end catch_common.cpp
// start catch_config.cpp
namespace Catch {
Config::Config( ConfigData const& data )
: m_data( data ),
m_stream( openStream() )
{
// We need to trim filter specs to avoid trouble with superfluous
// whitespace (esp. important for bdd macros, as those are manually
// aligned with whitespace).
for (auto& elem : m_data.testsOrTags) {
elem = trim(elem);
}
for (auto& elem : m_data.sectionsToRun) {
elem = trim(elem);
}
TestSpecParser parser(ITagAliasRegistry::get());
if (!m_data.testsOrTags.empty()) {
m_hasTestFilters = true;
for (auto const& testOrTags : m_data.testsOrTags) {
parser.parse(testOrTags);
}
}
m_testSpec = parser.testSpec();
}
std::string const& Config::getFilename() const {
return m_data.outputFilename ;
}
bool Config::listTests() const { return m_data.listTests; }
bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
bool Config::listTags() const { return m_data.listTags; }
bool Config::listReporters() const { return m_data.listReporters; }
std::string Config::getProcessName() const { return m_data.processName; }
std::string const& Config::getReporterName() const { return m_data.reporterName; }
std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
TestSpec const& Config::testSpec() const { return m_testSpec; }
bool Config::hasTestFilters() const { return m_hasTestFilters; }
bool Config::showHelp() const { return m_data.showHelp; }
// IConfig interface
bool Config::allowThrows() const { return !m_data.noThrow; }
std::ostream& Config::stream() const { return m_stream->stream(); }
std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
double Config::minDuration() const { return m_data.minDuration; }
RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
unsigned int Config::rngSeed() const { return m_data.rngSeed; }
UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
int Config::abortAfter() const { return m_data.abortAfter; }
bool Config::showInvisibles() const { return m_data.showInvisibles; }
Verbosity Config::verbosity() const { return m_data.verbosity; }
bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
IStream const* Config::openStream() {
return Catch::makeStream(m_data.outputFilename);
}
} // end namespace Catch
// end catch_config.cpp
// start catch_console_colour.cpp
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wexit-time-destructors"
#endif
// start catch_errno_guard.h
namespace Catch {
class ErrnoGuard {
public:
ErrnoGuard();
~ErrnoGuard();
private:
int m_oldErrno;
};
}
// end catch_errno_guard.h
#include <sstream>
namespace Catch {
namespace {
struct IColourImpl {
virtual ~IColourImpl() = default;
virtual void use( Colour::Code _colourCode ) = 0;
};
struct NoColourImpl : IColourImpl {
void use( Colour::Code ) override {}
static IColourImpl* instance() {
static NoColourImpl s_instance;
return &s_instance;
}
};
} // anon namespace
} // namespace Catch
#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
# ifdef CATCH_PLATFORM_WINDOWS
# define CATCH_CONFIG_COLOUR_WINDOWS
# else
# define CATCH_CONFIG_COLOUR_ANSI
# endif
#endif
#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
namespace Catch {
namespace {
class Win32ColourImpl : public IColourImpl {
public:
Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
{
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
}
void use( Colour::Code _colourCode ) override {
switch( _colourCode ) {
case Colour::None: return setTextAttribute( originalForegroundAttributes );
case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
case Colour::Red: return setTextAttribute( FOREGROUND_RED );
case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
case Colour::Grey: return setTextAttribute( 0 );
case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
default:
CATCH_ERROR( "Unknown colour requested" );
}
}
private:
void setTextAttribute( WORD _textAttribute ) {
SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
}
HANDLE stdoutHandle;
WORD originalForegroundAttributes;
WORD originalBackgroundAttributes;
};
IColourImpl* platformColourInstance() {
static Win32ColourImpl s_instance;
IConfigPtr config = getCurrentContext().getConfig();
UseColour::YesOrNo colourMode = config
? config->useColour()
: UseColour::Auto;
if( colourMode == UseColour::Auto )
colourMode = UseColour::Yes;
return colourMode == UseColour::Yes
? &s_instance
: NoColourImpl::instance();
}
} // end anon namespace
} // end namespace Catch
#elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
#include <unistd.h>
namespace Catch {
namespace {
// use POSIX/ ANSI console terminal codes
// Thanks to Adam Strzelecki for original contribution
// (http://github.com/nanoant)
// https://github.com/philsquared/Catch/pull/131
class PosixColourImpl : public IColourImpl {
public:
void use( Colour::Code _colourCode ) override {
switch( _colourCode ) {
case Colour::None:
case Colour::White: return setColour( "[0m" );
case Colour::Red: return setColour( "[0;31m" );
case Colour::Green: return setColour( "[0;32m" );
case Colour::Blue: return setColour( "[0;34m" );
case Colour::Cyan: return setColour( "[0;36m" );
case Colour::Yellow: return setColour( "[0;33m" );
case Colour::Grey: return setColour( "[1;30m" );
case Colour::LightGrey: return setColour( "[0;37m" );
case Colour::BrightRed: return setColour( "[1;31m" );
case Colour::BrightGreen: return setColour( "[1;32m" );
case Colour::BrightWhite: return setColour( "[1;37m" );
case Colour::BrightYellow: return setColour( "[1;33m" );
case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
}
}
static IColourImpl* instance() {
static PosixColourImpl s_instance;
return &s_instance;
}
private:
void setColour( const char* _escapeCode ) {
getCurrentContext().getConfig()->stream()
<< '\033' << _escapeCode;
}
};
bool useColourOnPlatform() {
return
#if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
!isDebuggerActive() &&
#endif
#if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
isatty(STDOUT_FILENO)
#else
false
#endif
;
}
IColourImpl* platformColourInstance() {
ErrnoGuard guard;
IConfigPtr config = getCurrentContext().getConfig();
UseColour::YesOrNo colourMode = config
? config->useColour()
: UseColour::Auto;
if( colourMode == UseColour::Auto )
colourMode = useColourOnPlatform()
? UseColour::Yes
: UseColour::No;
return colourMode == UseColour::Yes
? PosixColourImpl::instance()
: NoColourImpl::instance();
}
} // end anon namespace
} // end namespace Catch
#else // not Windows or ANSI ///////////////////////////////////////////////
namespace Catch {
static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
} // end namespace Catch
#endif // Windows/ ANSI/ None
namespace Catch {
Colour::Colour( Code _colourCode ) { use( _colourCode ); }
Colour::Colour( Colour&& other ) noexcept {
m_moved = other.m_moved;
other.m_moved = true;
}
Colour& Colour::operator=( Colour&& other ) noexcept {
m_moved = other.m_moved;
other.m_moved = true;
return *this;
}
Colour::~Colour(){ if( !m_moved ) use( None ); }
void Colour::use( Code _colourCode ) {
static IColourImpl* impl = platformColourInstance();
// Strictly speaking, this cannot possibly happen.
// However, under some conditions it does happen (see #1626),
// and this change is small enough that we can let practicality
// triumph over purity in this case.
if (impl != nullptr) {
impl->use( _colourCode );
}
}
std::ostream& operator << ( std::ostream& os, Colour const& ) {
return os;
}
} // end namespace Catch
#if defined(__clang__)
# pragma clang diagnostic pop
#endif
// end catch_console_colour.cpp
// start catch_context.cpp
namespace Catch {
class Context : public IMutableContext, NonCopyable {
public: // IContext
IResultCapture* getResultCapture() override {
return m_resultCapture;
}
IRunner* getRunner() override {
return m_runner;
}
IConfigPtr const& getConfig() const override {
return m_config;
}
~Context() override;
public: // IMutableContext
void setResultCapture( IResultCapture* resultCapture ) override {
m_resultCapture = resultCapture;
}
void setRunner( IRunner* runner ) override {
m_runner = runner;
}
void setConfig( IConfigPtr const& config ) override {
m_config = config;
}
friend IMutableContext& getCurrentMutableContext();
private:
IConfigPtr m_config;
IRunner* m_runner = nullptr;
IResultCapture* m_resultCapture = nullptr;
};
IMutableContext *IMutableContext::currentContext = nullptr;
void IMutableContext::createContext()
{
currentContext = new Context();
}
void cleanUpContext() {
delete IMutableContext::currentContext;
IMutableContext::currentContext = nullptr;
}
IContext::~IContext() = default;
IMutableContext::~IMutableContext() = default;
Context::~Context() = default;
SimplePcg32& rng() {
static SimplePcg32 s_rng;
return s_rng;
}
}
// end catch_context.cpp
// start catch_debug_console.cpp
// start catch_debug_console.h
#include <string>
namespace Catch {
void writeToDebugConsole( std::string const& text );
}
// end catch_debug_console.h
#if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
#include <android/log.h>
namespace Catch {
void writeToDebugConsole( std::string const& text ) {
__android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
}
}
#elif defined(CATCH_PLATFORM_WINDOWS)
namespace Catch {
void writeToDebugConsole( std::string const& text ) {
::OutputDebugStringA( text.c_str() );
}
}
#else
namespace Catch {
void writeToDebugConsole( std::string const& text ) {
// !TBD: Need a version for Mac/ XCode and other IDEs
Catch::cout() << text;
}
}
#endif // Platform
// end catch_debug_console.cpp
// start catch_debugger.cpp
#if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
# include <cassert>
# include <sys/types.h>
# include <unistd.h>
# include <cstddef>
# include <ostream>
#ifdef __apple_build_version__
// These headers will only compile with AppleClang (XCode)
// For other compilers (Clang, GCC, ... ) we need to exclude them
# include <sys/sysctl.h>
#endif
namespace Catch {
#ifdef __apple_build_version__
// The following function is taken directly from the following technical note:
// https://developer.apple.com/library/archive/qa/qa1361/_index.html
// Returns true if the current process is being debugged (either
// running under the debugger or has a debugger attached post facto).
bool isDebuggerActive(){
int mib[4];
struct kinfo_proc info;
std::size_t size;
// Initialize the flags so that, if sysctl fails for some bizarre
// reason, we get a predictable result.
info.kp_proc.p_flag = 0;
// Initialize mib, which tells sysctl the info we want, in this case
// we're looking for information about a specific process ID.
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = getpid();
// Call sysctl.
size = sizeof(info);
if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
return false;
}
// We're being debugged if the P_TRACED flag is set.
return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
}
#else
bool isDebuggerActive() {
// We need to find another way to determine this for non-appleclang compilers on macOS
return false;
}
#endif
} // namespace Catch
#elif defined(CATCH_PLATFORM_LINUX)
#include <fstream>
#include <string>
namespace Catch{
// The standard POSIX way of detecting a debugger is to attempt to
// ptrace() the process, but this needs to be done from a child and not
// this process itself to still allow attaching to this process later
// if wanted, so is rather heavy. Under Linux we have the PID of the
// "debugger" (which doesn't need to be gdb, of course, it could also
// be strace, for example) in /proc/$PID/status, so just get it from
// there instead.
bool isDebuggerActive(){
// Libstdc++ has a bug, where std::ifstream sets errno to 0
// This way our users can properly assert over errno values
ErrnoGuard guard;
std::ifstream in("/proc/self/status");
for( std::string line; std::getline(in, line); ) {
static const int PREFIX_LEN = 11;
if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
// We're traced if the PID is not 0 and no other PID starts
// with 0 digit, so it's enough to check for just a single
// character.
return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
}
}
return false;
}
} // namespace Catch
#elif defined(_MSC_VER)
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
namespace Catch {
bool isDebuggerActive() {
return IsDebuggerPresent() != 0;
}
}
#elif defined(__MINGW32__)
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
namespace Catch {
bool isDebuggerActive() {
return IsDebuggerPresent() != 0;
}
}
#else
namespace Catch {
bool isDebuggerActive() { return false; }
}
#endif // Platform
// end catch_debugger.cpp
// start catch_decomposer.cpp
namespace Catch {
ITransientExpression::~ITransientExpression() = default;
void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
if( lhs.size() + rhs.size() < 40 &&
lhs.find('\n') == std::string::npos &&
rhs.find('\n') == std::string::npos )
os << lhs << " " << op << " " << rhs;
else
os << lhs << "\n" << op << "\n" << rhs;
}
}
// end catch_decomposer.cpp
// start catch_enforce.cpp
#include <stdexcept>
namespace Catch {
#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
[[noreturn]]
void throw_exception(std::exception const& e) {
Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
<< "The message was: " << e.what() << '\n';
std::terminate();
}
#endif
[[noreturn]]
void throw_logic_error(std::string const& msg) {
throw_exception(std::logic_error(msg));
}
[[noreturn]]
void throw_domain_error(std::string const& msg) {
throw_exception(std::domain_error(msg));
}
[[noreturn]]
void throw_runtime_error(std::string const& msg) {
throw_exception(std::runtime_error(msg));
}
} // namespace Catch;
// end catch_enforce.cpp
// start catch_enum_values_registry.cpp
// start catch_enum_values_registry.h
#include <vector>
#include <memory>
namespace Catch {
namespace Detail {
std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
class EnumValuesRegistry : public IMutableEnumValuesRegistry {
std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
};
std::vector<StringRef> parseEnums( StringRef enums );
} // Detail
} // Catch
// end catch_enum_values_registry.h
#include <map>
#include <cassert>
namespace Catch {
IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
namespace Detail {
namespace {
// Extracts the actual name part of an enum instance
// In other words, it returns the Blue part of Bikeshed::Colour::Blue
StringRef extractInstanceName(StringRef enumInstance) {
// Find last occurence of ":"
size_t name_start = enumInstance.size();
while (name_start > 0 && enumInstance[name_start - 1] != ':') {
--name_start;
}
return enumInstance.substr(name_start, enumInstance.size() - name_start);
}
}
std::vector<StringRef> parseEnums( StringRef enums ) {
auto enumValues = splitStringRef( enums, ',' );
std::vector<StringRef> parsed;
parsed.reserve( enumValues.size() );
for( auto const& enumValue : enumValues ) {
parsed.push_back(trim(extractInstanceName(enumValue)));
}
return parsed;
}
EnumInfo::~EnumInfo() {}
StringRef EnumInfo::lookup( int value ) const {
for( auto const& valueToName : m_values ) {
if( valueToName.first == value )
return valueToName.second;
}
return "{** unexpected enum value **}"_sr;
}
std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
enumInfo->m_name = enumName;
enumInfo->m_values.reserve( values.size() );
const auto valueNames = Catch::Detail::parseEnums( allValueNames );
assert( valueNames.size() == values.size() );
std::size_t i = 0;
for( auto value : values )
enumInfo->m_values.emplace_back(value, valueNames[i++]);
return enumInfo;
}
EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
return *m_enumInfos.back();
}
} // Detail
} // Catch
// end catch_enum_values_registry.cpp
// start catch_errno_guard.cpp
#include <cerrno>
namespace Catch {
ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
}
// end catch_errno_guard.cpp
// start catch_exception_translator_registry.cpp
// start catch_exception_translator_registry.h
#include <vector>
#include <string>
#include <memory>
namespace Catch {
class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
public:
~ExceptionTranslatorRegistry();
virtual void registerTranslator( const IExceptionTranslator* translator );
std::string translateActiveException() const override;
std::string tryTranslators() const;
private:
std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
};
}
// end catch_exception_translator_registry.h
#ifdef __OBJC__
#import "Foundation/Foundation.h"
#endif
namespace Catch {
ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
}
void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
}
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
std::string ExceptionTranslatorRegistry::translateActiveException() const {
try {
#ifdef __OBJC__
// In Objective-C try objective-c exceptions first
@try {
return tryTranslators();
}
@catch (NSException *exception) {
return Catch::Detail::stringify( [exception description] );
}
#else
// Compiling a mixed mode project with MSVC means that CLR
// exceptions will be caught in (...) as well. However, these
// do not fill-in std::current_exception and thus lead to crash
// when attempting rethrow.
// /EHa switch also causes structured exceptions to be caught
// here, but they fill-in current_exception properly, so
// at worst the output should be a little weird, instead of
// causing a crash.
if (std::current_exception() == nullptr) {
return "Non C++ exception. Possibly a CLR exception.";
}
return tryTranslators();
#endif
}
catch( TestFailureException& ) {
std::rethrow_exception(std::current_exception());
}
catch( std::exception& ex ) {
return ex.what();
}
catch( std::string& msg ) {
return msg;
}
catch( const char* msg ) {
return msg;
}
catch(...) {
return "Unknown exception";
}
}
std::string ExceptionTranslatorRegistry::tryTranslators() const {
if (m_translators.empty()) {
std::rethrow_exception(std::current_exception());
} else {
return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
}
}
#else // ^^ Exceptions are enabled // Exceptions are disabled vv
std::string ExceptionTranslatorRegistry::translateActiveException() const {
CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
}
std::string ExceptionTranslatorRegistry::tryTranslators() const {
CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
}
#endif
}
// end catch_exception_translator_registry.cpp
// start catch_fatal_condition.cpp
#if defined(__GNUC__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif
#if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
namespace {
// Report the error condition
void reportFatal( char const * const message ) {
Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
}
}
#endif // signals/SEH handling
#if defined( CATCH_CONFIG_WINDOWS_SEH )
namespace Catch {
struct SignalDefs { DWORD id; const char* name; };
// There is no 1-1 mapping between signals and windows exceptions.
// Windows can easily distinguish between SO and SigSegV,
// but SigInt, SigTerm, etc are handled differently.
static SignalDefs signalDefs[] = {
{ static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
{ static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
{ static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
{ static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
};
LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
for (auto const& def : signalDefs) {
if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
reportFatal(def.name);
}
}
// If its not an exception we care about, pass it along.
// This stops us from eating debugger breaks etc.
return EXCEPTION_CONTINUE_SEARCH;
}
FatalConditionHandler::FatalConditionHandler() {
isSet = true;
// 32k seems enough for Catch to handle stack overflow,
// but the value was found experimentally, so there is no strong guarantee
guaranteeSize = 32 * 1024;
exceptionHandlerHandle = nullptr;
// Register as first handler in current chain
exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
// Pass in guarantee size to be filled
SetThreadStackGuarantee(&guaranteeSize);
}
void FatalConditionHandler::reset() {
if (isSet) {
RemoveVectoredExceptionHandler(exceptionHandlerHandle);
SetThreadStackGuarantee(&guaranteeSize);
exceptionHandlerHandle = nullptr;
isSet = false;
}
}
FatalConditionHandler::~FatalConditionHandler() {
reset();
}
bool FatalConditionHandler::isSet = false;
ULONG FatalConditionHandler::guaranteeSize = 0;
PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
} // namespace Catch
#elif defined( CATCH_CONFIG_POSIX_SIGNALS )
namespace Catch {
struct SignalDefs {
int id;
const char* name;
};
// 32kb for the alternate stack seems to be sufficient. However, this value
// is experimentally determined, so that's not guaranteed.
static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
static SignalDefs signalDefs[] = {
{ SIGINT, "SIGINT - Terminal interrupt signal" },
{ SIGILL, "SIGILL - Illegal instruction signal" },
{ SIGFPE, "SIGFPE - Floating point error signal" },
{ SIGSEGV, "SIGSEGV - Segmentation violation signal" },
{ SIGTERM, "SIGTERM - Termination request signal" },
{ SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
};
void FatalConditionHandler::handleSignal( int sig ) {
char const * name = "<unknown signal>";
for (auto const& def : signalDefs) {
if (sig == def.id) {
name = def.name;
break;
}
}
reset();
reportFatal(name);
raise( sig );
}
FatalConditionHandler::FatalConditionHandler() {
isSet = true;
stack_t sigStack;
sigStack.ss_sp = altStackMem;
sigStack.ss_size = sigStackSize;
sigStack.ss_flags = 0;
sigaltstack(&sigStack, &oldSigStack);
struct sigaction sa = { };
sa.sa_handler = handleSignal;
sa.sa_flags = SA_ONSTACK;
for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
}
}
FatalConditionHandler::~FatalConditionHandler() {
reset();
}
void FatalConditionHandler::reset() {
if( isSet ) {
// Set signals back to previous values -- hopefully nobody overwrote them in the meantime
for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
}
// Return the old stack
sigaltstack(&oldSigStack, nullptr);
isSet = false;
}
}
bool FatalConditionHandler::isSet = false;
struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
stack_t FatalConditionHandler::oldSigStack = {};
char FatalConditionHandler::altStackMem[sigStackSize] = {};
} // namespace Catch
#else
namespace Catch {
void FatalConditionHandler::reset() {}
}
#endif // signals/SEH handling
#if defined(__GNUC__)
# pragma GCC diagnostic pop
#endif
// end catch_fatal_condition.cpp
// start catch_generators.cpp
#include <limits>
#include <set>
namespace Catch {
IGeneratorTracker::~IGeneratorTracker() {}
const char* GeneratorException::what() const noexcept {
return m_msg;
}
namespace Generators {
GeneratorUntypedBase::~GeneratorUntypedBase() {}
auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
}
} // namespace Generators
} // namespace Catch
// end catch_generators.cpp
// start catch_interfaces_capture.cpp
namespace Catch {
IResultCapture::~IResultCapture() = default;
}
// end catch_interfaces_capture.cpp
// start catch_interfaces_config.cpp
namespace Catch {
IConfig::~IConfig() = default;
}
// end catch_interfaces_config.cpp
// start catch_interfaces_exception.cpp
namespace Catch {
IExceptionTranslator::~IExceptionTranslator() = default;
IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
}
// end catch_interfaces_exception.cpp
// start catch_interfaces_registry_hub.cpp
namespace Catch {
IRegistryHub::~IRegistryHub() = default;
IMutableRegistryHub::~IMutableRegistryHub() = default;
}
// end catch_interfaces_registry_hub.cpp
// start catch_interfaces_reporter.cpp
// start catch_reporter_listening.h
namespace Catch {
class ListeningReporter : public IStreamingReporter {
using Reporters = std::vector<IStreamingReporterPtr>;
Reporters m_listeners;
IStreamingReporterPtr m_reporter = nullptr;
ReporterPreferences m_preferences;
public:
ListeningReporter();
void addListener( IStreamingReporterPtr&& listener );
void addReporter( IStreamingReporterPtr&& reporter );
public: // IStreamingReporter
ReporterPreferences getPreferences() const override;
void noMatchingTestCases( std::string const& spec ) override;
void reportInvalidArguments(std::string const&arg) override;
static std::set<Verbosity> getSupportedVerbosities();
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
void benchmarkPreparing(std::string const& name) override;
void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
void benchmarkFailed(std::string const&) override;
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
void testRunStarting( TestRunInfo const& testRunInfo ) override;
void testGroupStarting( GroupInfo const& groupInfo ) override;
void testCaseStarting( TestCaseInfo const& testInfo ) override;
void sectionStarting( SectionInfo const& sectionInfo ) override;
void assertionStarting( AssertionInfo const& assertionInfo ) override;
// The return value indicates if the messages buffer should be cleared:
bool assertionEnded( AssertionStats const& assertionStats ) override;
void sectionEnded( SectionStats const& sectionStats ) override;
void testCaseEnded( TestCaseStats const& testCaseStats ) override;
void testGroupEnded( TestGroupStats const& testGroupStats ) override;
void testRunEnded( TestRunStats const& testRunStats ) override;
void skipTest( TestCaseInfo const& testInfo ) override;
bool isMulti() const override;
};
} // end namespace Catch
// end catch_reporter_listening.h
namespace Catch {
ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
: m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
: m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
std::ostream& ReporterConfig::stream() const { return *m_stream; }
IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
GroupInfo::GroupInfo( std::string const& _name,
std::size_t _groupIndex,
std::size_t _groupsCount )
: name( _name ),
groupIndex( _groupIndex ),
groupsCounts( _groupsCount )
{}
AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
std::vector<MessageInfo> const& _infoMessages,
Totals const& _totals )
: assertionResult( _assertionResult ),
infoMessages( _infoMessages ),
totals( _totals )
{
assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
if( assertionResult.hasMessage() ) {
// Copy message into messages list.
// !TBD This should have been done earlier, somewhere
MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
builder << assertionResult.getMessage();
builder.m_info.message = builder.m_stream.str();
infoMessages.push_back( builder.m_info );
}
}
AssertionStats::~AssertionStats() = default;
SectionStats::SectionStats( SectionInfo const& _sectionInfo,
Counts const& _assertions,
double _durationInSeconds,
bool _missingAssertions )
: sectionInfo( _sectionInfo ),
assertions( _assertions ),
durationInSeconds( _durationInSeconds ),
missingAssertions( _missingAssertions )
{}
SectionStats::~SectionStats() = default;
TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
Totals const& _totals,
std::string const& _stdOut,
std::string const& _stdErr,
bool _aborting )
: testInfo( _testInfo ),
totals( _totals ),
stdOut( _stdOut ),
stdErr( _stdErr ),
aborting( _aborting )
{}
TestCaseStats::~TestCaseStats() = default;
TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
Totals const& _totals,
bool _aborting )
: groupInfo( _groupInfo ),
totals( _totals ),
aborting( _aborting )
{}
TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
: groupInfo( _groupInfo ),
aborting( false )
{}
TestGroupStats::~TestGroupStats() = default;
TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
Totals const& _totals,
bool _aborting )
: runInfo( _runInfo ),
totals( _totals ),
aborting( _aborting )
{}
TestRunStats::~TestRunStats() = default;
void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
bool IStreamingReporter::isMulti() const { return false; }
IReporterFactory::~IReporterFactory() = default;
IReporterRegistry::~IReporterRegistry() = default;
} // end namespace Catch
// end catch_interfaces_reporter.cpp
// start catch_interfaces_runner.cpp
namespace Catch {
IRunner::~IRunner() = default;
}
// end catch_interfaces_runner.cpp
// start catch_interfaces_testcase.cpp
namespace Catch {
ITestInvoker::~ITestInvoker() = default;
ITestCaseRegistry::~ITestCaseRegistry() = default;
}
// end catch_interfaces_testcase.cpp
// start catch_leak_detector.cpp
#ifdef CATCH_CONFIG_WINDOWS_CRTDBG
#include <crtdbg.h>
namespace Catch {
LeakDetector::LeakDetector() {
int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
flag |= _CRTDBG_LEAK_CHECK_DF;
flag |= _CRTDBG_ALLOC_MEM_DF;
_CrtSetDbgFlag(flag);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
// Change this to leaking allocation's number to break there
_CrtSetBreakAlloc(-1);
}
}
#else
Catch::LeakDetector::LeakDetector() {}
#endif
Catch::LeakDetector::~LeakDetector() {
Catch::cleanUp();
}
// end catch_leak_detector.cpp
// start catch_list.cpp
// start catch_list.h
#include <set>
namespace Catch {
std::size_t listTests( Config const& config );
std::size_t listTestsNamesOnly( Config const& config );
struct TagInfo {
void add( std::string const& spelling );
std::string all() const;
std::set<std::string> spellings;
std::size_t count = 0;
};
std::size_t listTags( Config const& config );
std::size_t listReporters();
Option<std::size_t> list( std::shared_ptr<Config> const& config );
} // end namespace Catch
// end catch_list.h
// start catch_text.h
namespace Catch {
using namespace clara::TextFlow;
}
// end catch_text.h
#include <limits>
#include <algorithm>
#include <iomanip>
namespace Catch {
std::size_t listTests( Config const& config ) {
TestSpec const& testSpec = config.testSpec();
if( config.hasTestFilters() )
Catch::cout() << "Matching test cases:\n";
else {
Catch::cout() << "All available test cases:\n";
}
auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
for( auto const& testCaseInfo : matchedTestCases ) {
Colour::Code colour = testCaseInfo.isHidden()
? Colour::SecondaryText
: Colour::None;
Colour colourGuard( colour );
Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
if( config.verbosity() >= Verbosity::High ) {
Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
std::string description = testCaseInfo.description;
if( description.empty() )
description = "(NO DESCRIPTION)";
Catch::cout() << Column( description ).indent(4) << std::endl;
}
if( !testCaseInfo.tags.empty() )
Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
}
if( !config.hasTestFilters() )
Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
else
Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
return matchedTestCases.size();
}
std::size_t listTestsNamesOnly( Config const& config ) {
TestSpec const& testSpec = config.testSpec();
std::size_t matchedTests = 0;
std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
for( auto const& testCaseInfo : matchedTestCases ) {
matchedTests++;
if( startsWith( testCaseInfo.name, '#' ) )
Catch::cout() << '"' << testCaseInfo.name << '"';
else
Catch::cout() << testCaseInfo.name;
if ( config.verbosity() >= Verbosity::High )
Catch::cout() << "\t@" << testCaseInfo.lineInfo;
Catch::cout() << std::endl;
}
return matchedTests;
}
void TagInfo::add( std::string const& spelling ) {
++count;
spellings.insert( spelling );
}
std::string TagInfo::all() const {
size_t size = 0;
for (auto const& spelling : spellings) {
// Add 2 for the brackes
size += spelling.size() + 2;
}
std::string out; out.reserve(size);
for (auto const& spelling : spellings) {
out += '[';
out += spelling;
out += ']';
}
return out;
}
std::size_t listTags( Config const& config ) {
TestSpec const& testSpec = config.testSpec();
if( config.hasTestFilters() )
Catch::cout() << "Tags for matching test cases:\n";
else {
Catch::cout() << "All available tags:\n";
}
std::map<std::string, TagInfo> tagCounts;
std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
for( auto const& testCase : matchedTestCases ) {
for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
std::string lcaseTagName = toLower( tagName );
auto countIt = tagCounts.find( lcaseTagName );
if( countIt == tagCounts.end() )
countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
countIt->second.add( tagName );
}
}
for( auto const& tagCount : tagCounts ) {
ReusableStringStream rss;
rss << " " << std::setw(2) << tagCount.second.count << " ";
auto str = rss.str();
auto wrapper = Column( tagCount.second.all() )
.initialIndent( 0 )
.indent( str.size() )
.width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
Catch::cout() << str << wrapper << '\n';
}
Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
return tagCounts.size();
}
std::size_t listReporters() {
Catch::cout() << "Available reporters:\n";
IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
std::size_t maxNameLen = 0;
for( auto const& factoryKvp : factories )
maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
for( auto const& factoryKvp : factories ) {
Catch::cout()
<< Column( factoryKvp.first + ":" )
.indent(2)
.width( 5+maxNameLen )
+ Column( factoryKvp.second->getDescription() )
.initialIndent(0)
.indent(2)
.width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
<< "\n";
}
Catch::cout() << std::endl;
return factories.size();
}
Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
Option<std::size_t> listedCount;
getCurrentMutableContext().setConfig( config );
if( config->listTests() )
listedCount = listedCount.valueOr(0) + listTests( *config );
if( config->listTestNamesOnly() )
listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
if( config->listTags() )
listedCount = listedCount.valueOr(0) + listTags( *config );
if( config->listReporters() )
listedCount = listedCount.valueOr(0) + listReporters();
return listedCount;
}
} // end namespace Catch
// end catch_list.cpp
// start catch_matchers.cpp
namespace Catch {
namespace Matchers {
namespace Impl {
std::string MatcherUntypedBase::toString() const {
if( m_cachedToString.empty() )
m_cachedToString = describe();
return m_cachedToString;
}
MatcherUntypedBase::~MatcherUntypedBase() = default;
} // namespace Impl
} // namespace Matchers
using namespace Matchers;
using Matchers::Impl::MatcherBase;
} // namespace Catch
// end catch_matchers.cpp
// start catch_matchers_exception.cpp
namespace Catch {
namespace Matchers {
namespace Exception {
bool ExceptionMessageMatcher::match(std::exception const& ex) const {
return ex.what() == m_message;
}
std::string ExceptionMessageMatcher::describe() const {
return "exception message matches \"" + m_message + "\"";
}
}
Exception::ExceptionMessageMatcher Message(std::string const& message) {
return Exception::ExceptionMessageMatcher(message);
}
// namespace Exception
} // namespace Matchers
} // namespace Catch
// end catch_matchers_exception.cpp
// start catch_matchers_floating.cpp
// start catch_polyfills.hpp
namespace Catch {
bool isnan(float f);
bool isnan(double d);
}
// end catch_polyfills.hpp
// start catch_to_string.hpp
#include <string>
namespace Catch {
template <typename T>
std::string to_string(T const& t) {
#if defined(CATCH_CONFIG_CPP11_TO_STRING)
return std::to_string(t);
#else
ReusableStringStream rss;
rss << t;
return rss.str();
#endif
}
} // end namespace Catch
// end catch_to_string.hpp
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <sstream>
#include <type_traits>
#include <iomanip>
#include <limits>
namespace Catch {
namespace {
int32_t convert(float f) {
static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
int32_t i;
std::memcpy(&i, &f, sizeof(f));
return i;
}
int64_t convert(double d) {
static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
int64_t i;
std::memcpy(&i, &d, sizeof(d));
return i;
}
template <typename FP>
bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
// Comparison with NaN should always be false.
// This way we can rule it out before getting into the ugly details
if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
return false;
}
auto lc = convert(lhs);
auto rc = convert(rhs);
if ((lc < 0) != (rc < 0)) {
// Potentially we can have +0 and -0
return lhs == rhs;
}
auto ulpDiff = std::abs(lc - rc);
return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
}
#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
float nextafter(float x, float y) {
return ::nextafterf(x, y);
}
double nextafter(double x, double y) {
return ::nextafter(x, y);
}
#endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
template <typename FP>
FP step(FP start, FP direction, uint64_t steps) {
for (uint64_t i = 0; i < steps; ++i) {
#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
start = Catch::nextafter(start, direction);
#else
start = std::nextafter(start, direction);
#endif
}
return start;
}
// Performs equivalent check of std::fabs(lhs - rhs) <= margin
// But without the subtraction to allow for INFINITY in comparison
bool marginComparison(double lhs, double rhs, double margin) {
return (lhs + margin >= rhs) && (rhs + margin >= lhs);
}
template <typename FloatingPoint>
void write(std::ostream& out, FloatingPoint num) {
out << std::scientific
<< std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
<< num;
}
} // end anonymous namespace
namespace Matchers {
namespace Floating {
enum class FloatingPointKind : uint8_t {
Float,
Double
};
WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
:m_target{ target }, m_margin{ margin } {
CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
<< " Margin has to be non-negative.");
}
// Performs equivalent check of std::fabs(lhs - rhs) <= margin
// But without the subtraction to allow for INFINITY in comparison
bool WithinAbsMatcher::match(double const& matchee) const {
return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
}
std::string WithinAbsMatcher::describe() const {
return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
}
WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
:m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
CATCH_ENFORCE(m_type == FloatingPointKind::Double
|| m_ulps < (std::numeric_limits<uint32_t>::max)(),
"Provided ULP is impossibly large for a float comparison.");
}
#if defined(__clang__)
#pragma clang diagnostic push
// Clang <3.5 reports on the default branch in the switch below
#pragma clang diagnostic ignored "-Wunreachable-code"
#endif
bool WithinUlpsMatcher::match(double const& matchee) const {
switch (m_type) {
case FloatingPointKind::Float:
return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
case FloatingPointKind::Double:
return almostEqualUlps<double>(matchee, m_target, m_ulps);
default:
CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
}
}
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
std::string WithinUlpsMatcher::describe() const {
std::stringstream ret;
ret << "is within " << m_ulps << " ULPs of ";
if (m_type == FloatingPointKind::Float) {
write(ret, static_cast<float>(m_target));
ret << 'f';
} else {
write(ret, m_target);
}
ret << " ([";
if (m_type == FloatingPointKind::Double) {
write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
ret << ", ";
write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
} else {
// We have to cast INFINITY to float because of MinGW, see #1782
write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
ret << ", ";
write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
}
ret << "])";
return ret.str();
}
WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
m_target(target),
m_epsilon(epsilon){
CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
}
bool WithinRelMatcher::match(double const& matchee) const {
const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
return marginComparison(matchee, m_target,
std::isinf(relMargin)? 0 : relMargin);
}
std::string WithinRelMatcher::describe() const {
Catch::ReusableStringStream sstr;
sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
return sstr.str();
}
}// namespace Floating
Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
}
Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
}
Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
return Floating::WithinAbsMatcher(target, margin);
}
Floating::WithinRelMatcher WithinRel(double target, double eps) {
return Floating::WithinRelMatcher(target, eps);
}
Floating::WithinRelMatcher WithinRel(double target) {
return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
}
Floating::WithinRelMatcher WithinRel(float target, float eps) {
return Floating::WithinRelMatcher(target, eps);
}
Floating::WithinRelMatcher WithinRel(float target) {
return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
}
} // namespace Matchers
} // namespace Catch
// end catch_matchers_floating.cpp
// start catch_matchers_generic.cpp
std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
if (desc.empty()) {
return "matches undescribed predicate";
} else {
return "matches predicate: \"" + desc + '"';
}
}
// end catch_matchers_generic.cpp
// start catch_matchers_string.cpp
#include <regex>
namespace Catch {
namespace Matchers {
namespace StdString {
CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
: m_caseSensitivity( caseSensitivity ),
m_str( adjustString( str ) )
{}
std::string CasedString::adjustString( std::string const& str ) const {
return m_caseSensitivity == CaseSensitive::No
? toLower( str )
: str;
}
std::string CasedString::caseSensitivitySuffix() const {
return m_caseSensitivity == CaseSensitive::No
? " (case insensitive)"
: std::string();
}
StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
: m_comparator( comparator ),
m_operation( operation ) {
}
std::string StringMatcherBase::describe() const {
std::string description;
description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
m_comparator.caseSensitivitySuffix().size());
description += m_operation;
description += ": \"";
description += m_comparator.m_str;
description += "\"";
description += m_comparator.caseSensitivitySuffix();
return description;
}
EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
bool EqualsMatcher::match( std::string const& source ) const {
return m_comparator.adjustString( source ) == m_comparator.m_str;
}
ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
bool ContainsMatcher::match( std::string const& source ) const {
return contains( m_comparator.adjustString( source ), m_comparator.m_str );
}
StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
bool StartsWithMatcher::match( std::string const& source ) const {
return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
}
EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
bool EndsWithMatcher::match( std::string const& source ) const {
return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
}
RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
bool RegexMatcher::match(std::string const& matchee) const {
auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
if (m_caseSensitivity == CaseSensitive::Choice::No) {
flags |= std::regex::icase;
}
auto reg = std::regex(m_regex, flags);
return std::regex_match(matchee, reg);
}
std::string RegexMatcher::describe() const {
return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
}
} // namespace StdString
StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
}
StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
}
StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
}
StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
}
StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
return StdString::RegexMatcher(regex, caseSensitivity);
}
} // namespace Matchers
} // namespace Catch
// end catch_matchers_string.cpp
// start catch_message.cpp
// start catch_uncaught_exceptions.h
namespace Catch {
bool uncaught_exceptions();
} // end namespace Catch
// end catch_uncaught_exceptions.h
#include <cassert>
#include <stack>
namespace Catch {
MessageInfo::MessageInfo( StringRef const& _macroName,
SourceLineInfo const& _lineInfo,
ResultWas::OfType _type )
: macroName( _macroName ),
lineInfo( _lineInfo ),
type( _type ),
sequence( ++globalCount )
{}
bool MessageInfo::operator==( MessageInfo const& other ) const {
return sequence == other.sequence;
}
bool MessageInfo::operator<( MessageInfo const& other ) const {
return sequence < other.sequence;
}
// This may need protecting if threading support is added
unsigned int MessageInfo::globalCount = 0;
////////////////////////////////////////////////////////////////////////////
Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
SourceLineInfo const& lineInfo,
ResultWas::OfType type )
:m_info(macroName, lineInfo, type) {}
////////////////////////////////////////////////////////////////////////////
ScopedMessage::ScopedMessage( MessageBuilder const& builder )
: m_info( builder.m_info ), m_moved()
{
m_info.message = builder.m_stream.str();
getResultCapture().pushScopedMessage( m_info );
}
ScopedMessage::ScopedMessage( ScopedMessage&& old )
: m_info( old.m_info ), m_moved()
{
old.m_moved = true;
}
ScopedMessage::~ScopedMessage() {
if ( !uncaught_exceptions() && !m_moved ){
getResultCapture().popScopedMessage(m_info);
}
}
Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
auto trimmed = [&] (size_t start, size_t end) {
while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
++start;
}
while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
--end;
}
return names.substr(start, end - start + 1);
};
auto skipq = [&] (size_t start, char quote) {
for (auto i = start + 1; i < names.size() ; ++i) {
if (names[i] == quote)
return i;
if (names[i] == '\\')
++i;
}
CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
};
size_t start = 0;
std::stack<char> openings;
for (size_t pos = 0; pos < names.size(); ++pos) {
char c = names[pos];
switch (c) {
case '[':
case '{':
case '(':
// It is basically impossible to disambiguate between
// comparison and start of template args in this context
// case '<':
openings.push(c);
break;
case ']':
case '}':
case ')':
// case '>':
openings.pop();
break;
case '"':
case '\'':
pos = skipq(pos, c);
break;
case ',':
if (start != pos && openings.empty()) {
m_messages.emplace_back(macroName, lineInfo, resultType);
m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
m_messages.back().message += " := ";
start = pos;
}
}
}
assert(openings.empty() && "Mismatched openings");
m_messages.emplace_back(macroName, lineInfo, resultType);
m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
m_messages.back().message += " := ";
}
Capturer::~Capturer() {
if ( !uncaught_exceptions() ){
assert( m_captured == m_messages.size() );
for( size_t i = 0; i < m_captured; ++i )
m_resultCapture.popScopedMessage( m_messages[i] );
}
}
void Capturer::captureValue( size_t index, std::string const& value ) {
assert( index < m_messages.size() );
m_messages[index].message += value;
m_resultCapture.pushScopedMessage( m_messages[index] );
m_captured++;
}
} // end namespace Catch
// end catch_message.cpp
// start catch_output_redirect.cpp
// start catch_output_redirect.h
#ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
#define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
#include <cstdio>
#include <iosfwd>
#include <string>
namespace Catch {
class RedirectedStream {
std::ostream& m_originalStream;
std::ostream& m_redirectionStream;
std::streambuf* m_prevBuf;
public:
RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
~RedirectedStream();
};
class RedirectedStdOut {
ReusableStringStream m_rss;
RedirectedStream m_cout;
public:
RedirectedStdOut();
auto str() const -> std::string;
};
// StdErr has two constituent streams in C++, std::cerr and std::clog
// This means that we need to redirect 2 streams into 1 to keep proper
// order of writes
class RedirectedStdErr {
ReusableStringStream m_rss;
RedirectedStream m_cerr;
RedirectedStream m_clog;
public:
RedirectedStdErr();
auto str() const -> std::string;
};
class RedirectedStreams {
public:
RedirectedStreams(RedirectedStreams const&) = delete;
RedirectedStreams& operator=(RedirectedStreams const&) = delete;
RedirectedStreams(RedirectedStreams&&) = delete;
RedirectedStreams& operator=(RedirectedStreams&&) = delete;
RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
~RedirectedStreams();
private:
std::string& m_redirectedCout;
std::string& m_redirectedCerr;
RedirectedStdOut m_redirectedStdOut;
RedirectedStdErr m_redirectedStdErr;
};
#if defined(CATCH_CONFIG_NEW_CAPTURE)
// Windows's implementation of std::tmpfile is terrible (it tries
// to create a file inside system folder, thus requiring elevated
// privileges for the binary), so we have to use tmpnam(_s) and
// create the file ourselves there.
class TempFile {
public:
TempFile(TempFile const&) = delete;
TempFile& operator=(TempFile const&) = delete;
TempFile(TempFile&&) = delete;
TempFile& operator=(TempFile&&) = delete;
TempFile();
~TempFile();
std::FILE* getFile();
std::string getContents();
private:
std::FILE* m_file = nullptr;
#if defined(_MSC_VER)
char m_buffer[L_tmpnam] = { 0 };
#endif
};
class OutputRedirect {
public:
OutputRedirect(OutputRedirect const&) = delete;
OutputRedirect& operator=(OutputRedirect const&) = delete;
OutputRedirect(OutputRedirect&&) = delete;
OutputRedirect& operator=(OutputRedirect&&) = delete;
OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
~OutputRedirect();
private:
int m_originalStdout = -1;
int m_originalStderr = -1;
TempFile m_stdoutFile;
TempFile m_stderrFile;
std::string& m_stdoutDest;
std::string& m_stderrDest;
};
#endif
} // end namespace Catch
#endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
// end catch_output_redirect.h
#include <cstdio>
#include <cstring>
#include <fstream>
#include <sstream>
#include <stdexcept>
#if defined(CATCH_CONFIG_NEW_CAPTURE)
#if defined(_MSC_VER)
#include <io.h> //_dup and _dup2
#define dup _dup
#define dup2 _dup2
#define fileno _fileno
#else
#include <unistd.h> // dup and dup2
#endif
#endif
namespace Catch {
RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
: m_originalStream( originalStream ),
m_redirectionStream( redirectionStream ),
m_prevBuf( m_originalStream.rdbuf() )
{
m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
}
RedirectedStream::~RedirectedStream() {
m_originalStream.rdbuf( m_prevBuf );
}
RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
RedirectedStdErr::RedirectedStdErr()
: m_cerr( Catch::cerr(), m_rss.get() ),
m_clog( Catch::clog(), m_rss.get() )
{}
auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
: m_redirectedCout(redirectedCout),
m_redirectedCerr(redirectedCerr)
{}
RedirectedStreams::~RedirectedStreams() {
m_redirectedCout += m_redirectedStdOut.str();
m_redirectedCerr += m_redirectedStdErr.str();
}
#if defined(CATCH_CONFIG_NEW_CAPTURE)
#if defined(_MSC_VER)
TempFile::TempFile() {
if (tmpnam_s(m_buffer)) {
CATCH_RUNTIME_ERROR("Could not get a temp filename");
}
if (fopen_s(&m_file, m_buffer, "w+")) {
char buffer[100];
if (strerror_s(buffer, errno)) {
CATCH_RUNTIME_ERROR("Could not translate errno to a string");
}
CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
}
}
#else
TempFile::TempFile() {
m_file = std::tmpfile();
if (!m_file) {
CATCH_RUNTIME_ERROR("Could not create a temp file.");
}
}
#endif
TempFile::~TempFile() {
// TBD: What to do about errors here?
std::fclose(m_file);
// We manually create the file on Windows only, on Linux
// it will be autodeleted
#if defined(_MSC_VER)
std::remove(m_buffer);
#endif
}
FILE* TempFile::getFile() {
return m_file;
}
std::string TempFile::getContents() {
std::stringstream sstr;
char buffer[100] = {};
std::rewind(m_file);
while (std::fgets(buffer, sizeof(buffer), m_file)) {
sstr << buffer;
}
return sstr.str();
}
OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
m_originalStdout(dup(1)),
m_originalStderr(dup(2)),
m_stdoutDest(stdout_dest),
m_stderrDest(stderr_dest) {
dup2(fileno(m_stdoutFile.getFile()), 1);
dup2(fileno(m_stderrFile.getFile()), 2);
}
OutputRedirect::~OutputRedirect() {
Catch::cout() << std::flush;
fflush(stdout);
// Since we support overriding these streams, we flush cerr
// even though std::cerr is unbuffered
Catch::cerr() << std::flush;
Catch::clog() << std::flush;
fflush(stderr);
dup2(m_originalStdout, 1);
dup2(m_originalStderr, 2);
m_stdoutDest += m_stdoutFile.getContents();
m_stderrDest += m_stderrFile.getContents();
}
#endif // CATCH_CONFIG_NEW_CAPTURE
} // namespace Catch
#if defined(CATCH_CONFIG_NEW_CAPTURE)
#if defined(_MSC_VER)
#undef dup
#undef dup2
#undef fileno
#endif
#endif
// end catch_output_redirect.cpp
// start catch_polyfills.cpp
#include <cmath>
namespace Catch {
#if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
bool isnan(float f) {
return std::isnan(f);
}
bool isnan(double d) {
return std::isnan(d);
}
#else
// For now we only use this for embarcadero
bool isnan(float f) {
return std::_isnan(f);
}
bool isnan(double d) {
return std::_isnan(d);
}
#endif
} // end namespace Catch
// end catch_polyfills.cpp
// start catch_random_number_generator.cpp
namespace Catch {
namespace {
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4146) // we negate uint32 during the rotate
#endif
// Safe rotr implementation thanks to John Regehr
uint32_t rotate_right(uint32_t val, uint32_t count) {
const uint32_t mask = 31;
count &= mask;
return (val >> count) | (val << (-count & mask));
}
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
}
SimplePcg32::SimplePcg32(result_type seed_) {
seed(seed_);
}
void SimplePcg32::seed(result_type seed_) {
m_state = 0;
(*this)();
m_state += seed_;
(*this)();
}
void SimplePcg32::discard(uint64_t skip) {
// We could implement this to run in O(log n) steps, but this
// should suffice for our use case.
for (uint64_t s = 0; s < skip; ++s) {
static_cast<void>((*this)());
}
}
SimplePcg32::result_type SimplePcg32::operator()() {
// prepare the output value
const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
const auto output = rotate_right(xorshifted, m_state >> 59u);
// advance state
m_state = m_state * 6364136223846793005ULL + s_inc;
return output;
}
bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
return lhs.m_state == rhs.m_state;
}
bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
return lhs.m_state != rhs.m_state;
}
}
// end catch_random_number_generator.cpp
// start catch_registry_hub.cpp
// start catch_test_case_registry_impl.h
#include <vector>
#include <set>
#include <algorithm>
#include <ios>
namespace Catch {
class TestCase;
struct IConfig;
std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
bool isThrowSafe( TestCase const& testCase, IConfig const& config );
bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
class TestRegistry : public ITestCaseRegistry {
public:
virtual ~TestRegistry() = default;
virtual void registerTest( TestCase const& testCase );
std::vector<TestCase> const& getAllTests() const override;
std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
private:
std::vector<TestCase> m_functions;
mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
mutable std::vector<TestCase> m_sortedFunctions;
std::size_t m_unnamedCount = 0;
std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
};
///////////////////////////////////////////////////////////////////////////
class TestInvokerAsFunction : public ITestInvoker {
void(*m_testAsFunction)();
public:
TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
void invoke() const override;
};
std::string extractClassName( StringRef const& classOrQualifiedMethodName );
///////////////////////////////////////////////////////////////////////////
} // end namespace Catch
// end catch_test_case_registry_impl.h
// start catch_reporter_registry.h
#include <map>
namespace Catch {
class ReporterRegistry : public IReporterRegistry {
public:
~ReporterRegistry() override;
IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
void registerListener( IReporterFactoryPtr const& factory );
FactoryMap const& getFactories() const override;
Listeners const& getListeners() const override;
private:
FactoryMap m_factories;
Listeners m_listeners;
};
}
// end catch_reporter_registry.h
// start catch_tag_alias_registry.h
// start catch_tag_alias.h
#include <string>
namespace Catch {
struct TagAlias {
TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
std::string tag;
SourceLineInfo lineInfo;
};
} // end namespace Catch
// end catch_tag_alias.h
#include <map>
namespace Catch {
class TagAliasRegistry : public ITagAliasRegistry {
public:
~TagAliasRegistry() override;
TagAlias const* find( std::string const& alias ) const override;
std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
private:
std::map<std::string, TagAlias> m_registry;
};
} // end namespace Catch
// end catch_tag_alias_registry.h
// start catch_startup_exception_registry.h
#include <vector>
#include <exception>
namespace Catch {
class StartupExceptionRegistry {
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
public:
void add(std::exception_ptr const& exception) noexcept;
std::vector<std::exception_ptr> const& getExceptions() const noexcept;
private:
std::vector<std::exception_ptr> m_exceptions;
#endif
};
} // end namespace Catch
// end catch_startup_exception_registry.h
// start catch_singletons.hpp
namespace Catch {
struct ISingleton {
virtual ~ISingleton();
};
void addSingleton( ISingleton* singleton );
void cleanupSingletons();
template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
class Singleton : SingletonImplT, public ISingleton {
static auto getInternal() -> Singleton* {
static Singleton* s_instance = nullptr;
if( !s_instance ) {
s_instance = new Singleton;
addSingleton( s_instance );
}
return s_instance;
}
public:
static auto get() -> InterfaceT const& {
return *getInternal();
}
static auto getMutable() -> MutableInterfaceT& {
return *getInternal();
}
};
} // namespace Catch
// end catch_singletons.hpp
namespace Catch {
namespace {
class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
private NonCopyable {
public: // IRegistryHub
RegistryHub() = default;
IReporterRegistry const& getReporterRegistry() const override {
return m_reporterRegistry;
}
ITestCaseRegistry const& getTestCaseRegistry() const override {
return m_testCaseRegistry;
}
IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
return m_exceptionTranslatorRegistry;
}
ITagAliasRegistry const& getTagAliasRegistry() const override {
return m_tagAliasRegistry;
}
StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
return m_exceptionRegistry;
}
public: // IMutableRegistryHub
void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
m_reporterRegistry.registerReporter( name, factory );
}
void registerListener( IReporterFactoryPtr const& factory ) override {
m_reporterRegistry.registerListener( factory );
}
void registerTest( TestCase const& testInfo ) override {
m_testCaseRegistry.registerTest( testInfo );
}
void registerTranslator( const IExceptionTranslator* translator ) override {
m_exceptionTranslatorRegistry.registerTranslator( translator );
}
void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
m_tagAliasRegistry.add( alias, tag, lineInfo );
}
void registerStartupException() noexcept override {
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
m_exceptionRegistry.add(std::current_exception());
#else
CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
#endif
}
IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
return m_enumValuesRegistry;
}
private:
TestRegistry m_testCaseRegistry;
ReporterRegistry m_reporterRegistry;
ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
TagAliasRegistry m_tagAliasRegistry;
StartupExceptionRegistry m_exceptionRegistry;
Detail::EnumValuesRegistry m_enumValuesRegistry;
};
}
using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
IRegistryHub const& getRegistryHub() {
return RegistryHubSingleton::get();
}
IMutableRegistryHub& getMutableRegistryHub() {
return RegistryHubSingleton::getMutable();
}
void cleanUp() {
cleanupSingletons();
cleanUpContext();
}
std::string translateActiveException() {
return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
}
} // end namespace Catch
// end catch_registry_hub.cpp
// start catch_reporter_registry.cpp
namespace Catch {
ReporterRegistry::~ReporterRegistry() = default;
IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
auto it = m_factories.find( name );
if( it == m_factories.end() )
return nullptr;
return it->second->create( ReporterConfig( config ) );
}
void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
m_factories.emplace(name, factory);
}
void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
m_listeners.push_back( factory );
}
IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
return m_factories;
}
IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
return m_listeners;
}
}
// end catch_reporter_registry.cpp
// start catch_result_type.cpp
namespace Catch {
bool isOk( ResultWas::OfType resultType ) {
return ( resultType & ResultWas::FailureBit ) == 0;
}
bool isJustInfo( int flags ) {
return flags == ResultWas::Info;
}
ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
}
bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
} // end namespace Catch
// end catch_result_type.cpp
// start catch_run_context.cpp
#include <cassert>
#include <algorithm>
#include <sstream>
namespace Catch {
namespace Generators {
struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
GeneratorBasePtr m_generator;
GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
: TrackerBase( nameAndLocation, ctx, parent )
{}
~GeneratorTracker();
static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
std::shared_ptr<GeneratorTracker> tracker;
ITracker& currentTracker = ctx.currentTracker();
// Under specific circumstances, the generator we want
// to acquire is also the current tracker. If this is
// the case, we have to avoid looking through current
// tracker's children, and instead return the current
// tracker.
// A case where this check is important is e.g.
// for (int i = 0; i < 5; ++i) {
// int n = GENERATE(1, 2);
// }
//
// without it, the code above creates 5 nested generators.
if (currentTracker.nameAndLocation() == nameAndLocation) {
auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
assert(thisTracker);
assert(thisTracker->isGeneratorTracker());
tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
} else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
assert( childTracker );
assert( childTracker->isGeneratorTracker() );
tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
} else {
tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, ¤tTracker );
currentTracker.addChild( tracker );
}
if( !tracker->isComplete() ) {
tracker->open();
}
return *tracker;
}
// TrackerBase interface
bool isGeneratorTracker() const override { return true; }
auto hasGenerator() const -> bool override {
return !!m_generator;
}
void close() override {
TrackerBase::close();
// If a generator has a child (it is followed by a section)
// and none of its children have started, then we must wait
// until later to start consuming its values.
// This catches cases where `GENERATE` is placed between two
// `SECTION`s.
// **The check for m_children.empty cannot be removed**.
// doing so would break `GENERATE` _not_ followed by `SECTION`s.
const bool should_wait_for_child = [&]() {
// No children -> nobody to wait for
if ( m_children.empty() ) {
return false;
}
// If at least one child started executing, don't wait
if ( std::find_if(
m_children.begin(),
m_children.end(),
[]( TestCaseTracking::ITrackerPtr tracker ) {
return tracker->hasStarted();
} ) != m_children.end() ) {
return false;
}
// No children have started. We need to check if they _can_
// start, and thus we should wait for them, or they cannot
// start (due to filters), and we shouldn't wait for them
auto* parent = m_parent;
// This is safe: there is always at least one section
// tracker in a test case tracking tree
while ( !parent->isSectionTracker() ) {
parent = &( parent->parent() );
}
assert( parent &&
"Missing root (test case) level section" );
auto const& parentSection =
static_cast<SectionTracker&>( *parent );
auto const& filters = parentSection.getFilters();
// No filters -> no restrictions on running sections
if ( filters.empty() ) {
return true;
}
for ( auto const& child : m_children ) {
if ( child->isSectionTracker() &&
std::find( filters.begin(),
filters.end(),
static_cast<SectionTracker&>( *child )
.trimmedName() ) !=
filters.end() ) {
return true;
}
}
return false;
}();
// This check is a bit tricky, because m_generator->next()
// has a side-effect, where it consumes generator's current
// value, but we do not want to invoke the side-effect if
// this generator is still waiting for any child to start.
if ( should_wait_for_child ||
( m_runState == CompletedSuccessfully &&
m_generator->next() ) ) {
m_children.clear();
m_runState = Executing;
}
}
// IGeneratorTracker interface
auto getGenerator() const -> GeneratorBasePtr const& override {
return m_generator;
}
void setGenerator( GeneratorBasePtr&& generator ) override {
m_generator = std::move( generator );
}
};
GeneratorTracker::~GeneratorTracker() {}
}
RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
: m_runInfo(_config->name()),
m_context(getCurrentMutableContext()),
m_config(_config),
m_reporter(std::move(reporter)),
m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
{
m_context.setRunner(this);
m_context.setConfig(m_config);
m_context.setResultCapture(this);
m_reporter->testRunStarting(m_runInfo);
}
RunContext::~RunContext() {
m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
}
void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
}
void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
}
Totals RunContext::runTest(TestCase const& testCase) {
Totals prevTotals = m_totals;
std::string redirectedCout;
std::string redirectedCerr;
auto const& testInfo = testCase.getTestCaseInfo();
m_reporter->testCaseStarting(testInfo);
m_activeTestCase = &testCase;
ITracker& rootTracker = m_trackerContext.startRun();
assert(rootTracker.isSectionTracker());
static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
do {
m_trackerContext.startCycle();
m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
runCurrentTest(redirectedCout, redirectedCerr);
} while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
Totals deltaTotals = m_totals.delta(prevTotals);
if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
deltaTotals.assertions.failed++;
deltaTotals.testCases.passed--;
deltaTotals.testCases.failed++;
}
m_totals.testCases += deltaTotals.testCases;
m_reporter->testCaseEnded(TestCaseStats(testInfo,
deltaTotals,
redirectedCout,
redirectedCerr,
aborting()));
m_activeTestCase = nullptr;
m_testCaseTracker = nullptr;
return deltaTotals;
}
IConfigPtr RunContext::config() const {
return m_config;
}
IStreamingReporter& RunContext::reporter() const {
return *m_reporter;
}
void RunContext::assertionEnded(AssertionResult const & result) {
if (result.getResultType() == ResultWas::Ok) {
m_totals.assertions.passed++;
m_lastAssertionPassed = true;
} else if (!result.isOk()) {
m_lastAssertionPassed = false;
if( m_activeTestCase->getTestCaseInfo().okToFail() )
m_totals.assertions.failedButOk++;
else
m_totals.assertions.failed++;
}
else {
m_lastAssertionPassed = true;
}
// We have no use for the return value (whether messages should be cleared), because messages were made scoped
// and should be let to clear themselves out.
static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
if (result.getResultType() != ResultWas::Warning)
m_messageScopes.clear();
// Reset working state
resetAssertionInfo();
m_lastResult = result;
}
void RunContext::resetAssertionInfo() {
m_lastAssertionInfo.macroName = StringRef();
m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
}
bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
if (!sectionTracker.isOpen())
return false;
m_activeSections.push_back(§ionTracker);
m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
m_reporter->sectionStarting(sectionInfo);
assertions = m_totals.assertions;
return true;
}
auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
using namespace Generators;
GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
m_lastAssertionInfo.lineInfo = lineInfo;
return tracker;
}
bool RunContext::testForMissingAssertions(Counts& assertions) {
if (assertions.total() != 0)
return false;
if (!m_config->warnAboutMissingAssertions())
return false;
if (m_trackerContext.currentTracker().hasChildren())
return false;
m_totals.assertions.failed++;
assertions.failed++;
return true;
}
void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
Counts assertions = m_totals.assertions - endInfo.prevAssertions;
bool missingAssertions = testForMissingAssertions(assertions);
if (!m_activeSections.empty()) {
m_activeSections.back()->close();
m_activeSections.pop_back();
}
m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
m_messages.clear();
m_messageScopes.clear();
}
void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
if (m_unfinishedSections.empty())
m_activeSections.back()->fail();
else
m_activeSections.back()->close();
m_activeSections.pop_back();
m_unfinishedSections.push_back(endInfo);
}
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
void RunContext::benchmarkPreparing(std::string const& name) {
m_reporter->benchmarkPreparing(name);
}
void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
m_reporter->benchmarkStarting( info );
}
void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
m_reporter->benchmarkEnded( stats );
}
void RunContext::benchmarkFailed(std::string const & error) {
m_reporter->benchmarkFailed(error);
}
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
void RunContext::pushScopedMessage(MessageInfo const & message) {
m_messages.push_back(message);
}
void RunContext::popScopedMessage(MessageInfo const & message) {
m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
}
void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
m_messageScopes.emplace_back( builder );
}
std::string RunContext::getCurrentTestName() const {
return m_activeTestCase
? m_activeTestCase->getTestCaseInfo().name
: std::string();
}
const AssertionResult * RunContext::getLastResult() const {
return &(*m_lastResult);
}
void RunContext::exceptionEarlyReported() {
m_shouldReportUnexpected = false;
}
void RunContext::handleFatalErrorCondition( StringRef message ) {
// First notify reporter that bad things happened
m_reporter->fatalErrorEncountered(message);
// Don't rebuild the result -- the stringification itself can cause more fatal errors
// Instead, fake a result data.
AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
tempResult.message = static_cast<std::string>(message);
AssertionResult result(m_lastAssertionInfo, tempResult);
assertionEnded(result);
handleUnfinishedSections();
// Recreate section for test case (as we will lose the one that was in scope)
auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
Counts assertions;
assertions.failed = 1;
SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
m_reporter->sectionEnded(testCaseSectionStats);
auto const& testInfo = m_activeTestCase->getTestCaseInfo();
Totals deltaTotals;
deltaTotals.testCases.failed = 1;
deltaTotals.assertions.failed = 1;
m_reporter->testCaseEnded(TestCaseStats(testInfo,
deltaTotals,
std::string(),
std::string(),
false));
m_totals.testCases.failed++;
testGroupEnded(std::string(), m_totals, 1, 1);
m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
}
bool RunContext::lastAssertionPassed() {
return m_lastAssertionPassed;
}
void RunContext::assertionPassed() {
m_lastAssertionPassed = true;
++m_totals.assertions.passed;
resetAssertionInfo();
m_messageScopes.clear();
}
bool RunContext::aborting() const {
return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
}
void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
m_reporter->sectionStarting(testCaseSection);
Counts prevAssertions = m_totals.assertions;
double duration = 0;
m_shouldReportUnexpected = true;
m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
seedRng(*m_config);
Timer timer;
CATCH_TRY {
if (m_reporter->getPreferences().shouldRedirectStdOut) {
#if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
timer.start();
invokeActiveTestCase();
#else
OutputRedirect r(redirectedCout, redirectedCerr);
timer.start();
invokeActiveTestCase();
#endif
} else {
timer.start();
invokeActiveTestCase();
}
duration = timer.getElapsedSeconds();
} CATCH_CATCH_ANON (TestFailureException&) {
// This just means the test was aborted due to failure
} CATCH_CATCH_ALL {
// Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
// are reported without translation at the point of origin.
if( m_shouldReportUnexpected ) {
AssertionReaction dummyReaction;
handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
}
}
Counts assertions = m_totals.assertions - prevAssertions;
bool missingAssertions = testForMissingAssertions(assertions);
m_testCaseTracker->close();
handleUnfinishedSections();
m_messages.clear();
m_messageScopes.clear();
SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
m_reporter->sectionEnded(testCaseSectionStats);
}
void RunContext::invokeActiveTestCase() {
FatalConditionHandler fatalConditionHandler; // Handle signals
m_activeTestCase->invoke();
fatalConditionHandler.reset();
}
void RunContext::handleUnfinishedSections() {
// If sections ended prematurely due to an exception we stored their
// infos here so we can tear them down outside the unwind process.
for (auto it = m_unfinishedSections.rbegin(),
itEnd = m_unfinishedSections.rend();
it != itEnd;
++it)
sectionEnded(*it);
m_unfinishedSections.clear();
}
void RunContext::handleExpr(
AssertionInfo const& info,
ITransientExpression const& expr,
AssertionReaction& reaction
) {
m_reporter->assertionStarting( info );
bool negated = isFalseTest( info.resultDisposition );
bool result = expr.getResult() != negated;
if( result ) {
if (!m_includeSuccessfulResults) {
assertionPassed();
}
else {
reportExpr(info, ResultWas::Ok, &expr, negated);
}
}
else {
reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
populateReaction( reaction );
}
}
void RunContext::reportExpr(
AssertionInfo const &info,
ResultWas::OfType resultType,
ITransientExpression const *expr,
bool negated ) {
m_lastAssertionInfo = info;
AssertionResultData data( resultType, LazyExpression( negated ) );
AssertionResult assertionResult{ info, data };
assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
assertionEnded( assertionResult );
}
void RunContext::handleMessage(
AssertionInfo const& info,
ResultWas::OfType resultType,
StringRef const& message,
AssertionReaction& reaction
) {
m_reporter->assertionStarting( info );
m_lastAssertionInfo = info;
AssertionResultData data( resultType, LazyExpression( false ) );
data.message = static_cast<std::string>(message);
AssertionResult assertionResult{ m_lastAssertionInfo, data };
assertionEnded( assertionResult );
if( !assertionResult.isOk() )
populateReaction( reaction );
}
void RunContext::handleUnexpectedExceptionNotThrown(
AssertionInfo const& info,
AssertionReaction& reaction
) {
handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
}
void RunContext::handleUnexpectedInflightException(
AssertionInfo const& info,
std::string const& message,
AssertionReaction& reaction
) {
m_lastAssertionInfo = info;
AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
data.message = message;
AssertionResult assertionResult{ info, data };
assertionEnded( assertionResult );
populateReaction( reaction );
}
void RunContext::populateReaction( AssertionReaction& reaction ) {
reaction.shouldDebugBreak = m_config->shouldDebugBreak();
reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
}
void RunContext::handleIncomplete(
AssertionInfo const& info
) {
m_lastAssertionInfo = info;
AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
AssertionResult assertionResult{ info, data };
assertionEnded( assertionResult );
}
void RunContext::handleNonExpr(
AssertionInfo const &info,
ResultWas::OfType resultType,
AssertionReaction &reaction
) {
m_lastAssertionInfo = info;
AssertionResultData data( resultType, LazyExpression( false ) );
AssertionResult assertionResult{ info, data };
assertionEnded( assertionResult );
if( !assertionResult.isOk() )
populateReaction( reaction );
}
IResultCapture& getResultCapture() {
if (auto* capture = getCurrentContext().getResultCapture())
return *capture;
else
CATCH_INTERNAL_ERROR("No result capture instance");
}
void seedRng(IConfig const& config) {
if (config.rngSeed() != 0) {
std::srand(config.rngSeed());
rng().seed(config.rngSeed());
}
}
unsigned int rngSeed() {
return getCurrentContext().getConfig()->rngSeed();
}
}
// end catch_run_context.cpp
// start catch_section.cpp
namespace Catch {
Section::Section( SectionInfo const& info )
: m_info( info ),
m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
{
m_timer.start();
}
Section::~Section() {
if( m_sectionIncluded ) {
SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
if( uncaught_exceptions() )
getResultCapture().sectionEndedEarly( endInfo );
else
getResultCapture().sectionEnded( endInfo );
}
}
// This indicates whether the section should be executed or not
Section::operator bool() const {
return m_sectionIncluded;
}
} // end namespace Catch
// end catch_section.cpp
// start catch_section_info.cpp
namespace Catch {
SectionInfo::SectionInfo
( SourceLineInfo const& _lineInfo,
std::string const& _name )
: name( _name ),
lineInfo( _lineInfo )
{}
} // end namespace Catch
// end catch_section_info.cpp
// start catch_session.cpp
// start catch_session.h
#include <memory>
namespace Catch {
class Session : NonCopyable {
public:
Session();
~Session() override;
void showHelp() const;
void libIdentify();
int applyCommandLine( int argc, char const * const * argv );
#if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
int applyCommandLine( int argc, wchar_t const * const * argv );
#endif
void useConfigData( ConfigData const& configData );
template<typename CharT>
int run(int argc, CharT const * const argv[]) {
if (m_startupExceptions)
return 1;
int returnCode = applyCommandLine(argc, argv);
if (returnCode == 0)
returnCode = run();
return returnCode;
}
int run();
clara::Parser const& cli() const;
void cli( clara::Parser const& newParser );
ConfigData& configData();
Config& config();
private:
int runInternal();
clara::Parser m_cli;
ConfigData m_configData;
std::shared_ptr<Config> m_config;
bool m_startupExceptions = false;
};
} // end namespace Catch
// end catch_session.h
// start catch_version.h
#include <iosfwd>
namespace Catch {
// Versioning information
struct Version {
Version( Version const& ) = delete;
Version& operator=( Version const& ) = delete;
Version( unsigned int _majorVersion,
unsigned int _minorVersion,
unsigned int _patchNumber,
char const * const _branchName,
unsigned int _buildNumber );
unsigned int const majorVersion;
unsigned int const minorVersion;
unsigned int const patchNumber;
// buildNumber is only used if branchName is not null
char const * const branchName;
unsigned int const buildNumber;
friend std::ostream& operator << ( std::ostream& os, Version const& version );
};
Version const& libraryVersion();
}
// end catch_version.h
#include <cstdlib>
#include <iomanip>
#include <set>
#include <iterator>
namespace Catch {
namespace {
const int MaxExitCode = 255;
IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
return reporter;
}
IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
return createReporter(config->getReporterName(), config);
}
// On older platforms, returning std::unique_ptr<ListeningReporter>
// when the return type is std::unique_ptr<IStreamingReporter>
// doesn't compile without a std::move call. However, this causes
// a warning on newer platforms. Thus, we have to work around
// it a bit and downcast the pointer manually.
auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
auto& multi = static_cast<ListeningReporter&>(*ret);
auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
for (auto const& listener : listeners) {
multi.addListener(listener->create(Catch::ReporterConfig(config)));
}
multi.addReporter(createReporter(config->getReporterName(), config));
return ret;
}
class TestGroup {
public:
explicit TestGroup(std::shared_ptr<Config> const& config)
: m_config{config}
, m_context{config, makeReporter(config)}
{
auto const& allTestCases = getAllTestCasesSorted(*m_config);
m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
if (m_matches.empty() && invalidArgs.empty()) {
for (auto const& test : allTestCases)
if (!test.isHidden())
m_tests.emplace(&test);
} else {
for (auto const& match : m_matches)
m_tests.insert(match.tests.begin(), match.tests.end());
}
}
Totals execute() {
auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
Totals totals;
m_context.testGroupStarting(m_config->name(), 1, 1);
for (auto const& testCase : m_tests) {
if (!m_context.aborting())
totals += m_context.runTest(*testCase);
else
m_context.reporter().skipTest(*testCase);
}
for (auto const& match : m_matches) {
if (match.tests.empty()) {
m_context.reporter().noMatchingTestCases(match.name);
totals.error = -1;
}
}
if (!invalidArgs.empty()) {
for (auto const& invalidArg: invalidArgs)
m_context.reporter().reportInvalidArguments(invalidArg);
}
m_context.testGroupEnded(m_config->name(), totals, 1, 1);
return totals;
}
private:
using Tests = std::set<TestCase const*>;
std::shared_ptr<Config> m_config;
RunContext m_context;
Tests m_tests;
TestSpec::Matches m_matches;
};
void applyFilenamesAsTags(Catch::IConfig const& config) {
auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
for (auto& testCase : tests) {
auto tags = testCase.tags;
std::string filename = testCase.lineInfo.file;
auto lastSlash = filename.find_last_of("\\/");
if (lastSlash != std::string::npos) {
filename.erase(0, lastSlash);
filename[0] = '#';
}
auto lastDot = filename.find_last_of('.');
if (lastDot != std::string::npos) {
filename.erase(lastDot);
}
tags.push_back(std::move(filename));
setTags(testCase, tags);
}
}
} // anon namespace
Session::Session() {
static bool alreadyInstantiated = false;
if( alreadyInstantiated ) {
CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
}
// There cannot be exceptions at startup in no-exception mode.
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
if ( !exceptions.empty() ) {
config();
getCurrentMutableContext().setConfig(m_config);
m_startupExceptions = true;
Colour colourGuard( Colour::Red );
Catch::cerr() << "Errors occurred during startup!" << '\n';
// iterate over all exceptions and notify user
for ( const auto& ex_ptr : exceptions ) {
try {
std::rethrow_exception(ex_ptr);
} catch ( std::exception const& ex ) {
Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
}
}
}
#endif
alreadyInstantiated = true;
m_cli = makeCommandLineParser( m_configData );
}
Session::~Session() {
Catch::cleanUp();
}
void Session::showHelp() const {
Catch::cout()
<< "\nCatch v" << libraryVersion() << "\n"
<< m_cli << std::endl
<< "For more detailed usage please see the project docs\n" << std::endl;
}
void Session::libIdentify() {
Catch::cout()
<< std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
<< std::left << std::setw(16) << "category: " << "testframework\n"
<< std::left << std::setw(16) << "framework: " << "Catch Test\n"
<< std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
}
int Session::applyCommandLine( int argc, char const * const * argv ) {
if( m_startupExceptions )
return 1;
auto result = m_cli.parse( clara::Args( argc, argv ) );
if( !result ) {
config();
getCurrentMutableContext().setConfig(m_config);
Catch::cerr()
<< Colour( Colour::Red )
<< "\nError(s) in input:\n"
<< Column( result.errorMessage() ).indent( 2 )
<< "\n\n";
Catch::cerr() << "Run with -? for usage\n" << std::endl;
return MaxExitCode;
}
if( m_configData.showHelp )
showHelp();
if( m_configData.libIdentify )
libIdentify();
m_config.reset();
return 0;
}
#if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
char **utf8Argv = new char *[ argc ];
for ( int i = 0; i < argc; ++i ) {
int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
utf8Argv[ i ] = new char[ bufSize ];
WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
}
int returnCode = applyCommandLine( argc, utf8Argv );
for ( int i = 0; i < argc; ++i )
delete [] utf8Argv[ i ];
delete [] utf8Argv;
return returnCode;
}
#endif
void Session::useConfigData( ConfigData const& configData ) {
m_configData = configData;
m_config.reset();
}
int Session::run() {
if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
static_cast<void>(std::getchar());
}
int exitCode = runInternal();
if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
static_cast<void>(std::getchar());
}
return exitCode;
}
clara::Parser const& Session::cli() const {
return m_cli;
}
void Session::cli( clara::Parser const& newParser ) {
m_cli = newParser;
}
ConfigData& Session::configData() {
return m_configData;
}
Config& Session::config() {
if( !m_config )
m_config = std::make_shared<Config>( m_configData );
return *m_config;
}
int Session::runInternal() {
if( m_startupExceptions )
return 1;
if (m_configData.showHelp || m_configData.libIdentify) {
return 0;
}
CATCH_TRY {
config(); // Force config to be constructed
seedRng( *m_config );
if( m_configData.filenamesAsTags )
applyFilenamesAsTags( *m_config );
// Handle list request
if( Option<std::size_t> listed = list( m_config ) )
return static_cast<int>( *listed );
TestGroup tests { m_config };
auto const totals = tests.execute();
if( m_config->warnAboutNoTests() && totals.error == -1 )
return 2;
// Note that on unices only the lower 8 bits are usually used, clamping
// the return value to 255 prevents false negative when some multiple
// of 256 tests has failed
return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
}
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
catch( std::exception& ex ) {
Catch::cerr() << ex.what() << std::endl;
return MaxExitCode;
}
#endif
}
} // end namespace Catch
// end catch_session.cpp
// start catch_singletons.cpp
#include <vector>
namespace Catch {
namespace {
static auto getSingletons() -> std::vector<ISingleton*>*& {
static std::vector<ISingleton*>* g_singletons = nullptr;
if( !g_singletons )
g_singletons = new std::vector<ISingleton*>();
return g_singletons;
}
}
ISingleton::~ISingleton() {}
void addSingleton(ISingleton* singleton ) {
getSingletons()->push_back( singleton );
}
void cleanupSingletons() {
auto& singletons = getSingletons();
for( auto singleton : *singletons )
delete singleton;
delete singletons;
singletons = nullptr;
}
} // namespace Catch
// end catch_singletons.cpp
// start catch_startup_exception_registry.cpp
#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
namespace Catch {
void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
CATCH_TRY {
m_exceptions.push_back(exception);
} CATCH_CATCH_ALL {
// If we run out of memory during start-up there's really not a lot more we can do about it
std::terminate();
}
}
std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
return m_exceptions;
}
} // end namespace Catch
#endif
// end catch_startup_exception_registry.cpp
// start catch_stream.cpp
#include <cstdio>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <memory>
namespace Catch {
Catch::IStream::~IStream() = default;
namespace Detail { namespace {
template<typename WriterF, std::size_t bufferSize=256>
class StreamBufImpl : public std::streambuf {
char data[bufferSize];
WriterF m_writer;
public:
StreamBufImpl() {
setp( data, data + sizeof(data) );
}
~StreamBufImpl() noexcept {
StreamBufImpl::sync();
}
private:
int overflow( int c ) override {
sync();
if( c != EOF ) {
if( pbase() == epptr() )
m_writer( std::string( 1, static_cast<char>( c ) ) );
else
sputc( static_cast<char>( c ) );
}
return 0;
}
int sync() override {
if( pbase() != pptr() ) {
m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
setp( pbase(), epptr() );
}
return 0;
}
};
///////////////////////////////////////////////////////////////////////////
struct OutputDebugWriter {
void operator()( std::string const&str ) {
writeToDebugConsole( str );
}
};
///////////////////////////////////////////////////////////////////////////
class FileStream : public IStream {
mutable std::ofstream m_ofs;
public:
FileStream( StringRef filename ) {
m_ofs.open( filename.c_str() );
CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
}
~FileStream() override = default;
public: // IStream
std::ostream& stream() const override {
return m_ofs;
}
};
///////////////////////////////////////////////////////////////////////////
class CoutStream : public IStream {
mutable std::ostream m_os;
public:
// Store the streambuf from cout up-front because
// cout may get redirected when running tests
CoutStream() : m_os( Catch::cout().rdbuf() ) {}
~CoutStream() override = default;
public: // IStream
std::ostream& stream() const override { return m_os; }
};
///////////////////////////////////////////////////////////////////////////
class DebugOutStream : public IStream {
std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
mutable std::ostream m_os;
public:
DebugOutStream()
: m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
m_os( m_streamBuf.get() )
{}
~DebugOutStream() override = default;
public: // IStream
std::ostream& stream() const override { return m_os; }
};
}} // namespace anon::detail
///////////////////////////////////////////////////////////////////////////
auto makeStream( StringRef const &filename ) -> IStream const* {
if( filename.empty() )
return new Detail::CoutStream();
else if( filename[0] == '%' ) {
if( filename == "%debug" )
return new Detail::DebugOutStream();
else
CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
}
else
return new Detail::FileStream( filename );
}
// This class encapsulates the idea of a pool of ostringstreams that can be reused.
struct StringStreams {
std::vector<std::unique_ptr<std::ostringstream>> m_streams;
std::vector<std::size_t> m_unused;
std::ostringstream m_referenceStream; // Used for copy state/ flags from
auto add() -> std::size_t {
if( m_unused.empty() ) {
m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
return m_streams.size()-1;
}
else {
auto index = m_unused.back();
m_unused.pop_back();
return index;
}
}
void release( std::size_t index ) {
m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
m_unused.push_back(index);
}
};
ReusableStringStream::ReusableStringStream()
: m_index( Singleton<StringStreams>::getMutable().add() ),
m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
{}
ReusableStringStream::~ReusableStringStream() {
static_cast<std::ostringstream*>( m_oss )->str("");
m_oss->clear();
Singleton<StringStreams>::getMutable().release( m_index );
}
auto ReusableStringStream::str() const -> std::string {
return static_cast<std::ostringstream*>( m_oss )->str();
}
///////////////////////////////////////////////////////////////////////////
#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
std::ostream& cout() { return std::cout; }
std::ostream& cerr() { return std::cerr; }
std::ostream& clog() { return std::clog; }
#endif
}
// end catch_stream.cpp
// start catch_string_manip.cpp
#include <algorithm>
#include <ostream>
#include <cstring>
#include <cctype>
#include <vector>
namespace Catch {
namespace {
char toLowerCh(char c) {
return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
}
}
bool startsWith( std::string const& s, std::string const& prefix ) {
return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
}
bool startsWith( std::string const& s, char prefix ) {
return !s.empty() && s[0] == prefix;
}
bool endsWith( std::string const& s, std::string const& suffix ) {
return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
}
bool endsWith( std::string const& s, char suffix ) {
return !s.empty() && s[s.size()-1] == suffix;
}
bool contains( std::string const& s, std::string const& infix ) {
return s.find( infix ) != std::string::npos;
}
void toLowerInPlace( std::string& s ) {
std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
}
std::string toLower( std::string const& s ) {
std::string lc = s;
toLowerInPlace( lc );
return lc;
}
std::string trim( std::string const& str ) {
static char const* whitespaceChars = "\n\r\t ";
std::string::size_type start = str.find_first_not_of( whitespaceChars );
std::string::size_type end = str.find_last_not_of( whitespaceChars );
return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
}
StringRef trim(StringRef ref) {
const auto is_ws = [](char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
};
size_t real_begin = 0;
while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
size_t real_end = ref.size();
while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
return ref.substr(real_begin, real_end - real_begin);
}
bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
bool replaced = false;
std::size_t i = str.find( replaceThis );
while( i != std::string::npos ) {
replaced = true;
str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
if( i < str.size()-withThis.size() )
i = str.find( replaceThis, i+withThis.size() );
else
i = std::string::npos;
}
return replaced;
}
std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
std::vector<StringRef> subStrings;
std::size_t start = 0;
for(std::size_t pos = 0; pos < str.size(); ++pos ) {
if( str[pos] == delimiter ) {
if( pos - start > 1 )
subStrings.push_back( str.substr( start, pos-start ) );
start = pos+1;
}
}
if( start < str.size() )
subStrings.push_back( str.substr( start, str.size()-start ) );
return subStrings;
}
pluralise::pluralise( std::size_t count, std::string const& label )
: m_count( count ),
m_label( label )
{}
std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
os << pluraliser.m_count << ' ' << pluraliser.m_label;
if( pluraliser.m_count != 1 )
os << 's';
return os;
}
}
// end catch_string_manip.cpp
// start catch_stringref.cpp
#include <algorithm>
#include <ostream>
#include <cstring>
#include <cstdint>
namespace Catch {
StringRef::StringRef( char const* rawChars ) noexcept
: StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
{}
auto StringRef::c_str() const -> char const* {
CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance");
return m_start;
}
auto StringRef::data() const noexcept -> char const* {
return m_start;
}
auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
if (start < m_size) {
return StringRef(m_start + start, (std::min)(m_size - start, size));
} else {
return StringRef();
}
}
auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
return m_size == other.m_size
&& (std::memcmp( m_start, other.m_start, m_size ) == 0);
}
auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
return os.write(str.data(), str.size());
}
auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
lhs.append(rhs.data(), rhs.size());
return lhs;
}
} // namespace Catch
// end catch_stringref.cpp
// start catch_tag_alias.cpp
namespace Catch {
TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
}
// end catch_tag_alias.cpp
// start catch_tag_alias_autoregistrar.cpp
namespace Catch {
RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
CATCH_TRY {
getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
} CATCH_CATCH_ALL {
// Do not throw when constructing global objects, instead register the exception to be processed later
getMutableRegistryHub().registerStartupException();
}
}
}
// end catch_tag_alias_autoregistrar.cpp
// start catch_tag_alias_registry.cpp
#include <sstream>
namespace Catch {
TagAliasRegistry::~TagAliasRegistry() {}
TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
auto it = m_registry.find( alias );
if( it != m_registry.end() )
return &(it->second);
else
return nullptr;
}
std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
std::string expandedTestSpec = unexpandedTestSpec;
for( auto const& registryKvp : m_registry ) {
std::size_t pos = expandedTestSpec.find( registryKvp.first );
if( pos != std::string::npos ) {
expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
registryKvp.second.tag +
expandedTestSpec.substr( pos + registryKvp.first.size() );
}
}
return expandedTestSpec;
}
void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
"error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
"error: tag alias, '" << alias << "' already registered.\n"
<< "\tFirst seen at: " << find(alias)->lineInfo << "\n"
<< "\tRedefined at: " << lineInfo );
}
ITagAliasRegistry::~ITagAliasRegistry() {}
ITagAliasRegistry const& ITagAliasRegistry::get() {
return getRegistryHub().getTagAliasRegistry();
}
} // end namespace Catch
// end catch_tag_alias_registry.cpp
// start catch_test_case_info.cpp
#include <cctype>
#include <exception>
#include <algorithm>
#include <sstream>
namespace Catch {
namespace {
TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
if( startsWith( tag, '.' ) ||
tag == "!hide" )
return TestCaseInfo::IsHidden;
else if( tag == "!throws" )
return TestCaseInfo::Throws;
else if( tag == "!shouldfail" )
return TestCaseInfo::ShouldFail;
else if( tag == "!mayfail" )
return TestCaseInfo::MayFail;
else if( tag == "!nonportable" )
return TestCaseInfo::NonPortable;
else if( tag == "!benchmark" )
return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
else
return TestCaseInfo::None;
}
bool isReservedTag( std::string const& tag ) {
return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
}
void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
CATCH_ENFORCE( !isReservedTag(tag),
"Tag name: [" << tag << "] is not allowed.\n"
<< "Tag names starting with non alphanumeric characters are reserved\n"
<< _lineInfo );
}
}
TestCase makeTestCase( ITestInvoker* _testCase,
std::string const& _className,
NameAndTags const& nameAndTags,
SourceLineInfo const& _lineInfo )
{
bool isHidden = false;
// Parse out tags
std::vector<std::string> tags;
std::string desc, tag;
bool inTag = false;
for (char c : nameAndTags.tags) {
if( !inTag ) {
if( c == '[' )
inTag = true;
else
desc += c;
}
else {
if( c == ']' ) {
TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
if( ( prop & TestCaseInfo::IsHidden ) != 0 )
isHidden = true;
else if( prop == TestCaseInfo::None )
enforceNotReservedTag( tag, _lineInfo );
// Merged hide tags like `[.approvals]` should be added as
// `[.][approvals]`. The `[.]` is added at later point, so
// we only strip the prefix
if (startsWith(tag, '.') && tag.size() > 1) {
tag.erase(0, 1);
}
tags.push_back( tag );
tag.clear();
inTag = false;
}
else
tag += c;
}
}
if( isHidden ) {
// Add all "hidden" tags to make them behave identically
tags.insert( tags.end(), { ".", "!hide" } );
}
TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
return TestCase( _testCase, std::move(info) );
}
void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
std::sort(begin(tags), end(tags));
tags.erase(std::unique(begin(tags), end(tags)), end(tags));
testCaseInfo.lcaseTags.clear();
for( auto const& tag : tags ) {
std::string lcaseTag = toLower( tag );
testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
testCaseInfo.lcaseTags.push_back( lcaseTag );
}
testCaseInfo.tags = std::move(tags);
}
TestCaseInfo::TestCaseInfo( std::string const& _name,
std::string const& _className,
std::string const& _description,
std::vector<std::string> const& _tags,
SourceLineInfo const& _lineInfo )
: name( _name ),
className( _className ),
description( _description ),
lineInfo( _lineInfo ),
properties( None )
{
setTags( *this, _tags );
}
bool TestCaseInfo::isHidden() const {
return ( properties & IsHidden ) != 0;
}
bool TestCaseInfo::throws() const {
return ( properties & Throws ) != 0;
}
bool TestCaseInfo::okToFail() const {
return ( properties & (ShouldFail | MayFail ) ) != 0;
}
bool TestCaseInfo::expectedToFail() const {
return ( properties & (ShouldFail ) ) != 0;
}
std::string TestCaseInfo::tagsAsString() const {
std::string ret;
// '[' and ']' per tag
std::size_t full_size = 2 * tags.size();
for (const auto& tag : tags) {
full_size += tag.size();
}
ret.reserve(full_size);
for (const auto& tag : tags) {
ret.push_back('[');
ret.append(tag);
ret.push_back(']');
}
return ret;
}
TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
TestCase TestCase::withName( std::string const& _newName ) const {
TestCase other( *this );
other.name = _newName;
return other;
}
void TestCase::invoke() const {
test->invoke();
}
bool TestCase::operator == ( TestCase const& other ) const {
return test.get() == other.test.get() &&
name == other.name &&
className == other.className;
}
bool TestCase::operator < ( TestCase const& other ) const {
return name < other.name;
}
TestCaseInfo const& TestCase::getTestCaseInfo() const
{
return *this;
}
} // end namespace Catch
// end catch_test_case_info.cpp
// start catch_test_case_registry_impl.cpp
#include <algorithm>
#include <sstream>
namespace Catch {
namespace {
struct TestHasher {
explicit TestHasher(Catch::SimplePcg32& rng_instance) {
basis = rng_instance();
basis <<= 32;
basis |= rng_instance();
}
uint64_t basis;
uint64_t operator()(TestCase const& t) const {
// Modified FNV-1a hash
static constexpr uint64_t prime = 1099511628211;
uint64_t hash = basis;
for (const char c : t.name) {
hash ^= c;
hash *= prime;
}
return hash;
}
};
} // end unnamed namespace
std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
switch( config.runOrder() ) {
case RunTests::InDeclarationOrder:
// already in declaration order
break;
case RunTests::InLexicographicalOrder: {
std::vector<TestCase> sorted = unsortedTestCases;
std::sort( sorted.begin(), sorted.end() );
return sorted;
}
case RunTests::InRandomOrder: {
seedRng( config );
TestHasher h( rng() );
using hashedTest = std::pair<uint64_t, TestCase const*>;
std::vector<hashedTest> indexed_tests;
indexed_tests.reserve( unsortedTestCases.size() );
for (auto const& testCase : unsortedTestCases) {
indexed_tests.emplace_back(h(testCase), &testCase);
}
std::sort(indexed_tests.begin(), indexed_tests.end(),
[](hashedTest const& lhs, hashedTest const& rhs) {
if (lhs.first == rhs.first) {
return lhs.second->name < rhs.second->name;
}
return lhs.first < rhs.first;
});
std::vector<TestCase> sorted;
sorted.reserve( indexed_tests.size() );
for (auto const& hashed : indexed_tests) {
sorted.emplace_back(*hashed.second);
}
return sorted;
}
}
return unsortedTestCases;
}
bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
return !testCase.throws() || config.allowThrows();
}
bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
}
void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
std::set<TestCase> seenFunctions;
for( auto const& function : functions ) {
auto prev = seenFunctions.insert( function );
CATCH_ENFORCE( prev.second,
"error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
<< "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
<< "\tRedefined at " << function.getTestCaseInfo().lineInfo );
}
}
std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
std::vector<TestCase> filtered;
filtered.reserve( testCases.size() );
for (auto const& testCase : testCases) {
if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
(testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
filtered.push_back(testCase);
}
}
return filtered;
}
std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
}
void TestRegistry::registerTest( TestCase const& testCase ) {
std::string name = testCase.getTestCaseInfo().name;
if( name.empty() ) {
ReusableStringStream rss;
rss << "Anonymous test case " << ++m_unnamedCount;
return registerTest( testCase.withName( rss.str() ) );
}
m_functions.push_back( testCase );
}
std::vector<TestCase> const& TestRegistry::getAllTests() const {
return m_functions;
}
std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
if( m_sortedFunctions.empty() )
enforceNoDuplicateTestCases( m_functions );
if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
m_sortedFunctions = sortTests( config, m_functions );
m_currentSortOrder = config.runOrder();
}
return m_sortedFunctions;
}
///////////////////////////////////////////////////////////////////////////
TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
void TestInvokerAsFunction::invoke() const {
m_testAsFunction();
}
std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
std::string className(classOrQualifiedMethodName);
if( startsWith( className, '&' ) )
{
std::size_t lastColons = className.rfind( "::" );
std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
if( penultimateColons == std::string::npos )
penultimateColons = 1;
className = className.substr( penultimateColons, lastColons-penultimateColons );
}
return className;
}
} // end namespace Catch
// end catch_test_case_registry_impl.cpp
// start catch_test_case_tracker.cpp
#include <algorithm>
#include <cassert>
#include <stdexcept>
#include <memory>
#include <sstream>
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wexit-time-destructors"
#endif
namespace Catch {
namespace TestCaseTracking {
NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
: name( _name ),
location( _location )
{}
ITracker::~ITracker() = default;
ITracker& TrackerContext::startRun() {
m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
m_currentTracker = nullptr;
m_runState = Executing;
return *m_rootTracker;
}
void TrackerContext::endRun() {
m_rootTracker.reset();
m_currentTracker = nullptr;
m_runState = NotStarted;
}
void TrackerContext::startCycle() {
m_currentTracker = m_rootTracker.get();
m_runState = Executing;
}
void TrackerContext::completeCycle() {
m_runState = CompletedCycle;
}
bool TrackerContext::completedCycle() const {
return m_runState == CompletedCycle;
}
ITracker& TrackerContext::currentTracker() {
return *m_currentTracker;
}
void TrackerContext::setCurrentTracker( ITracker* tracker ) {
m_currentTracker = tracker;
}
TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
ITracker(nameAndLocation),
m_ctx( ctx ),
m_parent( parent )
{}
bool TrackerBase::isComplete() const {
return m_runState == CompletedSuccessfully || m_runState == Failed;
}
bool TrackerBase::isSuccessfullyCompleted() const {
return m_runState == CompletedSuccessfully;
}
bool TrackerBase::isOpen() const {
return m_runState != NotStarted && !isComplete();
}
bool TrackerBase::hasChildren() const {
return !m_children.empty();
}
void TrackerBase::addChild( ITrackerPtr const& child ) {
m_children.push_back( child );
}
ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
auto it = std::find_if( m_children.begin(), m_children.end(),
[&nameAndLocation]( ITrackerPtr const& tracker ){
return
tracker->nameAndLocation().location == nameAndLocation.location &&
tracker->nameAndLocation().name == nameAndLocation.name;
} );
return( it != m_children.end() )
? *it
: nullptr;
}
ITracker& TrackerBase::parent() {
assert( m_parent ); // Should always be non-null except for root
return *m_parent;
}
void TrackerBase::openChild() {
if( m_runState != ExecutingChildren ) {
m_runState = ExecutingChildren;
if( m_parent )
m_parent->openChild();
}
}
bool TrackerBase::isSectionTracker() const { return false; }
bool TrackerBase::isGeneratorTracker() const { return false; }
void TrackerBase::open() {
m_runState = Executing;
moveToThis();
if( m_parent )
m_parent->openChild();
}
void TrackerBase::close() {
// Close any still open children (e.g. generators)
while( &m_ctx.currentTracker() != this )
m_ctx.currentTracker().close();
switch( m_runState ) {
case NeedsAnotherRun:
break;
case Executing:
m_runState = CompletedSuccessfully;
break;
case ExecutingChildren:
if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
m_runState = CompletedSuccessfully;
break;
case NotStarted:
case CompletedSuccessfully:
case Failed:
CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
default:
CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
}
moveToParent();
m_ctx.completeCycle();
}
void TrackerBase::fail() {
m_runState = Failed;
if( m_parent )
m_parent->markAsNeedingAnotherRun();
moveToParent();
m_ctx.completeCycle();
}
void TrackerBase::markAsNeedingAnotherRun() {
m_runState = NeedsAnotherRun;
}
void TrackerBase::moveToParent() {
assert( m_parent );
m_ctx.setCurrentTracker( m_parent );
}
void TrackerBase::moveToThis() {
m_ctx.setCurrentTracker( this );
}
SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
: TrackerBase( nameAndLocation, ctx, parent ),
m_trimmed_name(trim(nameAndLocation.name))
{
if( parent ) {
while( !parent->isSectionTracker() )
parent = &parent->parent();
SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
addNextFilters( parentSection.m_filters );
}
}
bool SectionTracker::isComplete() const {
bool complete = true;
if (m_filters.empty()
|| m_filters[0] == ""
|| std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
complete = TrackerBase::isComplete();
}
return complete;
}
bool SectionTracker::isSectionTracker() const { return true; }
SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
std::shared_ptr<SectionTracker> section;
ITracker& currentTracker = ctx.currentTracker();
if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
assert( childTracker );
assert( childTracker->isSectionTracker() );
section = std::static_pointer_cast<SectionTracker>( childTracker );
}
else {
section = std::make_shared<SectionTracker>( nameAndLocation, ctx, ¤tTracker );
currentTracker.addChild( section );
}
if( !ctx.completedCycle() )
section->tryOpen();
return *section;
}
void SectionTracker::tryOpen() {
if( !isComplete() )
open();
}
void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
if( !filters.empty() ) {
m_filters.reserve( m_filters.size() + filters.size() + 2 );
m_filters.emplace_back(""); // Root - should never be consulted
m_filters.emplace_back(""); // Test Case - not a section filter
m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
}
}
void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
if( filters.size() > 1 )
m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
}
std::vector<std::string> const& SectionTracker::getFilters() const {
return m_filters;
}
std::string const& SectionTracker::trimmedName() const {
return m_trimmed_name;
}
} // namespace TestCaseTracking
using TestCaseTracking::ITracker;
using TestCaseTracking::TrackerContext;
using TestCaseTracking::SectionTracker;
} // namespace Catch
#if defined(__clang__)
# pragma clang diagnostic pop
#endif
// end catch_test_case_tracker.cpp
// start catch_test_registry.cpp
namespace Catch {
auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
}
NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
CATCH_TRY {
getMutableRegistryHub()
.registerTest(
makeTestCase(
invoker,
extractClassName( classOrMethod ),
nameAndTags,
lineInfo));
} CATCH_CATCH_ALL {
// Do not throw when constructing global objects, instead register the exception to be processed later
getMutableRegistryHub().registerStartupException();
}
}
AutoReg::~AutoReg() = default;
}
// end catch_test_registry.cpp
// start catch_test_spec.cpp
#include <algorithm>
#include <string>
#include <vector>
#include <memory>
namespace Catch {
TestSpec::Pattern::Pattern( std::string const& name )
: m_name( name )
{}
TestSpec::Pattern::~Pattern() = default;
std::string const& TestSpec::Pattern::name() const {
return m_name;
}
TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
: Pattern( filterString )
, m_wildcardPattern( toLower( name ), CaseSensitive::No )
{}
bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
return m_wildcardPattern.matches( testCase.name );
}
TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
: Pattern( filterString )
, m_tag( toLower( tag ) )
{}
bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
return std::find(begin(testCase.lcaseTags),
end(testCase.lcaseTags),
m_tag) != end(testCase.lcaseTags);
}
TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
: Pattern( underlyingPattern->name() )
, m_underlyingPattern( underlyingPattern )
{}
bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
return !m_underlyingPattern->matches( testCase );
}
bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
}
std::string TestSpec::Filter::name() const {
std::string name;
for( auto const& p : m_patterns )
name += p->name();
return name;
}
bool TestSpec::hasFilters() const {
return !m_filters.empty();
}
bool TestSpec::matches( TestCaseInfo const& testCase ) const {
return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
}
TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
{
Matches matches( m_filters.size() );
std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
std::vector<TestCase const*> currentMatches;
for( auto const& test : testCases )
if( isThrowSafe( test, config ) && filter.matches( test ) )
currentMatches.emplace_back( &test );
return FilterMatch{ filter.name(), currentMatches };
} );
return matches;
}
const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{
return (m_invalidArgs);
}
}
// end catch_test_spec.cpp
// start catch_test_spec_parser.cpp
namespace Catch {
TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
m_mode = None;
m_exclusion = false;
m_arg = m_tagAliases->expandAliases( arg );
m_escapeChars.clear();
m_substring.reserve(m_arg.size());
m_patternName.reserve(m_arg.size());
m_realPatternPos = 0;
for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
//if visitChar fails
if( !visitChar( m_arg[m_pos] ) ){
m_testSpec.m_invalidArgs.push_back(arg);
break;
}
endMode();
return *this;
}
TestSpec TestSpecParser::testSpec() {
addFilter();
return m_testSpec;
}
bool TestSpecParser::visitChar( char c ) {
if( (m_mode != EscapedName) && (c == '\\') ) {
escape();
addCharToPattern(c);
return true;
}else if((m_mode != EscapedName) && (c == ',') ) {
return separate();
}
switch( m_mode ) {
case None:
if( processNoneChar( c ) )
return true;
break;
case Name:
processNameChar( c );
break;
case EscapedName:
endMode();
addCharToPattern(c);
return true;
default:
case Tag:
case QuotedName:
if( processOtherChar( c ) )
return true;
break;
}
m_substring += c;
if( !isControlChar( c ) ) {
m_patternName += c;
m_realPatternPos++;
}
return true;
}
// Two of the processing methods return true to signal the caller to return
// without adding the given character to the current pattern strings
bool TestSpecParser::processNoneChar( char c ) {
switch( c ) {
case ' ':
return true;
case '~':
m_exclusion = true;
return false;
case '[':
startNewMode( Tag );
return false;
case '"':
startNewMode( QuotedName );
return false;
default:
startNewMode( Name );
return false;
}
}
void TestSpecParser::processNameChar( char c ) {
if( c == '[' ) {
if( m_substring == "exclude:" )
m_exclusion = true;
else
endMode();
startNewMode( Tag );
}
}
bool TestSpecParser::processOtherChar( char c ) {
if( !isControlChar( c ) )
return false;
m_substring += c;
endMode();
return true;
}
void TestSpecParser::startNewMode( Mode mode ) {
m_mode = mode;
}
void TestSpecParser::endMode() {
switch( m_mode ) {
case Name:
case QuotedName:
return addNamePattern();
case Tag:
return addTagPattern();
case EscapedName:
revertBackToLastMode();
return;
case None:
default:
return startNewMode( None );
}
}
void TestSpecParser::escape() {
saveLastMode();
m_mode = EscapedName;
m_escapeChars.push_back(m_realPatternPos);
}
bool TestSpecParser::isControlChar( char c ) const {
switch( m_mode ) {
default:
return false;
case None:
return c == '~';
case Name:
return c == '[';
case EscapedName:
return true;
case QuotedName:
return c == '"';
case Tag:
return c == '[' || c == ']';
}
}
void TestSpecParser::addFilter() {
if( !m_currentFilter.m_patterns.empty() ) {
m_testSpec.m_filters.push_back( m_currentFilter );
m_currentFilter = TestSpec::Filter();
}
}
void TestSpecParser::saveLastMode() {
lastMode = m_mode;
}
void TestSpecParser::revertBackToLastMode() {
m_mode = lastMode;
}
bool TestSpecParser::separate() {
if( (m_mode==QuotedName) || (m_mode==Tag) ){
//invalid argument, signal failure to previous scope.
m_mode = None;
m_pos = m_arg.size();
m_substring.clear();
m_patternName.clear();
m_realPatternPos = 0;
return false;
}
endMode();
addFilter();
return true; //success
}
std::string TestSpecParser::preprocessPattern() {
std::string token = m_patternName;
for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
m_escapeChars.clear();
if (startsWith(token, "exclude:")) {
m_exclusion = true;
token = token.substr(8);
}
m_patternName.clear();
m_realPatternPos = 0;
return token;
}
void TestSpecParser::addNamePattern() {
auto token = preprocessPattern();
if (!token.empty()) {
TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
if (m_exclusion)
pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
m_currentFilter.m_patterns.push_back(pattern);
}
m_substring.clear();
m_exclusion = false;
m_mode = None;
}
void TestSpecParser::addTagPattern() {
auto token = preprocessPattern();
if (!token.empty()) {
// If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
// we have to create a separate hide tag and shorten the real one
if (token.size() > 1 && token[0] == '.') {
token.erase(token.begin());
TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
if (m_exclusion) {
pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
}
m_currentFilter.m_patterns.push_back(pattern);
}
TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
if (m_exclusion) {
pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
}
m_currentFilter.m_patterns.push_back(pattern);
}
m_substring.clear();
m_exclusion = false;
m_mode = None;
}
TestSpec parseTestSpec( std::string const& arg ) {
return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
}
} // namespace Catch
// end catch_test_spec_parser.cpp
// start catch_timer.cpp
#include <chrono>
static const uint64_t nanosecondsInSecond = 1000000000;
namespace Catch {
auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
}
namespace {
auto estimateClockResolution() -> uint64_t {
uint64_t sum = 0;
static const uint64_t iterations = 1000000;
auto startTime = getCurrentNanosecondsSinceEpoch();
for( std::size_t i = 0; i < iterations; ++i ) {
uint64_t ticks;
uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
do {
ticks = getCurrentNanosecondsSinceEpoch();
} while( ticks == baseTicks );
auto delta = ticks - baseTicks;
sum += delta;
// If we have been calibrating for over 3 seconds -- the clock
// is terrible and we should move on.
// TBD: How to signal that the measured resolution is probably wrong?
if (ticks > startTime + 3 * nanosecondsInSecond) {
return sum / ( i + 1u );
}
}
// We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
// - and potentially do more iterations if there's a high variance.
return sum/iterations;
}
}
auto getEstimatedClockResolution() -> uint64_t {
static auto s_resolution = estimateClockResolution();
return s_resolution;
}
void Timer::start() {
m_nanoseconds = getCurrentNanosecondsSinceEpoch();
}
auto Timer::getElapsedNanoseconds() const -> uint64_t {
return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
}
auto Timer::getElapsedMicroseconds() const -> uint64_t {
return getElapsedNanoseconds()/1000;
}
auto Timer::getElapsedMilliseconds() const -> unsigned int {
return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
}
auto Timer::getElapsedSeconds() const -> double {
return getElapsedMicroseconds()/1000000.0;
}
} // namespace Catch
// end catch_timer.cpp
// start catch_tostring.cpp
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wexit-time-destructors"
# pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
// Enable specific decls locally
#if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
#endif
#include <cmath>
#include <iomanip>
namespace Catch {
namespace Detail {
const std::string unprintableString = "{?}";
namespace {
const int hexThreshold = 255;
struct Endianness {
enum Arch { Big, Little };
static Arch which() {
int one = 1;
// If the lowest byte we read is non-zero, we can assume
// that little endian format is used.
auto value = *reinterpret_cast<char*>(&one);
return value ? Little : Big;
}
};
}
std::string rawMemoryToString( const void *object, std::size_t size ) {
// Reverse order for little endian architectures
int i = 0, end = static_cast<int>( size ), inc = 1;
if( Endianness::which() == Endianness::Little ) {
i = end-1;
end = inc = -1;
}
unsigned char const *bytes = static_cast<unsigned char const *>(object);
ReusableStringStream rss;
rss << "0x" << std::setfill('0') << std::hex;
for( ; i != end; i += inc )
rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
return rss.str();
}
}
template<typename T>
std::string fpToString( T value, int precision ) {
if (Catch::isnan(value)) {
return "nan";
}
ReusableStringStream rss;
rss << std::setprecision( precision )
<< std::fixed
<< value;
std::string d = rss.str();
std::size_t i = d.find_last_not_of( '0' );
if( i != std::string::npos && i != d.size()-1 ) {
if( d[i] == '.' )
i++;
d = d.substr( 0, i+1 );
}
return d;
}
//// ======================================================= ////
//
// Out-of-line defs for full specialization of StringMaker
//
//// ======================================================= ////
std::string StringMaker<std::string>::convert(const std::string& str) {
if (!getCurrentContext().getConfig()->showInvisibles()) {
return '"' + str + '"';
}
std::string s("\"");
for (char c : str) {
switch (c) {
case '\n':
s.append("\\n");
break;
case '\t':
s.append("\\t");
break;
default:
s.push_back(c);
break;
}
}
s.append("\"");
return s;
}
#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
std::string StringMaker<std::string_view>::convert(std::string_view str) {
return ::Catch::Detail::stringify(std::string{ str });
}
#endif
std::string StringMaker<char const*>::convert(char const* str) {
if (str) {
return ::Catch::Detail::stringify(std::string{ str });
} else {
return{ "{null string}" };
}
}
std::string StringMaker<char*>::convert(char* str) {
if (str) {
return ::Catch::Detail::stringify(std::string{ str });
} else {
return{ "{null string}" };
}
}
#ifdef CATCH_CONFIG_WCHAR
std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
std::string s;
s.reserve(wstr.size());
for (auto c : wstr) {
s += (c <= 0xff) ? static_cast<char>(c) : '?';
}
return ::Catch::Detail::stringify(s);
}
# ifdef CATCH_CONFIG_CPP17_STRING_VIEW
std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
return StringMaker<std::wstring>::convert(std::wstring(str));
}
# endif
std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
if (str) {
return ::Catch::Detail::stringify(std::wstring{ str });
} else {
return{ "{null string}" };
}
}
std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
if (str) {
return ::Catch::Detail::stringify(std::wstring{ str });
} else {
return{ "{null string}" };
}
}
#endif
#if defined(CATCH_CONFIG_CPP17_BYTE)
#include <cstddef>
std::string StringMaker<std::byte>::convert(std::byte value) {
return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
}
#endif // defined(CATCH_CONFIG_CPP17_BYTE)
std::string StringMaker<int>::convert(int value) {
return ::Catch::Detail::stringify(static_cast<long long>(value));
}
std::string StringMaker<long>::convert(long value) {
return ::Catch::Detail::stringify(static_cast<long long>(value));
}
std::string StringMaker<long long>::convert(long long value) {
ReusableStringStream rss;
rss << value;
if (value > Detail::hexThreshold) {
rss << " (0x" << std::hex << value << ')';
}
return rss.str();
}
std::string StringMaker<unsigned int>::convert(unsigned int value) {
return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
}
std::string StringMaker<unsigned long>::convert(unsigned long value) {
return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
}
std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
ReusableStringStream rss;
rss << value;
if (value > Detail::hexThreshold) {
rss << " (0x" << std::hex << value << ')';
}
return rss.str();
}
std::string StringMaker<bool>::convert(bool b) {
return b ? "true" : "false";
}
std::string StringMaker<signed char>::convert(signed char value) {
if (value == '\r') {
return "'\\r'";
} else if (value == '\f') {
return "'\\f'";
} else if (value == '\n') {
return "'\\n'";
} else if (value == '\t') {
return "'\\t'";
} else if ('\0' <= value && value < ' ') {
return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
} else {
char chstr[] = "' '";
chstr[1] = value;
return chstr;
}
}
std::string StringMaker<char>::convert(char c) {
return ::Catch::Detail::stringify(static_cast<signed char>(c));
}
std::string StringMaker<unsigned char>::convert(unsigned char c) {
return ::Catch::Detail::stringify(static_cast<char>(c));
}
std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
return "nullptr";
}
int StringMaker<float>::precision = 5;
std::string StringMaker<float>::convert(float value) {
return fpToString(value, precision) + 'f';
}
int StringMaker<double>::precision = 10;
std::string StringMaker<double>::convert(double value) {
return fpToString(value, precision);
}
std::string ratio_string<std::atto>::symbol() { return "a"; }
std::string ratio_string<std::femto>::symbol() { return "f"; }
std::string ratio_string<std::pico>::symbol() { return "p"; }
std::string ratio_string<std::nano>::symbol() { return "n"; }
std::string ratio_string<std::micro>::symbol() { return "u"; }
std::string ratio_string<std::milli>::symbol() { return "m"; }
} // end namespace Catch
#if defined(__clang__)
# pragma clang diagnostic pop
#endif
// end catch_tostring.cpp
// start catch_totals.cpp
namespace Catch {
Counts Counts::operator - ( Counts const& other ) const {
Counts diff;
diff.passed = passed - other.passed;
diff.failed = failed - other.failed;
diff.failedButOk = failedButOk - other.failedButOk;
return diff;
}
Counts& Counts::operator += ( Counts const& other ) {
passed += other.passed;
failed += other.failed;
failedButOk += other.failedButOk;
return *this;
}
std::size_t Counts::total() const {
return passed + failed + failedButOk;
}
bool Counts::allPassed() const {
return failed == 0 && failedButOk == 0;
}
bool Counts::allOk() const {
return failed == 0;
}
Totals Totals::operator - ( Totals const& other ) const {
Totals diff;
diff.assertions = assertions - other.assertions;
diff.testCases = testCases - other.testCases;
return diff;
}
Totals& Totals::operator += ( Totals const& other ) {
assertions += other.assertions;
testCases += other.testCases;
return *this;
}
Totals Totals::delta( Totals const& prevTotals ) const {
Totals diff = *this - prevTotals;
if( diff.assertions.failed > 0 )
++diff.testCases.failed;
else if( diff.assertions.failedButOk > 0 )
++diff.testCases.failedButOk;
else
++diff.testCases.passed;
return diff;
}
}
// end catch_totals.cpp
// start catch_uncaught_exceptions.cpp
// start catch_config_uncaught_exceptions.hpp
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
#ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
#define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
#if defined(_MSC_VER)
# if _MSC_VER >= 1900 // Visual Studio 2015 or newer
# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
# endif
#endif
#include <exception>
#if defined(__cpp_lib_uncaught_exceptions) \
&& !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
#endif // __cpp_lib_uncaught_exceptions
#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
&& !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
&& !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
# define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
#endif
#endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
// end catch_config_uncaught_exceptions.hpp
#include <exception>
namespace Catch {
bool uncaught_exceptions() {
#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
return false;
#elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
return std::uncaught_exceptions() > 0;
#else
return std::uncaught_exception();
#endif
}
} // end namespace Catch
// end catch_uncaught_exceptions.cpp
// start catch_version.cpp
#include <ostream>
namespace Catch {
Version::Version
( unsigned int _majorVersion,
unsigned int _minorVersion,
unsigned int _patchNumber,
char const * const _branchName,
unsigned int _buildNumber )
: majorVersion( _majorVersion ),
minorVersion( _minorVersion ),
patchNumber( _patchNumber ),
branchName( _branchName ),
buildNumber( _buildNumber )
{}
std::ostream& operator << ( std::ostream& os, Version const& version ) {
os << version.majorVersion << '.'
<< version.minorVersion << '.'
<< version.patchNumber;
// branchName is never null -> 0th char is \0 if it is empty
if (version.branchName[0]) {
os << '-' << version.branchName
<< '.' << version.buildNumber;
}
return os;
}
Version const& libraryVersion() {
static Version version( 2, 13, 3, "", 0 );
return version;
}
}
// end catch_version.cpp
// start catch_wildcard_pattern.cpp
namespace Catch {
WildcardPattern::WildcardPattern( std::string const& pattern,
CaseSensitive::Choice caseSensitivity )
: m_caseSensitivity( caseSensitivity ),
m_pattern( normaliseString( pattern ) )
{
if( startsWith( m_pattern, '*' ) ) {
m_pattern = m_pattern.substr( 1 );
m_wildcard = WildcardAtStart;
}
if( endsWith( m_pattern, '*' ) ) {
m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
}
}
bool WildcardPattern::matches( std::string const& str ) const {
switch( m_wildcard ) {
case NoWildcard:
return m_pattern == normaliseString( str );
case WildcardAtStart:
return endsWith( normaliseString( str ), m_pattern );
case WildcardAtEnd:
return startsWith( normaliseString( str ), m_pattern );
case WildcardAtBothEnds:
return contains( normaliseString( str ), m_pattern );
default:
CATCH_INTERNAL_ERROR( "Unknown enum" );
}
}
std::string WildcardPattern::normaliseString( std::string const& str ) const {
return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
}
}
// end catch_wildcard_pattern.cpp
// start catch_xmlwriter.cpp
#include <iomanip>
#include <type_traits>
namespace Catch {
namespace {
size_t trailingBytes(unsigned char c) {
if ((c & 0xE0) == 0xC0) {
return 2;
}
if ((c & 0xF0) == 0xE0) {
return 3;
}
if ((c & 0xF8) == 0xF0) {
return 4;
}
CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
}
uint32_t headerValue(unsigned char c) {
if ((c & 0xE0) == 0xC0) {
return c & 0x1F;
}
if ((c & 0xF0) == 0xE0) {
return c & 0x0F;
}
if ((c & 0xF8) == 0xF0) {
return c & 0x07;
}
CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
}
void hexEscapeChar(std::ostream& os, unsigned char c) {
std::ios_base::fmtflags f(os.flags());
os << "\\x"
<< std::uppercase << std::hex << std::setfill('0') << std::setw(2)
<< static_cast<int>(c);
os.flags(f);
}
bool shouldNewline(XmlFormatting fmt) {
return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
}
bool shouldIndent(XmlFormatting fmt) {
return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
}
} // anonymous namespace
XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
return static_cast<XmlFormatting>(
static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
);
}
XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
return static_cast<XmlFormatting>(
static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
);
}
XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
: m_str( str ),
m_forWhat( forWhat )
{}
void XmlEncode::encodeTo( std::ostream& os ) const {
// Apostrophe escaping not necessary if we always use " to write attributes
// (see: http://www.w3.org/TR/xml/#syntax)
for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
unsigned char c = m_str[idx];
switch (c) {
case '<': os << "<"; break;
case '&': os << "&"; break;
case '>':
// See: http://www.w3.org/TR/xml/#syntax
if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
os << ">";
else
os << c;
break;
case '\"':
if (m_forWhat == ForAttributes)
os << """;
else
os << c;
break;
default:
// Check for control characters and invalid utf-8
// Escape control characters in standard ascii
// see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
hexEscapeChar(os, c);
break;
}
// Plain ASCII: Write it to stream
if (c < 0x7F) {
os << c;
break;
}
// UTF-8 territory
// Check if the encoding is valid and if it is not, hex escape bytes.
// Important: We do not check the exact decoded values for validity, only the encoding format
// First check that this bytes is a valid lead byte:
// This means that it is not encoded as 1111 1XXX
// Or as 10XX XXXX
if (c < 0xC0 ||
c >= 0xF8) {
hexEscapeChar(os, c);
break;
}
auto encBytes = trailingBytes(c);
// Are there enough bytes left to avoid accessing out-of-bounds memory?
if (idx + encBytes - 1 >= m_str.size()) {
hexEscapeChar(os, c);
break;
}
// The header is valid, check data
// The next encBytes bytes must together be a valid utf-8
// This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
bool valid = true;
uint32_t value = headerValue(c);
for (std::size_t n = 1; n < encBytes; ++n) {
unsigned char nc = m_str[idx + n];
valid &= ((nc & 0xC0) == 0x80);
value = (value << 6) | (nc & 0x3F);
}
if (
// Wrong bit pattern of following bytes
(!valid) ||
// Overlong encodings
(value < 0x80) ||
(0x80 <= value && value < 0x800 && encBytes > 2) ||
(0x800 < value && value < 0x10000 && encBytes > 3) ||
// Encoded value out of range
(value >= 0x110000)
) {
hexEscapeChar(os, c);
break;
}
// If we got here, this is in fact a valid(ish) utf-8 sequence
for (std::size_t n = 0; n < encBytes; ++n) {
os << m_str[idx + n];
}
idx += encBytes - 1;
break;
}
}
}
std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
xmlEncode.encodeTo( os );
return os;
}
XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
: m_writer( writer ),
m_fmt(fmt)
{}
XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
: m_writer( other.m_writer ),
m_fmt(other.m_fmt)
{
other.m_writer = nullptr;
other.m_fmt = XmlFormatting::None;
}
XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
if ( m_writer ) {
m_writer->endElement();
}
m_writer = other.m_writer;
other.m_writer = nullptr;
m_fmt = other.m_fmt;
other.m_fmt = XmlFormatting::None;
return *this;
}
XmlWriter::ScopedElement::~ScopedElement() {
if (m_writer) {
m_writer->endElement(m_fmt);
}
}
XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {
m_writer->writeText( text, fmt );
return *this;
}
XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
{
writeDeclaration();
}
XmlWriter::~XmlWriter() {
while (!m_tags.empty()) {
endElement();
}
newlineIfNecessary();
}
XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
ensureTagClosed();
newlineIfNecessary();
if (shouldIndent(fmt)) {
m_os << m_indent;
m_indent += " ";
}
m_os << '<' << name;
m_tags.push_back( name );
m_tagIsOpen = true;
applyFormatting(fmt);
return *this;
}
XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
ScopedElement scoped( this, fmt );
startElement( name, fmt );
return scoped;
}
XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
m_indent = m_indent.substr(0, m_indent.size() - 2);
if( m_tagIsOpen ) {
m_os << "/>";
m_tagIsOpen = false;
} else {
newlineIfNecessary();
if (shouldIndent(fmt)) {
m_os << m_indent;
}
m_os << "</" << m_tags.back() << ">";
}
m_os << std::flush;
applyFormatting(fmt);
m_tags.pop_back();
return *this;
}
XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
if( !name.empty() && !attribute.empty() )
m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
return *this;
}
XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
return *this;
}
XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {
if( !text.empty() ){
bool tagWasOpen = m_tagIsOpen;
ensureTagClosed();
if (tagWasOpen && shouldIndent(fmt)) {
m_os << m_indent;
}
m_os << XmlEncode( text );
applyFormatting(fmt);
}
return *this;
}
XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {
ensureTagClosed();
if (shouldIndent(fmt)) {
m_os << m_indent;
}
m_os << "<!--" << text << "-->";
applyFormatting(fmt);
return *this;
}
void XmlWriter::writeStylesheetRef( std::string const& url ) {
m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
}
XmlWriter& XmlWriter::writeBlankLine() {
ensureTagClosed();
m_os << '\n';
return *this;
}
void XmlWriter::ensureTagClosed() {
if( m_tagIsOpen ) {
m_os << '>' << std::flush;
newlineIfNecessary();
m_tagIsOpen = false;
}
}
void XmlWriter::applyFormatting(XmlFormatting fmt) {
m_needsNewline = shouldNewline(fmt);
}
void XmlWriter::writeDeclaration() {
m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
}
void XmlWriter::newlineIfNecessary() {
if( m_needsNewline ) {
m_os << std::endl;
m_needsNewline = false;
}
}
}
// end catch_xmlwriter.cpp
// start catch_reporter_bases.cpp
#include <cstring>
#include <cfloat>
#include <cstdio>
#include <cassert>
#include <memory>
namespace Catch {
void prepareExpandedExpression(AssertionResult& result) {
result.getExpandedExpression();
}
// Because formatting using c++ streams is stateful, drop down to C is required
// Alternatively we could use stringstream, but its performance is... not good.
std::string getFormattedDuration( double duration ) {
// Max exponent + 1 is required to represent the whole part
// + 1 for decimal point
// + 3 for the 3 decimal places
// + 1 for null terminator
const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
char buffer[maxDoubleSize];
// Save previous errno, to prevent sprintf from overwriting it
ErrnoGuard guard;
#ifdef _MSC_VER
sprintf_s(buffer, "%.3f", duration);
#else
std::sprintf(buffer, "%.3f", duration);
#endif
return std::string(buffer);
}
bool shouldShowDuration( IConfig const& config, double duration ) {
if ( config.showDurations() == ShowDurations::Always ) {
return true;
}
if ( config.showDurations() == ShowDurations::Never ) {
return false;
}
const double min = config.minDuration();
return min >= 0 && duration >= min;
}
std::string serializeFilters( std::vector<std::string> const& container ) {
ReusableStringStream oss;
bool first = true;
for (auto&& filter : container)
{
if (!first)
oss << ' ';
else
first = false;
oss << filter;
}
return oss.str();
}
TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
:StreamingReporterBase(_config) {}
std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
}
void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
return false;
}
} // end namespace Catch
// end catch_reporter_bases.cpp
// start catch_reporter_compact.cpp
namespace {
#ifdef CATCH_PLATFORM_MAC
const char* failedString() { return "FAILED"; }
const char* passedString() { return "PASSED"; }
#else
const char* failedString() { return "failed"; }
const char* passedString() { return "passed"; }
#endif
// Colour::LightGrey
Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
std::string bothOrAll( std::size_t count ) {
return count == 1 ? std::string() :
count == 2 ? "both " : "all " ;
}
} // anon namespace
namespace Catch {
namespace {
// Colour, message variants:
// - white: No tests ran.
// - red: Failed [both/all] N test cases, failed [both/all] M assertions.
// - white: Passed [both/all] N test cases (no assertions).
// - red: Failed N tests cases, failed M assertions.
// - green: Passed [both/all] N tests cases with M assertions.
void printTotals(std::ostream& out, const Totals& totals) {
if (totals.testCases.total() == 0) {
out << "No tests ran.";
} else if (totals.testCases.failed == totals.testCases.total()) {
Colour colour(Colour::ResultError);
const std::string qualify_assertions_failed =
totals.assertions.failed == totals.assertions.total() ?
bothOrAll(totals.assertions.failed) : std::string();
out <<
"Failed " << bothOrAll(totals.testCases.failed)
<< pluralise(totals.testCases.failed, "test case") << ", "
"failed " << qualify_assertions_failed <<
pluralise(totals.assertions.failed, "assertion") << '.';
} else if (totals.assertions.total() == 0) {
out <<
"Passed " << bothOrAll(totals.testCases.total())
<< pluralise(totals.testCases.total(), "test case")
<< " (no assertions).";
} else if (totals.assertions.failed) {
Colour colour(Colour::ResultError);
out <<
"Failed " << pluralise(totals.testCases.failed, "test case") << ", "
"failed " << pluralise(totals.assertions.failed, "assertion") << '.';
} else {
Colour colour(Colour::ResultSuccess);
out <<
"Passed " << bothOrAll(totals.testCases.passed)
<< pluralise(totals.testCases.passed, "test case") <<
" with " << pluralise(totals.assertions.passed, "assertion") << '.';
}
}
// Implementation of CompactReporter formatting
class AssertionPrinter {
public:
AssertionPrinter& operator= (AssertionPrinter const&) = delete;
AssertionPrinter(AssertionPrinter const&) = delete;
AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
: stream(_stream)
, result(_stats.assertionResult)
, messages(_stats.infoMessages)
, itMessage(_stats.infoMessages.begin())
, printInfoMessages(_printInfoMessages) {}
void print() {
printSourceInfo();
itMessage = messages.begin();
switch (result.getResultType()) {
case ResultWas::Ok:
printResultType(Colour::ResultSuccess, passedString());
printOriginalExpression();
printReconstructedExpression();
if (!result.hasExpression())
printRemainingMessages(Colour::None);
else
printRemainingMessages();
break;
case ResultWas::ExpressionFailed:
if (result.isOk())
printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
else
printResultType(Colour::Error, failedString());
printOriginalExpression();
printReconstructedExpression();
printRemainingMessages();
break;
case ResultWas::ThrewException:
printResultType(Colour::Error, failedString());
printIssue("unexpected exception with message:");
printMessage();
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::FatalErrorCondition:
printResultType(Colour::Error, failedString());
printIssue("fatal error condition with message:");
printMessage();
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::DidntThrowException:
printResultType(Colour::Error, failedString());
printIssue("expected exception, got none");
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::Info:
printResultType(Colour::None, "info");
printMessage();
printRemainingMessages();
break;
case ResultWas::Warning:
printResultType(Colour::None, "warning");
printMessage();
printRemainingMessages();
break;
case ResultWas::ExplicitFailure:
printResultType(Colour::Error, failedString());
printIssue("explicitly");
printRemainingMessages(Colour::None);
break;
// These cases are here to prevent compiler warnings
case ResultWas::Unknown:
case ResultWas::FailureBit:
case ResultWas::Exception:
printResultType(Colour::Error, "** internal error **");
break;
}
}
private:
void printSourceInfo() const {
Colour colourGuard(Colour::FileName);
stream << result.getSourceInfo() << ':';
}
void printResultType(Colour::Code colour, std::string const& passOrFail) const {
if (!passOrFail.empty()) {
{
Colour colourGuard(colour);
stream << ' ' << passOrFail;
}
stream << ':';
}
}
void printIssue(std::string const& issue) const {
stream << ' ' << issue;
}
void printExpressionWas() {
if (result.hasExpression()) {
stream << ';';
{
Colour colour(dimColour());
stream << " expression was:";
}
printOriginalExpression();
}
}
void printOriginalExpression() const {
if (result.hasExpression()) {
stream << ' ' << result.getExpression();
}
}
void printReconstructedExpression() const {
if (result.hasExpandedExpression()) {
{
Colour colour(dimColour());
stream << " for: ";
}
stream << result.getExpandedExpression();
}
}
void printMessage() {
if (itMessage != messages.end()) {
stream << " '" << itMessage->message << '\'';
++itMessage;
}
}
void printRemainingMessages(Colour::Code colour = dimColour()) {
if (itMessage == messages.end())
return;
const auto itEnd = messages.cend();
const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
{
Colour colourGuard(colour);
stream << " with " << pluralise(N, "message") << ':';
}
while (itMessage != itEnd) {
// If this assertion is a warning ignore any INFO messages
if (printInfoMessages || itMessage->type != ResultWas::Info) {
printMessage();
if (itMessage != itEnd) {
Colour colourGuard(dimColour());
stream << " and";
}
continue;
}
++itMessage;
}
}
private:
std::ostream& stream;
AssertionResult const& result;
std::vector<MessageInfo> messages;
std::vector<MessageInfo>::const_iterator itMessage;
bool printInfoMessages;
};
} // anon namespace
std::string CompactReporter::getDescription() {
return "Reports test results on a single line, suitable for IDEs";
}
void CompactReporter::noMatchingTestCases( std::string const& spec ) {
stream << "No test cases matched '" << spec << '\'' << std::endl;
}
void CompactReporter::assertionStarting( AssertionInfo const& ) {}
bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
AssertionResult const& result = _assertionStats.assertionResult;
bool printInfoMessages = true;
// Drop out if result was successful and we're not printing those
if( !m_config->includeSuccessfulResults() && result.isOk() ) {
if( result.getResultType() != ResultWas::Warning )
return false;
printInfoMessages = false;
}
AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
printer.print();
stream << std::endl;
return true;
}
void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
double dur = _sectionStats.durationInSeconds;
if ( shouldShowDuration( *m_config, dur ) ) {
stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl;
}
}
void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
printTotals( stream, _testRunStats.totals );
stream << '\n' << std::endl;
StreamingReporterBase::testRunEnded( _testRunStats );
}
CompactReporter::~CompactReporter() {}
CATCH_REGISTER_REPORTER( "compact", CompactReporter )
} // end namespace Catch
// end catch_reporter_compact.cpp
// start catch_reporter_console.cpp
#include <cfloat>
#include <cstdio>
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
// Note that 4062 (not all labels are handled and default is missing) is enabled
#endif
#if defined(__clang__)
# pragma clang diagnostic push
// For simplicity, benchmarking-only helpers are always enabled
# pragma clang diagnostic ignored "-Wunused-function"
#endif
namespace Catch {
namespace {
// Formatter impl for ConsoleReporter
class ConsoleAssertionPrinter {
public:
ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
: stream(_stream),
stats(_stats),
result(_stats.assertionResult),
colour(Colour::None),
message(result.getMessage()),
messages(_stats.infoMessages),
printInfoMessages(_printInfoMessages) {
switch (result.getResultType()) {
case ResultWas::Ok:
colour = Colour::Success;
passOrFail = "PASSED";
//if( result.hasMessage() )
if (_stats.infoMessages.size() == 1)
messageLabel = "with message";
if (_stats.infoMessages.size() > 1)
messageLabel = "with messages";
break;
case ResultWas::ExpressionFailed:
if (result.isOk()) {
colour = Colour::Success;
passOrFail = "FAILED - but was ok";
} else {
colour = Colour::Error;
passOrFail = "FAILED";
}
if (_stats.infoMessages.size() == 1)
messageLabel = "with message";
if (_stats.infoMessages.size() > 1)
messageLabel = "with messages";
break;
case ResultWas::ThrewException:
colour = Colour::Error;
passOrFail = "FAILED";
messageLabel = "due to unexpected exception with ";
if (_stats.infoMessages.size() == 1)
messageLabel += "message";
if (_stats.infoMessages.size() > 1)
messageLabel += "messages";
break;
case ResultWas::FatalErrorCondition:
colour = Colour::Error;
passOrFail = "FAILED";
messageLabel = "due to a fatal error condition";
break;
case ResultWas::DidntThrowException:
colour = Colour::Error;
passOrFail = "FAILED";
messageLabel = "because no exception was thrown where one was expected";
break;
case ResultWas::Info:
messageLabel = "info";
break;
case ResultWas::Warning:
messageLabel = "warning";
break;
case ResultWas::ExplicitFailure:
passOrFail = "FAILED";
colour = Colour::Error;
if (_stats.infoMessages.size() == 1)
messageLabel = "explicitly with message";
if (_stats.infoMessages.size() > 1)
messageLabel = "explicitly with messages";
break;
// These cases are here to prevent compiler warnings
case ResultWas::Unknown:
case ResultWas::FailureBit:
case ResultWas::Exception:
passOrFail = "** internal error **";
colour = Colour::Error;
break;
}
}
void print() const {
printSourceInfo();
if (stats.totals.assertions.total() > 0) {
printResultType();
printOriginalExpression();
printReconstructedExpression();
} else {
stream << '\n';
}
printMessage();
}
private:
void printResultType() const {
if (!passOrFail.empty()) {
Colour colourGuard(colour);
stream << passOrFail << ":\n";
}
}
void printOriginalExpression() const {
if (result.hasExpression()) {
Colour colourGuard(Colour::OriginalExpression);
stream << " ";
stream << result.getExpressionInMacro();
stream << '\n';
}
}
void printReconstructedExpression() const {
if (result.hasExpandedExpression()) {
stream << "with expansion:\n";
Colour colourGuard(Colour::ReconstructedExpression);
stream << Column(result.getExpandedExpression()).indent(2) << '\n';
}
}
void printMessage() const {
if (!messageLabel.empty())
stream << messageLabel << ':' << '\n';
for (auto const& msg : messages) {
// If this assertion is a warning ignore any INFO messages
if (printInfoMessages || msg.type != ResultWas::Info)
stream << Column(msg.message).indent(2) << '\n';
}
}
void printSourceInfo() const {
Colour colourGuard(Colour::FileName);
stream << result.getSourceInfo() << ": ";
}
std::ostream& stream;
AssertionStats const& stats;
AssertionResult const& result;
Colour::Code colour;
std::string passOrFail;
std::string messageLabel;
std::string message;
std::vector<MessageInfo> messages;
bool printInfoMessages;
};
std::size_t makeRatio(std::size_t number, std::size_t total) {
std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
return (ratio == 0 && number > 0) ? 1 : ratio;
}
std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
if (i > j && i > k)
return i;
else if (j > k)
return j;
else
return k;
}
struct ColumnInfo {
enum Justification { Left, Right };
std::string name;
int width;
Justification justification;
};
struct ColumnBreak {};
struct RowBreak {};
class Duration {
enum class Unit {
Auto,
Nanoseconds,
Microseconds,
Milliseconds,
Seconds,
Minutes
};
static const uint64_t s_nanosecondsInAMicrosecond = 1000;
static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
double m_inNanoseconds;
Unit m_units;
public:
explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
: m_inNanoseconds(inNanoseconds),
m_units(units) {
if (m_units == Unit::Auto) {
if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
m_units = Unit::Nanoseconds;
else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
m_units = Unit::Microseconds;
else if (m_inNanoseconds < s_nanosecondsInASecond)
m_units = Unit::Milliseconds;
else if (m_inNanoseconds < s_nanosecondsInAMinute)
m_units = Unit::Seconds;
else
m_units = Unit::Minutes;
}
}
auto value() const -> double {
switch (m_units) {
case Unit::Microseconds:
return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
case Unit::Milliseconds:
return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
case Unit::Seconds:
return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
case Unit::Minutes:
return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
default:
return m_inNanoseconds;
}
}
auto unitsAsString() const -> std::string {
switch (m_units) {
case Unit::Nanoseconds:
return "ns";
case Unit::Microseconds:
return "us";
case Unit::Milliseconds:
return "ms";
case Unit::Seconds:
return "s";
case Unit::Minutes:
return "m";
default:
return "** internal error **";
}
}
friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
return os << duration.value() << ' ' << duration.unitsAsString();
}
};
} // end anon namespace
class TablePrinter {
std::ostream& m_os;
std::vector<ColumnInfo> m_columnInfos;
std::ostringstream m_oss;
int m_currentColumn = -1;
bool m_isOpen = false;
public:
TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
: m_os( os ),
m_columnInfos( std::move( columnInfos ) ) {}
auto columnInfos() const -> std::vector<ColumnInfo> const& {
return m_columnInfos;
}
void open() {
if (!m_isOpen) {
m_isOpen = true;
*this << RowBreak();
Columns headerCols;
Spacer spacer(2);
for (auto const& info : m_columnInfos) {
headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
headerCols += spacer;
}
m_os << headerCols << '\n';
m_os << Catch::getLineOfChars<'-'>() << '\n';
}
}
void close() {
if (m_isOpen) {
*this << RowBreak();
m_os << std::endl;
m_isOpen = false;
}
}
template<typename T>
friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
tp.m_oss << value;
return tp;
}
friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
auto colStr = tp.m_oss.str();
const auto strSize = colStr.size();
tp.m_oss.str("");
tp.open();
if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
tp.m_currentColumn = -1;
tp.m_os << '\n';
}
tp.m_currentColumn++;
auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
? std::string(colInfo.width - (strSize + 1), ' ')
: std::string();
if (colInfo.justification == ColumnInfo::Left)
tp.m_os << colStr << padding << ' ';
else
tp.m_os << padding << colStr << ' ';
return tp;
}
friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
if (tp.m_currentColumn > 0) {
tp.m_os << '\n';
tp.m_currentColumn = -1;
}
return tp;
}
};
ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
: StreamingReporterBase(config),
m_tablePrinter(new TablePrinter(config.stream(),
[&config]() -> std::vector<ColumnInfo> {
if (config.fullConfig()->benchmarkNoAnalysis())
{
return{
{ "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
{ " samples", 14, ColumnInfo::Right },
{ " iterations", 14, ColumnInfo::Right },
{ " mean", 14, ColumnInfo::Right }
};
}
else
{
return{
{ "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
{ "samples mean std dev", 14, ColumnInfo::Right },
{ "iterations low mean low std dev", 14, ColumnInfo::Right },
{ "estimated high mean high std dev", 14, ColumnInfo::Right }
};
}
}())) {}
ConsoleReporter::~ConsoleReporter() = default;
std::string ConsoleReporter::getDescription() {
return "Reports test results as plain lines of text";
}
void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
stream << "No test cases matched '" << spec << '\'' << std::endl;
}
void ConsoleReporter::reportInvalidArguments(std::string const&arg){
stream << "Invalid Filter: " << arg << std::endl;
}
void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
AssertionResult const& result = _assertionStats.assertionResult;
bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
// Drop out if result was successful but we're not printing them.
if (!includeResults && result.getResultType() != ResultWas::Warning)
return false;
lazyPrint();
ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
printer.print();
stream << std::endl;
return true;
}
void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
m_tablePrinter->close();
m_headerPrinted = false;
StreamingReporterBase::sectionStarting(_sectionInfo);
}
void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
m_tablePrinter->close();
if (_sectionStats.missingAssertions) {
lazyPrint();
Colour colour(Colour::ResultError);
if (m_sectionStack.size() > 1)
stream << "\nNo assertions in section";
else
stream << "\nNo assertions in test case";
stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
}
double dur = _sectionStats.durationInSeconds;
if (shouldShowDuration(*m_config, dur)) {
stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
}
if (m_headerPrinted) {
m_headerPrinted = false;
}
StreamingReporterBase::sectionEnded(_sectionStats);
}
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
void ConsoleReporter::benchmarkPreparing(std::string const& name) {
lazyPrintWithoutClosingBenchmarkTable();
auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
bool firstLine = true;
for (auto line : nameCol) {
if (!firstLine)
(*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
else
firstLine = false;
(*m_tablePrinter) << line << ColumnBreak();
}
}
void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
(*m_tablePrinter) << info.samples << ColumnBreak()
<< info.iterations << ColumnBreak();
if (!m_config->benchmarkNoAnalysis())
(*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
}
void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
if (m_config->benchmarkNoAnalysis())
{
(*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
}
else
{
(*m_tablePrinter) << ColumnBreak()
<< Duration(stats.mean.point.count()) << ColumnBreak()
<< Duration(stats.mean.lower_bound.count()) << ColumnBreak()
<< Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
<< Duration(stats.standardDeviation.point.count()) << ColumnBreak()
<< Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
<< Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
}
}
void ConsoleReporter::benchmarkFailed(std::string const& error) {
Colour colour(Colour::Red);
(*m_tablePrinter)
<< "Benchmark failed (" << error << ')'
<< ColumnBreak() << RowBreak();
}
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
m_tablePrinter->close();
StreamingReporterBase::testCaseEnded(_testCaseStats);
m_headerPrinted = false;
}
void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
if (currentGroupInfo.used) {
printSummaryDivider();
stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
printTotals(_testGroupStats.totals);
stream << '\n' << std::endl;
}
StreamingReporterBase::testGroupEnded(_testGroupStats);
}
void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
printTotalsDivider(_testRunStats.totals);
printTotals(_testRunStats.totals);
stream << std::endl;
StreamingReporterBase::testRunEnded(_testRunStats);
}
void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
StreamingReporterBase::testRunStarting(_testInfo);
printTestFilters();
}
void ConsoleReporter::lazyPrint() {
m_tablePrinter->close();
lazyPrintWithoutClosingBenchmarkTable();
}
void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
if (!currentTestRunInfo.used)
lazyPrintRunInfo();
if (!currentGroupInfo.used)
lazyPrintGroupInfo();
if (!m_headerPrinted) {
printTestCaseAndSectionHeader();
m_headerPrinted = true;
}
}
void ConsoleReporter::lazyPrintRunInfo() {
stream << '\n' << getLineOfChars<'~'>() << '\n';
Colour colour(Colour::SecondaryText);
stream << currentTestRunInfo->name
<< " is a Catch v" << libraryVersion() << " host application.\n"
<< "Run with -? for options\n\n";
if (m_config->rngSeed() != 0)
stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
currentTestRunInfo.used = true;
}
void ConsoleReporter::lazyPrintGroupInfo() {
if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
printClosedHeader("Group: " + currentGroupInfo->name);
currentGroupInfo.used = true;
}
}
void ConsoleReporter::printTestCaseAndSectionHeader() {
assert(!m_sectionStack.empty());
printOpenHeader(currentTestCaseInfo->name);
if (m_sectionStack.size() > 1) {
Colour colourGuard(Colour::Headers);
auto
it = m_sectionStack.begin() + 1, // Skip first section (test case)
itEnd = m_sectionStack.end();
for (; it != itEnd; ++it)
printHeaderString(it->name, 2);
}
SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
stream << getLineOfChars<'-'>() << '\n';
Colour colourGuard(Colour::FileName);
stream << lineInfo << '\n';
stream << getLineOfChars<'.'>() << '\n' << std::endl;
}
void ConsoleReporter::printClosedHeader(std::string const& _name) {
printOpenHeader(_name);
stream << getLineOfChars<'.'>() << '\n';
}
void ConsoleReporter::printOpenHeader(std::string const& _name) {
stream << getLineOfChars<'-'>() << '\n';
{
Colour colourGuard(Colour::Headers);
printHeaderString(_name);
}
}
// if string has a : in first line will set indent to follow it on
// subsequent lines
void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
std::size_t i = _string.find(": ");
if (i != std::string::npos)
i += 2;
else
i = 0;
stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
}
struct SummaryColumn {
SummaryColumn( std::string _label, Colour::Code _colour )
: label( std::move( _label ) ),
colour( _colour ) {}
SummaryColumn addRow( std::size_t count ) {
ReusableStringStream rss;
rss << count;
std::string row = rss.str();
for (auto& oldRow : rows) {
while (oldRow.size() < row.size())
oldRow = ' ' + oldRow;
while (oldRow.size() > row.size())
row = ' ' + row;
}
rows.push_back(row);
return *this;
}
std::string label;
Colour::Code colour;
std::vector<std::string> rows;
};
void ConsoleReporter::printTotals( Totals const& totals ) {
if (totals.testCases.total() == 0) {
stream << Colour(Colour::Warning) << "No tests ran\n";
} else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
stream << Colour(Colour::ResultSuccess) << "All tests passed";
stream << " ("
<< pluralise(totals.assertions.passed, "assertion") << " in "
<< pluralise(totals.testCases.passed, "test case") << ')'
<< '\n';
} else {
std::vector<SummaryColumn> columns;
columns.push_back(SummaryColumn("", Colour::None)
.addRow(totals.testCases.total())
.addRow(totals.assertions.total()));
columns.push_back(SummaryColumn("passed", Colour::Success)
.addRow(totals.testCases.passed)
.addRow(totals.assertions.passed));
columns.push_back(SummaryColumn("failed", Colour::ResultError)
.addRow(totals.testCases.failed)
.addRow(totals.assertions.failed));
columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
.addRow(totals.testCases.failedButOk)
.addRow(totals.assertions.failedButOk));
printSummaryRow("test cases", columns, 0);
printSummaryRow("assertions", columns, 1);
}
}
void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
for (auto col : cols) {
std::string value = col.rows[row];
if (col.label.empty()) {
stream << label << ": ";
if (value != "0")
stream << value;
else
stream << Colour(Colour::Warning) << "- none -";
} else if (value != "0") {
stream << Colour(Colour::LightGrey) << " | ";
stream << Colour(col.colour)
<< value << ' ' << col.label;
}
}
stream << '\n';
}
void ConsoleReporter::printTotalsDivider(Totals const& totals) {
if (totals.testCases.total() > 0) {
std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
findMax(failedRatio, failedButOkRatio, passedRatio)++;
while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
findMax(failedRatio, failedButOkRatio, passedRatio)--;
stream << Colour(Colour::Error) << std::string(failedRatio, '=');
stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
if (totals.testCases.allPassed())
stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
else
stream << Colour(Colour::Success) << std::string(passedRatio, '=');
} else {
stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
}
stream << '\n';
}
void ConsoleReporter::printSummaryDivider() {
stream << getLineOfChars<'-'>() << '\n';
}
void ConsoleReporter::printTestFilters() {
if (m_config->testSpec().hasFilters()) {
Colour guard(Colour::BrightYellow);
stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
}
}
CATCH_REGISTER_REPORTER("console", ConsoleReporter)
} // end namespace Catch
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#if defined(__clang__)
# pragma clang diagnostic pop
#endif
// end catch_reporter_console.cpp
// start catch_reporter_junit.cpp
#include <cassert>
#include <sstream>
#include <ctime>
#include <algorithm>
namespace Catch {
namespace {
std::string getCurrentTimestamp() {
// Beware, this is not reentrant because of backward compatibility issues
// Also, UTC only, again because of backward compatibility (%z is C++11)
time_t rawtime;
std::time(&rawtime);
auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
#ifdef _MSC_VER
std::tm timeInfo = {};
gmtime_s(&timeInfo, &rawtime);
#else
std::tm* timeInfo;
timeInfo = std::gmtime(&rawtime);
#endif
char timeStamp[timeStampSize];
const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
#ifdef _MSC_VER
std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
#else
std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
#endif
return std::string(timeStamp);
}
std::string fileNameTag(const std::vector<std::string> &tags) {
auto it = std::find_if(begin(tags),
end(tags),
[] (std::string const& tag) {return tag.front() == '#'; });
if (it != tags.end())
return it->substr(1);
return std::string();
}
} // anonymous namespace
JunitReporter::JunitReporter( ReporterConfig const& _config )
: CumulativeReporterBase( _config ),
xml( _config.stream() )
{
m_reporterPrefs.shouldRedirectStdOut = true;
m_reporterPrefs.shouldReportAllAssertions = true;
}
JunitReporter::~JunitReporter() {}
std::string JunitReporter::getDescription() {
return "Reports test results in an XML format that looks like Ant's junitreport target";
}
void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
CumulativeReporterBase::testRunStarting( runInfo );
xml.startElement( "testsuites" );
}
void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
suiteTimer.start();
stdOutForSuite.clear();
stdErrForSuite.clear();
unexpectedExceptions = 0;
CumulativeReporterBase::testGroupStarting( groupInfo );
}
void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
m_okToFail = testCaseInfo.okToFail();
}
bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
unexpectedExceptions++;
return CumulativeReporterBase::assertionEnded( assertionStats );
}
void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
stdOutForSuite += testCaseStats.stdOut;
stdErrForSuite += testCaseStats.stdErr;
CumulativeReporterBase::testCaseEnded( testCaseStats );
}
void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
double suiteTime = suiteTimer.getElapsedSeconds();
CumulativeReporterBase::testGroupEnded( testGroupStats );
writeGroup( *m_testGroups.back(), suiteTime );
}
void JunitReporter::testRunEndedCumulative() {
xml.endElement();
}
void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
TestGroupStats const& stats = groupNode.value;
xml.writeAttribute( "name", stats.groupInfo.name );
xml.writeAttribute( "errors", unexpectedExceptions );
xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
xml.writeAttribute( "tests", stats.totals.assertions.total() );
xml.writeAttribute( "hostname", "tbd" ); // !TBD
if( m_config->showDurations() == ShowDurations::Never )
xml.writeAttribute( "time", "" );
else
xml.writeAttribute( "time", suiteTime );
xml.writeAttribute( "timestamp", getCurrentTimestamp() );
// Write properties if there are any
if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
auto properties = xml.scopedElement("properties");
if (m_config->hasTestFilters()) {
xml.scopedElement("property")
.writeAttribute("name", "filters")
.writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
}
if (m_config->rngSeed() != 0) {
xml.scopedElement("property")
.writeAttribute("name", "random-seed")
.writeAttribute("value", m_config->rngSeed());
}
}
// Write test cases
for( auto const& child : groupNode.children )
writeTestCase( *child );
xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
}
void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
TestCaseStats const& stats = testCaseNode.value;
// All test cases have exactly one section - which represents the
// test case itself. That section may have 0-n nested sections
assert( testCaseNode.children.size() == 1 );
SectionNode const& rootSection = *testCaseNode.children.front();
std::string className = stats.testInfo.className;
if( className.empty() ) {
className = fileNameTag(stats.testInfo.tags);
if ( className.empty() )
className = "global";
}
if ( !m_config->name().empty() )
className = m_config->name() + "." + className;
writeSection( className, "", rootSection );
}
void JunitReporter::writeSection( std::string const& className,
std::string const& rootName,
SectionNode const& sectionNode ) {
std::string name = trim( sectionNode.stats.sectionInfo.name );
if( !rootName.empty() )
name = rootName + '/' + name;
if( !sectionNode.assertions.empty() ||
!sectionNode.stdOut.empty() ||
!sectionNode.stdErr.empty() ) {
XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
if( className.empty() ) {
xml.writeAttribute( "classname", name );
xml.writeAttribute( "name", "root" );
}
else {
xml.writeAttribute( "classname", className );
xml.writeAttribute( "name", name );
}
xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
// This is not ideal, but it should be enough to mimic gtest's
// junit output.
// Ideally the JUnit reporter would also handle `skipTest`
// events and write those out appropriately.
xml.writeAttribute( "status", "run" );
writeAssertions( sectionNode );
if( !sectionNode.stdOut.empty() )
xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
if( !sectionNode.stdErr.empty() )
xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
}
for( auto const& childNode : sectionNode.childSections )
if( className.empty() )
writeSection( name, "", *childNode );
else
writeSection( className, name, *childNode );
}
void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
for( auto const& assertion : sectionNode.assertions )
writeAssertion( assertion );
}
void JunitReporter::writeAssertion( AssertionStats const& stats ) {
AssertionResult const& result = stats.assertionResult;
if( !result.isOk() ) {
std::string elementName;
switch( result.getResultType() ) {
case ResultWas::ThrewException:
case ResultWas::FatalErrorCondition:
elementName = "error";
break;
case ResultWas::ExplicitFailure:
case ResultWas::ExpressionFailed:
case ResultWas::DidntThrowException:
elementName = "failure";
break;
// We should never see these here:
case ResultWas::Info:
case ResultWas::Warning:
case ResultWas::Ok:
case ResultWas::Unknown:
case ResultWas::FailureBit:
case ResultWas::Exception:
elementName = "internalError";
break;
}
XmlWriter::ScopedElement e = xml.scopedElement( elementName );
xml.writeAttribute( "message", result.getExpression() );
xml.writeAttribute( "type", result.getTestMacroName() );
ReusableStringStream rss;
if (stats.totals.assertions.total() > 0) {
rss << "FAILED" << ":\n";
if (result.hasExpression()) {
rss << " ";
rss << result.getExpressionInMacro();
rss << '\n';
}
if (result.hasExpandedExpression()) {
rss << "with expansion:\n";
rss << Column(result.getExpandedExpression()).indent(2) << '\n';
}
} else {
rss << '\n';
}
if( !result.getMessage().empty() )
rss << result.getMessage() << '\n';
for( auto const& msg : stats.infoMessages )
if( msg.type == ResultWas::Info )
rss << msg.message << '\n';
rss << "at " << result.getSourceInfo();
xml.writeText( rss.str(), XmlFormatting::Newline );
}
}
CATCH_REGISTER_REPORTER( "junit", JunitReporter )
} // end namespace Catch
// end catch_reporter_junit.cpp
// start catch_reporter_listening.cpp
#include <cassert>
namespace Catch {
ListeningReporter::ListeningReporter() {
// We will assume that listeners will always want all assertions
m_preferences.shouldReportAllAssertions = true;
}
void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
m_listeners.push_back( std::move( listener ) );
}
void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
m_reporter = std::move( reporter );
m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
}
ReporterPreferences ListeningReporter::getPreferences() const {
return m_preferences;
}
std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
return std::set<Verbosity>{ };
}
void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
for ( auto const& listener : m_listeners ) {
listener->noMatchingTestCases( spec );
}
m_reporter->noMatchingTestCases( spec );
}
void ListeningReporter::reportInvalidArguments(std::string const&arg){
for ( auto const& listener : m_listeners ) {
listener->reportInvalidArguments( arg );
}
m_reporter->reportInvalidArguments( arg );
}
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
void ListeningReporter::benchmarkPreparing( std::string const& name ) {
for (auto const& listener : m_listeners) {
listener->benchmarkPreparing(name);
}
m_reporter->benchmarkPreparing(name);
}
void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
for ( auto const& listener : m_listeners ) {
listener->benchmarkStarting( benchmarkInfo );
}
m_reporter->benchmarkStarting( benchmarkInfo );
}
void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
for ( auto const& listener : m_listeners ) {
listener->benchmarkEnded( benchmarkStats );
}
m_reporter->benchmarkEnded( benchmarkStats );
}
void ListeningReporter::benchmarkFailed( std::string const& error ) {
for (auto const& listener : m_listeners) {
listener->benchmarkFailed(error);
}
m_reporter->benchmarkFailed(error);
}
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
for ( auto const& listener : m_listeners ) {
listener->testRunStarting( testRunInfo );
}
m_reporter->testRunStarting( testRunInfo );
}
void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
for ( auto const& listener : m_listeners ) {
listener->testGroupStarting( groupInfo );
}
m_reporter->testGroupStarting( groupInfo );
}
void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
for ( auto const& listener : m_listeners ) {
listener->testCaseStarting( testInfo );
}
m_reporter->testCaseStarting( testInfo );
}
void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
for ( auto const& listener : m_listeners ) {
listener->sectionStarting( sectionInfo );
}
m_reporter->sectionStarting( sectionInfo );
}
void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
for ( auto const& listener : m_listeners ) {
listener->assertionStarting( assertionInfo );
}
m_reporter->assertionStarting( assertionInfo );
}
// The return value indicates if the messages buffer should be cleared:
bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
for( auto const& listener : m_listeners ) {
static_cast<void>( listener->assertionEnded( assertionStats ) );
}
return m_reporter->assertionEnded( assertionStats );
}
void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
for ( auto const& listener : m_listeners ) {
listener->sectionEnded( sectionStats );
}
m_reporter->sectionEnded( sectionStats );
}
void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
for ( auto const& listener : m_listeners ) {
listener->testCaseEnded( testCaseStats );
}
m_reporter->testCaseEnded( testCaseStats );
}
void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
for ( auto const& listener : m_listeners ) {
listener->testGroupEnded( testGroupStats );
}
m_reporter->testGroupEnded( testGroupStats );
}
void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
for ( auto const& listener : m_listeners ) {
listener->testRunEnded( testRunStats );
}
m_reporter->testRunEnded( testRunStats );
}
void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
for ( auto const& listener : m_listeners ) {
listener->skipTest( testInfo );
}
m_reporter->skipTest( testInfo );
}
bool ListeningReporter::isMulti() const {
return true;
}
} // end namespace Catch
// end catch_reporter_listening.cpp
// start catch_reporter_xml.cpp
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
// Note that 4062 (not all labels are handled
// and default is missing) is enabled
#endif
namespace Catch {
XmlReporter::XmlReporter( ReporterConfig const& _config )
: StreamingReporterBase( _config ),
m_xml(_config.stream())
{
m_reporterPrefs.shouldRedirectStdOut = true;
m_reporterPrefs.shouldReportAllAssertions = true;
}
XmlReporter::~XmlReporter() = default;
std::string XmlReporter::getDescription() {
return "Reports test results as an XML document";
}
std::string XmlReporter::getStylesheetRef() const {
return std::string();
}
void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
m_xml
.writeAttribute( "filename", sourceInfo.file )
.writeAttribute( "line", sourceInfo.line );
}
void XmlReporter::noMatchingTestCases( std::string const& s ) {
StreamingReporterBase::noMatchingTestCases( s );
}
void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
StreamingReporterBase::testRunStarting( testInfo );
std::string stylesheetRef = getStylesheetRef();
if( !stylesheetRef.empty() )
m_xml.writeStylesheetRef( stylesheetRef );
m_xml.startElement( "Catch" );
if( !m_config->name().empty() )
m_xml.writeAttribute( "name", m_config->name() );
if (m_config->testSpec().hasFilters())
m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
if( m_config->rngSeed() != 0 )
m_xml.scopedElement( "Randomness" )
.writeAttribute( "seed", m_config->rngSeed() );
}
void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
StreamingReporterBase::testGroupStarting( groupInfo );
m_xml.startElement( "Group" )
.writeAttribute( "name", groupInfo.name );
}
void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
StreamingReporterBase::testCaseStarting(testInfo);
m_xml.startElement( "TestCase" )
.writeAttribute( "name", trim( testInfo.name ) )
.writeAttribute( "description", testInfo.description )
.writeAttribute( "tags", testInfo.tagsAsString() );
writeSourceInfo( testInfo.lineInfo );
if ( m_config->showDurations() == ShowDurations::Always )
m_testCaseTimer.start();
m_xml.ensureTagClosed();
}
void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
StreamingReporterBase::sectionStarting( sectionInfo );
if( m_sectionDepth++ > 0 ) {
m_xml.startElement( "Section" )
.writeAttribute( "name", trim( sectionInfo.name ) );
writeSourceInfo( sectionInfo.lineInfo );
m_xml.ensureTagClosed();
}
}
void XmlReporter::assertionStarting( AssertionInfo const& ) { }
bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
AssertionResult const& result = assertionStats.assertionResult;
bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
if( includeResults || result.getResultType() == ResultWas::Warning ) {
// Print any info messages in <Info> tags.
for( auto const& msg : assertionStats.infoMessages ) {
if( msg.type == ResultWas::Info && includeResults ) {
m_xml.scopedElement( "Info" )
.writeText( msg.message );
} else if ( msg.type == ResultWas::Warning ) {
m_xml.scopedElement( "Warning" )
.writeText( msg.message );
}
}
}
// Drop out if result was successful but we're not printing them.
if( !includeResults && result.getResultType() != ResultWas::Warning )
return true;
// Print the expression if there is one.
if( result.hasExpression() ) {
m_xml.startElement( "Expression" )
.writeAttribute( "success", result.succeeded() )
.writeAttribute( "type", result.getTestMacroName() );
writeSourceInfo( result.getSourceInfo() );
m_xml.scopedElement( "Original" )
.writeText( result.getExpression() );
m_xml.scopedElement( "Expanded" )
.writeText( result.getExpandedExpression() );
}
// And... Print a result applicable to each result type.
switch( result.getResultType() ) {
case ResultWas::ThrewException:
m_xml.startElement( "Exception" );
writeSourceInfo( result.getSourceInfo() );
m_xml.writeText( result.getMessage() );
m_xml.endElement();
break;
case ResultWas::FatalErrorCondition:
m_xml.startElement( "FatalErrorCondition" );
writeSourceInfo( result.getSourceInfo() );
m_xml.writeText( result.getMessage() );
m_xml.endElement();
break;
case ResultWas::Info:
m_xml.scopedElement( "Info" )
.writeText( result.getMessage() );
break;
case ResultWas::Warning:
// Warning will already have been written
break;
case ResultWas::ExplicitFailure:
m_xml.startElement( "Failure" );
writeSourceInfo( result.getSourceInfo() );
m_xml.writeText( result.getMessage() );
m_xml.endElement();
break;
default:
break;
}
if( result.hasExpression() )
m_xml.endElement();
return true;
}
void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
StreamingReporterBase::sectionEnded( sectionStats );
if( --m_sectionDepth > 0 ) {
XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
e.writeAttribute( "successes", sectionStats.assertions.passed );
e.writeAttribute( "failures", sectionStats.assertions.failed );
e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
if ( m_config->showDurations() == ShowDurations::Always )
e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
m_xml.endElement();
}
}
void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
StreamingReporterBase::testCaseEnded( testCaseStats );
XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
if ( m_config->showDurations() == ShowDurations::Always )
e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
if( !testCaseStats.stdOut.empty() )
m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
if( !testCaseStats.stdErr.empty() )
m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
m_xml.endElement();
}
void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
StreamingReporterBase::testGroupEnded( testGroupStats );
// TODO: Check testGroupStats.aborting and act accordingly.
m_xml.scopedElement( "OverallResults" )
.writeAttribute( "successes", testGroupStats.totals.assertions.passed )
.writeAttribute( "failures", testGroupStats.totals.assertions.failed )
.writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
m_xml.scopedElement( "OverallResultsCases")
.writeAttribute( "successes", testGroupStats.totals.testCases.passed )
.writeAttribute( "failures", testGroupStats.totals.testCases.failed )
.writeAttribute( "expectedFailures", testGroupStats.totals.testCases.failedButOk );
m_xml.endElement();
}
void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
StreamingReporterBase::testRunEnded( testRunStats );
m_xml.scopedElement( "OverallResults" )
.writeAttribute( "successes", testRunStats.totals.assertions.passed )
.writeAttribute( "failures", testRunStats.totals.assertions.failed )
.writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
m_xml.scopedElement( "OverallResultsCases")
.writeAttribute( "successes", testRunStats.totals.testCases.passed )
.writeAttribute( "failures", testRunStats.totals.testCases.failed )
.writeAttribute( "expectedFailures", testRunStats.totals.testCases.failedButOk );
m_xml.endElement();
}
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
void XmlReporter::benchmarkPreparing(std::string const& name) {
m_xml.startElement("BenchmarkResults")
.writeAttribute("name", name);
}
void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
m_xml.writeAttribute("samples", info.samples)
.writeAttribute("resamples", info.resamples)
.writeAttribute("iterations", info.iterations)
.writeAttribute("clockResolution", info.clockResolution)
.writeAttribute("estimatedDuration", info.estimatedDuration)
.writeComment("All values in nano seconds");
}
void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
m_xml.startElement("mean")
.writeAttribute("value", benchmarkStats.mean.point.count())
.writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
.writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
.writeAttribute("ci", benchmarkStats.mean.confidence_interval);
m_xml.endElement();
m_xml.startElement("standardDeviation")
.writeAttribute("value", benchmarkStats.standardDeviation.point.count())
.writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
.writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
.writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
m_xml.endElement();
m_xml.startElement("outliers")
.writeAttribute("variance", benchmarkStats.outlierVariance)
.writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
.writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
.writeAttribute("highMild", benchmarkStats.outliers.high_mild)
.writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
m_xml.endElement();
m_xml.endElement();
}
void XmlReporter::benchmarkFailed(std::string const &error) {
m_xml.scopedElement("failed").
writeAttribute("message", error);
m_xml.endElement();
}
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
CATCH_REGISTER_REPORTER( "xml", XmlReporter )
} // end namespace Catch
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
// end catch_reporter_xml.cpp
namespace Catch {
LeakDetector leakDetector;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// end catch_impl.hpp
#endif
#ifdef CATCH_CONFIG_MAIN
// start catch_default_main.hpp
#ifndef __OBJC__
#if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
// Standard C/C++ Win32 Unicode wmain entry point
extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
#else
// Standard C/C++ main entry point
int main (int argc, char * argv[]) {
#endif
return Catch::Session().run( argc, argv );
}
#else // __OBJC__
// Objective-C entry point
int main (int argc, char * const argv[]) {
#if !CATCH_ARC_ENABLED
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
#endif
Catch::registerTestMethods();
int result = Catch::Session().run( argc, (char**)argv );
#if !CATCH_ARC_ENABLED
[pool drain];
#endif
return result;
}
#endif // __OBJC__
// end catch_default_main.hpp
#endif
#if !defined(CATCH_CONFIG_IMPL_ONLY)
#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
# undef CLARA_CONFIG_MAIN
#endif
#if !defined(CATCH_CONFIG_DISABLE)
//////
// If this config identifier is defined then all CATCH macros are prefixed with CATCH_
#ifdef CATCH_CONFIG_PREFIX_ALL
#define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
#define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
#define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
#endif// CATCH_CONFIG_DISABLE_MATCHERS
#define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
#define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
#define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
#define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
#endif // CATCH_CONFIG_DISABLE_MATCHERS
#define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
#endif // CATCH_CONFIG_DISABLE_MATCHERS
#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
#define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
#define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
#define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
#define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
#define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
#define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
#define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
#else
#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
#endif
#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
#define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
#define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
#else
#define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
#define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
#endif
// "BDD-style" convenience wrappers
#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
#define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
#define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
#define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
#define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
#define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
#define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
#define CATCH_BENCHMARK(...) \
INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
#define CATCH_BENCHMARK_ADVANCED(name) \
INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
#else
#define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
#define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
#define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
#endif // CATCH_CONFIG_DISABLE_MATCHERS
#define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
#define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
#define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
#define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
#endif // CATCH_CONFIG_DISABLE_MATCHERS
#define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
#endif // CATCH_CONFIG_DISABLE_MATCHERS
#define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
#define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
#define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
#define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
#define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
#define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
#define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
#else
#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
#endif
#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
#define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
#define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
#else
#define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
#define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
#endif
#endif
#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
// "BDD-style" convenience wrappers
#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
#define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
#define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
#define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
#define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
#define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
#define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
#define BENCHMARK(...) \
INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
#define BENCHMARK_ADVANCED(name) \
INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
using Catch::Detail::Approx;
#else // CATCH_CONFIG_DISABLE
//////
// If this config identifier is defined then all CATCH macros are prefixed with CATCH_
#ifdef CATCH_CONFIG_PREFIX_ALL
#define CATCH_REQUIRE( ... ) (void)(0)
#define CATCH_REQUIRE_FALSE( ... ) (void)(0)
#define CATCH_REQUIRE_THROWS( ... ) (void)(0)
#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
#endif// CATCH_CONFIG_DISABLE_MATCHERS
#define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
#define CATCH_CHECK( ... ) (void)(0)
#define CATCH_CHECK_FALSE( ... ) (void)(0)
#define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
#define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
#define CATCH_CHECK_NOFAIL( ... ) (void)(0)
#define CATCH_CHECK_THROWS( ... ) (void)(0)
#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
#define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
#endif // CATCH_CONFIG_DISABLE_MATCHERS
#define CATCH_CHECK_NOTHROW( ... ) (void)(0)
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
#define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
#endif // CATCH_CONFIG_DISABLE_MATCHERS
#define CATCH_INFO( msg ) (void)(0)
#define CATCH_UNSCOPED_INFO( msg ) (void)(0)
#define CATCH_WARN( msg ) (void)(0)
#define CATCH_CAPTURE( msg ) (void)(0)
#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
#define CATCH_METHOD_AS_TEST_CASE( method, ... )
#define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
#define CATCH_SECTION( ... )
#define CATCH_DYNAMIC_SECTION( ... )
#define CATCH_FAIL( ... ) (void)(0)
#define CATCH_FAIL_CHECK( ... ) (void)(0)
#define CATCH_SUCCEED( ... ) (void)(0)
#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
#else
#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
#endif
// "BDD-style" convenience wrappers
#define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
#define CATCH_GIVEN( desc )
#define CATCH_AND_GIVEN( desc )
#define CATCH_WHEN( desc )
#define CATCH_AND_WHEN( desc )
#define CATCH_THEN( desc )
#define CATCH_AND_THEN( desc )
#define CATCH_STATIC_REQUIRE( ... ) (void)(0)
#define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
#else
#define REQUIRE( ... ) (void)(0)
#define REQUIRE_FALSE( ... ) (void)(0)
#define REQUIRE_THROWS( ... ) (void)(0)
#define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
#define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
#endif // CATCH_CONFIG_DISABLE_MATCHERS
#define REQUIRE_NOTHROW( ... ) (void)(0)
#define CHECK( ... ) (void)(0)
#define CHECK_FALSE( ... ) (void)(0)
#define CHECKED_IF( ... ) if (__VA_ARGS__)
#define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
#define CHECK_NOFAIL( ... ) (void)(0)
#define CHECK_THROWS( ... ) (void)(0)
#define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
#define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
#endif // CATCH_CONFIG_DISABLE_MATCHERS
#define CHECK_NOTHROW( ... ) (void)(0)
#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
#define CHECK_THAT( arg, matcher ) (void)(0)
#define REQUIRE_THAT( arg, matcher ) (void)(0)
#endif // CATCH_CONFIG_DISABLE_MATCHERS
#define INFO( msg ) (void)(0)
#define UNSCOPED_INFO( msg ) (void)(0)
#define WARN( msg ) (void)(0)
#define CAPTURE( msg ) (void)(0)
#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
#define METHOD_AS_TEST_CASE( method, ... )
#define REGISTER_TEST_CASE( Function, ... ) (void)(0)
#define SECTION( ... )
#define DYNAMIC_SECTION( ... )
#define FAIL( ... ) (void)(0)
#define FAIL_CHECK( ... ) (void)(0)
#define SUCCEED( ... ) (void)(0)
#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
#else
#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
#endif
#define STATIC_REQUIRE( ... ) (void)(0)
#define STATIC_REQUIRE_FALSE( ... ) (void)(0)
#endif
#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
// "BDD-style" convenience wrappers
#define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
#define GIVEN( desc )
#define AND_GIVEN( desc )
#define WHEN( desc )
#define AND_WHEN( desc )
#define THEN( desc )
#define AND_THEN( desc )
using Catch::Detail::Approx;
#endif
#endif // ! CATCH_CONFIG_IMPL_ONLY
// start catch_reenable_warnings.h
#ifdef __clang__
# ifdef __ICC // icpc defines the __clang__ macro
# pragma warning(pop)
# else
# pragma clang diagnostic pop
# endif
#elif defined __GNUC__
# pragma GCC diagnostic pop
#endif
// end catch_reenable_warnings.h
// end catch.hpp
#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
|
/*
* Copyright Andrey Semashev 2007 - 2014.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/*!
* \file windows_version.hpp
* \author Andrey Semashev
* \date 07.03.2009
*
* \brief This header is the Boost.Log library implementation, see the library documentation
* at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
*/
#ifndef BOOST_LOG_WINDOWS_VERSION_HPP_INCLUDED_
#define BOOST_LOG_WINDOWS_VERSION_HPP_INCLUDED_
#include <boost/log/detail/config.hpp>
#if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
#if defined(BOOST_LOG_USE_WINNT6_API)
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 // _WIN32_WINNT_LONGHORN
#endif
#elif !defined(_WIN32_WINNT)
// Use the default WinAPI version
#include <boost/detail/winapi/config.hpp>
#if !defined(_WIN32_WINNT)
#define _WIN32_WINNT BOOST_USE_WINAPI_VERSION
#endif
#endif // BOOST_LOG_USE_WINNT6_API
// This is to make Boost.ASIO happy
#ifndef __USE_W32_SOCKETS
#define __USE_W32_SOCKETS
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)
#endif // BOOST_LOG_WINDOWS_VERSION_HPP_INCLUDED_
|
//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// 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 <cstdint>
#include <memory>
#include "ngraph/axis_set.hpp"
#include "ngraph/builder/make_constant.hpp"
#include "ngraph/op/convert.hpp"
#include "ngraph/shape.hpp"
#include "ngraph/validation_util.hpp"
#include "onnx_import/core/null_node.hpp"
#include "onnx_import/default_opset.hpp"
#include "onnx_import/op/dequantize_linear.hpp"
#include "onnx_import/utils/common.hpp"
namespace ngraph
{
namespace onnx_import
{
namespace op
{
namespace
{
Output<ngraph::Node> get_zero_point(const OutputVector& inputs)
{
if (inputs.size() == 3 && !ngraph::op::is_null(inputs[2]))
{
auto zero_point = inputs[2];
if (zero_point.get_element_type() != element::f32)
{
zero_point =
std::make_shared<default_opset::Convert>(zero_point, element::f32);
}
return zero_point;
}
else
{
return default_opset::Constant::create(element::f32, Shape{}, {0});
}
}
}
namespace set_1
{
OutputVector dequantize_linear(const Node& node)
{
const OutputVector inputs{node.get_ng_inputs()};
NGRAPH_CHECK(
2 <= inputs.size() && inputs.size() <= 3,
"The DequantizeLinear op expects 2 required and one optional input. Got: ",
inputs.size());
const auto x = inputs[0];
const auto scale = inputs[1];
const auto zero_point = get_zero_point(inputs);
common::validate_scalar_input(
"Dequantization scale", scale.get_node_shared_ptr(), {element::f32});
common::validate_scalar_input("Zero point", zero_point.get_node_shared_ptr());
const auto converted_x =
std::make_shared<default_opset::Convert>(x, element::f32);
return {std::make_shared<default_opset::Multiply>(
std::make_shared<default_opset::Subtract>(converted_x, zero_point), scale)};
}
}
namespace set_13
{
namespace
{
void validate_scale(const Output<ngraph::Node> scale,
const Output<ngraph::Node> x,
const int64_t axis)
{
const auto& scale_shape = scale.get_partial_shape();
NGRAPH_CHECK(scale_shape.rank().get_length() == 0 ||
scale_shape.rank().get_length() == 1,
"Dequantization scale needs to be a scalar or a vector.");
if (scale_shape.rank().get_length() == 1)
{
const auto& scale_dim = scale_shape[0];
const auto& x_shape = x.get_partial_shape();
const auto& x_dim_at_axis = x_shape[axis];
NGRAPH_CHECK(scale_dim.same_scheme(x_dim_at_axis),
"The number of dequantization scale elements '",
scale_dim,
"' must match the input shape dimension '",
x_dim_at_axis,
" pointed to by the axis attribute: ",
axis);
}
}
void validate_zero_point(const Output<ngraph::Node> zero_point,
const Output<ngraph::Node> x,
const int64_t axis)
{
const auto& zero_point_shape = zero_point.get_partial_shape();
NGRAPH_CHECK(zero_point_shape.rank().get_length() == 0 ||
zero_point_shape.rank().get_length() == 1,
"Zero point needs to be a scalar or a vector.");
if (zero_point_shape.rank().get_length() == 1)
{
const auto& zero_point_dim = zero_point_shape[0];
const auto& x_shape = x.get_partial_shape();
const auto& x_dim_at_axis = x_shape[axis];
NGRAPH_CHECK(zero_point_dim.same_scheme(x_dim_at_axis),
"The number of zero point elements '",
zero_point_dim,
"' must match the input shape dimension '",
x_dim_at_axis,
" pointed to by the axis attribute: ",
axis);
}
}
std::shared_ptr<ngraph::Node> reshape_input(const Output<ngraph::Node> input,
const int64_t axis,
const PartialShape& x_shape)
{
std::vector<int64_t> target_dims;
for (size_t i = 0; i < axis; ++i)
{
target_dims.push_back(1);
}
// copy dimension at axis from input X
if (x_shape[axis].is_static())
{
target_dims.push_back(x_shape[axis].get_length());
}
else
{
target_dims.push_back(0);
}
for (size_t i = axis + 1; i < x_shape.rank().get_length(); ++i)
{
target_dims.push_back(1);
}
const auto target_shape = default_opset::Constant::create(
element::i64, Shape{target_dims.size()}, target_dims);
return std::make_shared<default_opset::Reshape>(input, target_shape, true);
}
}
OutputVector dequantize_linear(const Node& node)
{
const OutputVector inputs{node.get_ng_inputs()};
NGRAPH_CHECK(2 <= inputs.size() && inputs.size() <= 3,
"The DequantizeLinear op expects 2 required and one optional "
"input. Got: ",
inputs.size());
const auto x = inputs[0];
auto scale = inputs[1];
auto zero_point = get_zero_point(inputs);
const auto x_shape = x.get_partial_shape();
NGRAPH_CHECK(x_shape.rank().is_static(),
"Rank of the input data tensor has to be known (static).");
int64_t axis{node.get_attribute_value<int64_t>("axis", 1)};
axis = ngraph::normalize_axis(node.get_description(), axis, x_shape.rank());
validate_scale(scale, x, axis);
validate_zero_point(zero_point, x, axis);
// these reshapes make sure that dequantization happens over the specified axis
scale = reshape_input(scale, axis, x_shape);
zero_point = reshape_input(zero_point, axis, x_shape);
const auto converted_x =
std::make_shared<default_opset::Convert>(x, element::f32);
return {std::make_shared<default_opset::Multiply>(
std::make_shared<default_opset::Subtract>(converted_x, zero_point), scale)};
}
}
}
}
}
|
//===-- DumpDataExtractor.cpp ---------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/DumpDataExtractor.h"
#include "lldb/lldb-defines.h"
#include "lldb/lldb-forward.h"
#include "lldb/Core/Address.h"
#include "lldb/Core/Disassembler.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/ExecutionContextScope.h"
#include "lldb/Target/SectionLoadList.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Stream.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
#include <limits>
#include <memory>
#include <string>
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <math.h>
#include <bitset>
#include <sstream>
using namespace lldb_private;
using namespace lldb;
#define NON_PRINTABLE_CHAR '.'
static float half2float(uint16_t half) {
union {
float f;
uint32_t u;
} u;
int32_t v = (int16_t)half;
if (0 == (v & 0x7c00)) {
u.u = v & 0x80007FFFU;
return u.f * ldexpf(1, 125);
}
v <<= 13;
u.u = v | 0x70000000U;
return u.f * ldexpf(1, -112);
}
static llvm::Optional<llvm::APInt> GetAPInt(const DataExtractor &data,
lldb::offset_t *offset_ptr,
lldb::offset_t byte_size) {
if (byte_size == 0)
return llvm::None;
llvm::SmallVector<uint64_t, 2> uint64_array;
lldb::offset_t bytes_left = byte_size;
uint64_t u64;
const lldb::ByteOrder byte_order = data.GetByteOrder();
if (byte_order == lldb::eByteOrderLittle) {
while (bytes_left > 0) {
if (bytes_left >= 8) {
u64 = data.GetU64(offset_ptr);
bytes_left -= 8;
} else {
u64 = data.GetMaxU64(offset_ptr, (uint32_t)bytes_left);
bytes_left = 0;
}
uint64_array.push_back(u64);
}
return llvm::APInt(byte_size * 8, llvm::ArrayRef<uint64_t>(uint64_array));
} else if (byte_order == lldb::eByteOrderBig) {
lldb::offset_t be_offset = *offset_ptr + byte_size;
lldb::offset_t temp_offset;
while (bytes_left > 0) {
if (bytes_left >= 8) {
be_offset -= 8;
temp_offset = be_offset;
u64 = data.GetU64(&temp_offset);
bytes_left -= 8;
} else {
be_offset -= bytes_left;
temp_offset = be_offset;
u64 = data.GetMaxU64(&temp_offset, (uint32_t)bytes_left);
bytes_left = 0;
}
uint64_array.push_back(u64);
}
*offset_ptr += byte_size;
return llvm::APInt(byte_size * 8, llvm::ArrayRef<uint64_t>(uint64_array));
}
return llvm::None;
}
static lldb::offset_t DumpAPInt(Stream *s, const DataExtractor &data,
lldb::offset_t offset, lldb::offset_t byte_size,
bool is_signed, unsigned radix) {
llvm::Optional<llvm::APInt> apint = GetAPInt(data, &offset, byte_size);
if (apint.hasValue()) {
std::string apint_str(apint.getValue().toString(radix, is_signed));
switch (radix) {
case 2:
s->Write("0b", 2);
break;
case 8:
s->Write("0", 1);
break;
case 10:
break;
}
s->Write(apint_str.c_str(), apint_str.size());
}
return offset;
}
lldb::offset_t lldb_private::DumpDataExtractor(
const DataExtractor &DE, Stream *s, offset_t start_offset,
lldb::Format item_format, size_t item_byte_size, size_t item_count,
size_t num_per_line, uint64_t base_addr,
uint32_t item_bit_size, // If zero, this is not a bitfield value, if
// non-zero, the value is a bitfield
uint32_t item_bit_offset, // If "item_bit_size" is non-zero, this is the
// shift amount to apply to a bitfield
ExecutionContextScope *exe_scope) {
if (s == nullptr)
return start_offset;
if (item_format == eFormatPointer) {
if (item_byte_size != 4 && item_byte_size != 8)
item_byte_size = s->GetAddressByteSize();
}
offset_t offset = start_offset;
if (item_format == eFormatInstruction) {
TargetSP target_sp;
if (exe_scope)
target_sp = exe_scope->CalculateTarget();
if (target_sp) {
DisassemblerSP disassembler_sp(Disassembler::FindPlugin(
target_sp->GetArchitecture(),
target_sp->GetDisassemblyFlavor(), nullptr));
if (disassembler_sp) {
lldb::addr_t addr = base_addr + start_offset;
lldb_private::Address so_addr;
bool data_from_file = true;
if (target_sp->GetSectionLoadList().ResolveLoadAddress(addr, so_addr)) {
data_from_file = false;
} else {
if (target_sp->GetSectionLoadList().IsEmpty() ||
!target_sp->GetImages().ResolveFileAddress(addr, so_addr))
so_addr.SetRawAddress(addr);
}
size_t bytes_consumed = disassembler_sp->DecodeInstructions(
so_addr, DE, start_offset, item_count, false, data_from_file);
if (bytes_consumed) {
offset += bytes_consumed;
const bool show_address = base_addr != LLDB_INVALID_ADDRESS;
const bool show_bytes = true;
ExecutionContext exe_ctx;
exe_scope->CalculateExecutionContext(exe_ctx);
disassembler_sp->GetInstructionList().Dump(s, show_address,
show_bytes, &exe_ctx);
}
}
} else
s->Printf("invalid target");
return offset;
}
if ((item_format == eFormatOSType || item_format == eFormatAddressInfo) &&
item_byte_size > 8)
item_format = eFormatHex;
lldb::offset_t line_start_offset = start_offset;
for (uint32_t count = 0; DE.ValidOffset(offset) && count < item_count;
++count) {
if ((count % num_per_line) == 0) {
if (count > 0) {
if (item_format == eFormatBytesWithASCII &&
offset > line_start_offset) {
s->Printf("%*s",
static_cast<int>(
(num_per_line - (offset - line_start_offset)) * 3 + 2),
"");
DumpDataExtractor(DE, s, line_start_offset, eFormatCharPrintable, 1,
offset - line_start_offset, SIZE_MAX,
LLDB_INVALID_ADDRESS, 0, 0);
}
s->EOL();
}
if (base_addr != LLDB_INVALID_ADDRESS)
s->Printf("0x%8.8" PRIx64 ": ",
(uint64_t)(base_addr +
(offset - start_offset) / DE.getTargetByteSize()));
line_start_offset = offset;
} else if (item_format != eFormatChar &&
item_format != eFormatCharPrintable &&
item_format != eFormatCharArray && count > 0) {
s->PutChar(' ');
}
switch (item_format) {
case eFormatBoolean:
if (item_byte_size <= 8)
s->Printf("%s", DE.GetMaxU64Bitfield(&offset, item_byte_size,
item_bit_size, item_bit_offset)
? "true"
: "false");
else {
s->Printf("error: unsupported byte size (%" PRIu64
") for boolean format",
(uint64_t)item_byte_size);
return offset;
}
break;
case eFormatBinary:
if (item_byte_size <= 8) {
uint64_t uval64 = DE.GetMaxU64Bitfield(&offset, item_byte_size,
item_bit_size, item_bit_offset);
// Avoid std::bitset<64>::to_string() since it is missing in earlier
// C++ libraries
std::string binary_value(64, '0');
std::bitset<64> bits(uval64);
for (uint32_t i = 0; i < 64; ++i)
if (bits[i])
binary_value[64 - 1 - i] = '1';
if (item_bit_size > 0)
s->Printf("0b%s", binary_value.c_str() + 64 - item_bit_size);
else if (item_byte_size > 0 && item_byte_size <= 8)
s->Printf("0b%s", binary_value.c_str() + 64 - item_byte_size * 8);
} else {
const bool is_signed = false;
const unsigned radix = 2;
offset = DumpAPInt(s, DE, offset, item_byte_size, is_signed, radix);
}
break;
case eFormatBytes:
case eFormatBytesWithASCII:
for (uint32_t i = 0; i < item_byte_size; ++i) {
s->Printf("%2.2x", DE.GetU8(&offset));
}
// Put an extra space between the groups of bytes if more than one is
// being dumped in a group (item_byte_size is more than 1).
if (item_byte_size > 1)
s->PutChar(' ');
break;
case eFormatChar:
case eFormatCharPrintable:
case eFormatCharArray: {
// Reject invalid item_byte_size.
if (item_byte_size > 8) {
s->Printf("error: unsupported byte size (%" PRIu64 ") for char format",
(uint64_t)item_byte_size);
return offset;
}
// If we are only printing one character surround it with single quotes
if (item_count == 1 && item_format == eFormatChar)
s->PutChar('\'');
const uint64_t ch = DE.GetMaxU64Bitfield(&offset, item_byte_size,
item_bit_size, item_bit_offset);
if (isprint(ch))
s->Printf("%c", (char)ch);
else if (item_format != eFormatCharPrintable) {
switch (ch) {
case '\033':
s->Printf("\\e");
break;
case '\a':
s->Printf("\\a");
break;
case '\b':
s->Printf("\\b");
break;
case '\f':
s->Printf("\\f");
break;
case '\n':
s->Printf("\\n");
break;
case '\r':
s->Printf("\\r");
break;
case '\t':
s->Printf("\\t");
break;
case '\v':
s->Printf("\\v");
break;
case '\0':
s->Printf("\\0");
break;
default:
if (item_byte_size == 1)
s->Printf("\\x%2.2x", (uint8_t)ch);
else
s->Printf("%" PRIu64, ch);
break;
}
} else {
s->PutChar(NON_PRINTABLE_CHAR);
}
// If we are only printing one character surround it with single quotes
if (item_count == 1 && item_format == eFormatChar)
s->PutChar('\'');
} break;
case eFormatEnum: // Print enum value as a signed integer when we don't get
// the enum type
case eFormatDecimal:
if (item_byte_size <= 8)
s->Printf("%" PRId64,
DE.GetMaxS64Bitfield(&offset, item_byte_size, item_bit_size,
item_bit_offset));
else {
const bool is_signed = true;
const unsigned radix = 10;
offset = DumpAPInt(s, DE, offset, item_byte_size, is_signed, radix);
}
break;
case eFormatUnsigned:
if (item_byte_size <= 8)
s->Printf("%" PRIu64,
DE.GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size,
item_bit_offset));
else {
const bool is_signed = false;
const unsigned radix = 10;
offset = DumpAPInt(s, DE, offset, item_byte_size, is_signed, radix);
}
break;
case eFormatOctal:
if (item_byte_size <= 8)
s->Printf("0%" PRIo64,
DE.GetMaxS64Bitfield(&offset, item_byte_size, item_bit_size,
item_bit_offset));
else {
const bool is_signed = false;
const unsigned radix = 8;
offset = DumpAPInt(s, DE, offset, item_byte_size, is_signed, radix);
}
break;
case eFormatOSType: {
uint64_t uval64 = DE.GetMaxU64Bitfield(&offset, item_byte_size,
item_bit_size, item_bit_offset);
s->PutChar('\'');
for (uint32_t i = 0; i < item_byte_size; ++i) {
uint8_t ch = (uint8_t)(uval64 >> ((item_byte_size - i - 1) * 8));
if (isprint(ch))
s->Printf("%c", ch);
else {
switch (ch) {
case '\033':
s->Printf("\\e");
break;
case '\a':
s->Printf("\\a");
break;
case '\b':
s->Printf("\\b");
break;
case '\f':
s->Printf("\\f");
break;
case '\n':
s->Printf("\\n");
break;
case '\r':
s->Printf("\\r");
break;
case '\t':
s->Printf("\\t");
break;
case '\v':
s->Printf("\\v");
break;
case '\0':
s->Printf("\\0");
break;
default:
s->Printf("\\x%2.2x", ch);
break;
}
}
}
s->PutChar('\'');
} break;
case eFormatCString: {
const char *cstr = DE.GetCStr(&offset);
if (!cstr) {
s->Printf("NULL");
offset = LLDB_INVALID_OFFSET;
} else {
s->PutChar('\"');
while (const char c = *cstr) {
if (isprint(c)) {
s->PutChar(c);
} else {
switch (c) {
case '\033':
s->Printf("\\e");
break;
case '\a':
s->Printf("\\a");
break;
case '\b':
s->Printf("\\b");
break;
case '\f':
s->Printf("\\f");
break;
case '\n':
s->Printf("\\n");
break;
case '\r':
s->Printf("\\r");
break;
case '\t':
s->Printf("\\t");
break;
case '\v':
s->Printf("\\v");
break;
default:
s->Printf("\\x%2.2x", c);
break;
}
}
++cstr;
}
s->PutChar('\"');
}
} break;
case eFormatPointer:
DumpAddress(s->AsRawOstream(),
DE.GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size,
item_bit_offset),
sizeof(addr_t));
break;
case eFormatComplexInteger: {
size_t complex_int_byte_size = item_byte_size / 2;
if (complex_int_byte_size > 0 && complex_int_byte_size <= 8) {
s->Printf("%" PRIu64,
DE.GetMaxU64Bitfield(&offset, complex_int_byte_size, 0, 0));
s->Printf(" + %" PRIu64 "i",
DE.GetMaxU64Bitfield(&offset, complex_int_byte_size, 0, 0));
} else {
s->Printf("error: unsupported byte size (%" PRIu64
") for complex integer format",
(uint64_t)item_byte_size);
return offset;
}
} break;
case eFormatComplex:
if (sizeof(float) * 2 == item_byte_size) {
float f32_1 = DE.GetFloat(&offset);
float f32_2 = DE.GetFloat(&offset);
s->Printf("%g + %gi", f32_1, f32_2);
break;
} else if (sizeof(double) * 2 == item_byte_size) {
double d64_1 = DE.GetDouble(&offset);
double d64_2 = DE.GetDouble(&offset);
s->Printf("%lg + %lgi", d64_1, d64_2);
break;
} else if (sizeof(long double) * 2 == item_byte_size) {
long double ld64_1 = DE.GetLongDouble(&offset);
long double ld64_2 = DE.GetLongDouble(&offset);
s->Printf("%Lg + %Lgi", ld64_1, ld64_2);
break;
} else {
s->Printf("error: unsupported byte size (%" PRIu64
") for complex float format",
(uint64_t)item_byte_size);
return offset;
}
break;
default:
case eFormatDefault:
case eFormatHex:
case eFormatHexUppercase: {
bool wantsuppercase = (item_format == eFormatHexUppercase);
switch (item_byte_size) {
case 1:
case 2:
case 4:
case 8:
s->Printf(wantsuppercase ? "0x%*.*" PRIX64 : "0x%*.*" PRIx64,
(int)(2 * item_byte_size), (int)(2 * item_byte_size),
DE.GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size,
item_bit_offset));
break;
default: {
assert(item_bit_size == 0 && item_bit_offset == 0);
const uint8_t *bytes =
(const uint8_t *)DE.GetData(&offset, item_byte_size);
if (bytes) {
s->PutCString("0x");
uint32_t idx;
if (DE.GetByteOrder() == eByteOrderBig) {
for (idx = 0; idx < item_byte_size; ++idx)
s->Printf(wantsuppercase ? "%2.2X" : "%2.2x", bytes[idx]);
} else {
for (idx = 0; idx < item_byte_size; ++idx)
s->Printf(wantsuppercase ? "%2.2X" : "%2.2x",
bytes[item_byte_size - 1 - idx]);
}
}
} break;
}
} break;
case eFormatFloat: {
TargetSP target_sp;
bool used_upfloat = false;
if (exe_scope)
target_sp = exe_scope->CalculateTarget();
if (target_sp) {
auto type_system_or_err =
target_sp->GetScratchTypeSystemForLanguage(eLanguageTypeC);
if (!type_system_or_err) {
llvm::consumeError(type_system_or_err.takeError());
} else {
auto &type_system = *type_system_or_err;
llvm::SmallVector<char, 256> sv;
// Show full precision when printing float values
const unsigned format_precision = 0;
const unsigned format_max_padding =
target_sp->GetMaxZeroPaddingInFloatFormat();
const auto &semantics =
type_system.GetFloatTypeSemantics(item_byte_size);
// Recalculate the byte size in case of a difference. This is possible
// when item_byte_size is 16 (128-bit), because you could get back the
// x87DoubleExtended semantics which has a byte size of 10 (80-bit).
const size_t semantics_byte_size =
(llvm::APFloat::getSizeInBits(semantics) + 7) / 8;
llvm::Optional<llvm::APInt> apint =
GetAPInt(DE, &offset, semantics_byte_size);
if (apint.hasValue()) {
llvm::APFloat apfloat(semantics, apint.getValue());
apfloat.toString(sv, format_precision, format_max_padding);
if (!sv.empty()) {
s->Printf("%*.*s", (int)sv.size(), (int)sv.size(), sv.data());
used_upfloat = true;
}
}
}
}
if (!used_upfloat) {
std::ostringstream ss;
if (item_byte_size == sizeof(float) || item_byte_size == 2) {
float f;
if (item_byte_size == 2) {
uint16_t half = DE.GetU16(&offset);
f = half2float(half);
} else {
f = DE.GetFloat(&offset);
}
ss.precision(std::numeric_limits<float>::digits10);
ss << f;
} else if (item_byte_size == sizeof(double)) {
ss.precision(std::numeric_limits<double>::digits10);
ss << DE.GetDouble(&offset);
} else if (item_byte_size == sizeof(long double) ||
item_byte_size == 10) {
ss.precision(std::numeric_limits<long double>::digits10);
ss << DE.GetLongDouble(&offset);
} else {
s->Printf("error: unsupported byte size (%" PRIu64
") for float format",
(uint64_t)item_byte_size);
return offset;
}
ss.flush();
s->Printf("%s", ss.str().c_str());
}
} break;
case eFormatUnicode16:
s->Printf("U+%4.4x", DE.GetU16(&offset));
break;
case eFormatUnicode32:
s->Printf("U+0x%8.8x", DE.GetU32(&offset));
break;
case eFormatAddressInfo: {
addr_t addr = DE.GetMaxU64Bitfield(&offset, item_byte_size, item_bit_size,
item_bit_offset);
s->Printf("0x%*.*" PRIx64, (int)(2 * item_byte_size),
(int)(2 * item_byte_size), addr);
if (exe_scope) {
TargetSP target_sp(exe_scope->CalculateTarget());
lldb_private::Address so_addr;
if (target_sp) {
if (target_sp->GetSectionLoadList().ResolveLoadAddress(addr,
so_addr)) {
s->PutChar(' ');
so_addr.Dump(s, exe_scope, Address::DumpStyleResolvedDescription,
Address::DumpStyleModuleWithFileAddress);
} else {
so_addr.SetOffset(addr);
so_addr.Dump(s, exe_scope,
Address::DumpStyleResolvedPointerDescription);
}
}
}
} break;
case eFormatHexFloat:
if (sizeof(float) == item_byte_size) {
char float_cstr[256];
llvm::APFloat ap_float(DE.GetFloat(&offset));
ap_float.convertToHexString(float_cstr, 0, false,
llvm::APFloat::rmNearestTiesToEven);
s->Printf("%s", float_cstr);
break;
} else if (sizeof(double) == item_byte_size) {
char float_cstr[256];
llvm::APFloat ap_float(DE.GetDouble(&offset));
ap_float.convertToHexString(float_cstr, 0, false,
llvm::APFloat::rmNearestTiesToEven);
s->Printf("%s", float_cstr);
break;
} else {
s->Printf("error: unsupported byte size (%" PRIu64
") for hex float format",
(uint64_t)item_byte_size);
return offset;
}
break;
// please keep the single-item formats below in sync with
// FormatManager::GetSingleItemFormat if you fail to do so, users will
// start getting different outputs depending on internal implementation
// details they should not care about ||
case eFormatVectorOfChar: // ||
s->PutChar('{'); // \/
offset =
DumpDataExtractor(DE, s, offset, eFormatCharArray, 1, item_byte_size,
item_byte_size, LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfSInt8:
s->PutChar('{');
offset =
DumpDataExtractor(DE, s, offset, eFormatDecimal, 1, item_byte_size,
item_byte_size, LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfUInt8:
s->PutChar('{');
offset = DumpDataExtractor(DE, s, offset, eFormatHex, 1, item_byte_size,
item_byte_size, LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfSInt16:
s->PutChar('{');
offset = DumpDataExtractor(
DE, s, offset, eFormatDecimal, sizeof(uint16_t),
item_byte_size / sizeof(uint16_t), item_byte_size / sizeof(uint16_t),
LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfUInt16:
s->PutChar('{');
offset = DumpDataExtractor(DE, s, offset, eFormatHex, sizeof(uint16_t),
item_byte_size / sizeof(uint16_t),
item_byte_size / sizeof(uint16_t),
LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfSInt32:
s->PutChar('{');
offset = DumpDataExtractor(
DE, s, offset, eFormatDecimal, sizeof(uint32_t),
item_byte_size / sizeof(uint32_t), item_byte_size / sizeof(uint32_t),
LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfUInt32:
s->PutChar('{');
offset = DumpDataExtractor(DE, s, offset, eFormatHex, sizeof(uint32_t),
item_byte_size / sizeof(uint32_t),
item_byte_size / sizeof(uint32_t),
LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfSInt64:
s->PutChar('{');
offset = DumpDataExtractor(
DE, s, offset, eFormatDecimal, sizeof(uint64_t),
item_byte_size / sizeof(uint64_t), item_byte_size / sizeof(uint64_t),
LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfUInt64:
s->PutChar('{');
offset = DumpDataExtractor(DE, s, offset, eFormatHex, sizeof(uint64_t),
item_byte_size / sizeof(uint64_t),
item_byte_size / sizeof(uint64_t),
LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfFloat16:
s->PutChar('{');
offset =
DumpDataExtractor(DE, s, offset, eFormatFloat, 2, item_byte_size / 2,
item_byte_size / 2, LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfFloat32:
s->PutChar('{');
offset =
DumpDataExtractor(DE, s, offset, eFormatFloat, 4, item_byte_size / 4,
item_byte_size / 4, LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfFloat64:
s->PutChar('{');
offset =
DumpDataExtractor(DE, s, offset, eFormatFloat, 8, item_byte_size / 8,
item_byte_size / 8, LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
case eFormatVectorOfUInt128:
s->PutChar('{');
offset =
DumpDataExtractor(DE, s, offset, eFormatHex, 16, item_byte_size / 16,
item_byte_size / 16, LLDB_INVALID_ADDRESS, 0, 0);
s->PutChar('}');
break;
}
}
if (item_format == eFormatBytesWithASCII && offset > line_start_offset) {
s->Printf("%*s", static_cast<int>(
(num_per_line - (offset - line_start_offset)) * 3 + 2),
"");
DumpDataExtractor(DE, s, line_start_offset, eFormatCharPrintable, 1,
offset - line_start_offset, SIZE_MAX,
LLDB_INVALID_ADDRESS, 0, 0);
}
return offset; // Return the offset at which we ended up
}
void lldb_private::DumpHexBytes(Stream *s, const void *src, size_t src_len,
uint32_t bytes_per_line,
lldb::addr_t base_addr) {
DataExtractor data(src, src_len, lldb::eByteOrderLittle, 4);
DumpDataExtractor(data, s,
0, // Offset into "src"
lldb::eFormatBytes, // Dump as hex bytes
1, // Size of each item is 1 for single bytes
src_len, // Number of bytes
bytes_per_line, // Num bytes per line
base_addr, // Base address
0, 0); // Bitfield info
}
|
// Running jack: sudo jackd -P70 -p16 -t2000 -dalsa -p64 -n3 -r44100 -s &
//
// -march=armv8-a doesn't work with std::thread on this GCC version,
// see the Jonathan Wakely's comment (2015-10-05) for bug #42734 on gcc.gnu.org
#if ! defined (PV_VERSION)
#error PV_VERSION should be defined.
#endif
// No I/O, audio only. Useful to debug soundcard-related problems.
#undef MAIN_USE_VOID
// Define this to record a video capture of the display in addition to the
// audio streams
#undef MAIN_REC_VIDEO
#include "fstb/def.h"
#if fstb_SYS == fstb_SYS_WIN
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#endif
#define MAIN_DISP_ST7920 (1)
#define MAIN_DISP_PCD8544 (2)
#define MAIN_DISP_LINUXFB (3)
#if (PV_VERSION == 2)
#define MAIN_DISP MAIN_DISP_LINUXFB
#else
#define MAIN_DISP MAIN_DISP_ST7920
#endif
#define MAIN_API_JACK (1)
#define MAIN_API_ALSA (2)
#define MAIN_API_ASIO (3)
#define MAIN_API_MANUAL (4)
#define MAIN_API_PVAB (5)
#if 0 // For debugging complex audio things
#define MAIN_API MAIN_API_MANUAL
#elif fstb_SYS == fstb_SYS_LINUX
#if (PV_VERSION == 2)
#define MAIN_API MAIN_API_PVAB
#else
// #define MAIN_API MAIN_API_JACK
#define MAIN_API MAIN_API_ALSA
#endif
#else
#define MAIN_API MAIN_API_ASIO
#endif
#include "fstb/AllocAlign.h"
#include "fstb/fnc.h"
#include "mfx/adrv/CbInterface.h"
#include "mfx/adrv/DriverInterface.h"
#include "mfx/dsp/mix/Align.h"
#include "mfx/doc/SerRText.h"
#include "mfx/doc/SerWText.h"
#include "mfx/pi/dist1/Param.h"
#include "mfx/pi/dtone1/Param.h"
#include "mfx/pi/dwm/DryWetDesc.h"
#include "mfx/pi/dwm/Param.h"
#include "mfx/pi/freqsh/FreqShiftDesc.h"
#include "mfx/pi/freqsh/Param.h"
#include "mfx/pi/iifix/Param.h"
#include "mfx/pi/param/Tools.h"
#include "mfx/pi/trem1/Param.h"
#include "mfx/pi/trem1/Waveform.h"
#include "mfx/pi/wah1/Param.h"
#include "mfx/piapi/EventTs.h"
#include "mfx/ui/FontDataDefault.h"
#include "mfx/ui/TimeShareThread.h"
#include "mfx/uitk/NText.h"
#include "mfx/uitk/NWindow.h"
#include "mfx/uitk/ParentInterface.h"
#include "mfx/CmdLine.h"
#include "mfx/Model.h"
#include "mfx/ModelObserverDefault.h"
#include "mfx/PageSet.h"
#include "mfx/PluginPool.h"
#include "mfx/ProcessingContext.h"
#include "mfx/Stop.h"
#include "mfx/View.h"
#include "mfx/WaMsgQueue.h"
#include "mfx/WorldAudio.h"
#if fstb_SYS == fstb_SYS_LINUX
#if (MAIN_API == MAIN_API_JACK)
#include "mfx/adrv/DJack.h"
#elif (MAIN_API == MAIN_API_ALSA)
#include "mfx/adrv/DAlsa.h"
#elif (MAIN_API == MAIN_API_MANUAL)
#include "mfx/adrv/DManual.h"
#elif (MAIN_API == MAIN_API_PVAB)
#include "mfx/adrv/DPvabI2sDma.h"
#else
#error Wrong MAIN_API value
#endif // MAIN_API
#include "mfx/hw/FileIOPi3.h"
#include "mfx/hw/UniqueRscLinux.h"
#if ! defined (MAIN_USE_VOID)
#if MAIN_DISP == MAIN_DISP_LINUXFB
#include "mfx/hw/DisplayLinuxFrameBuf.h"
#elif MAIN_DISP == MAIN_DISP_PCD8544
#include "mfx/hw/DisplayPi3Pcd8544.h"
#else
#include "mfx/hw/DisplayPi3St7920.h"
#endif
#include "mfx/hw/LedPi3.h"
#include "mfx/hw/UserInputPi3.h"
#include <wiringPi.h>
#include <wiringPiI2C.h>
#include <wiringPiSPI.h>
#endif // MAIN_USE_VOID
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <signal.h>
#elif (fstb_SYS == fstb_SYS_WIN)
#include "mfx/hw/FileIOWindows.h"
#include "mfx/hw/IoWindows.h"
#if (MAIN_API == MAIN_API_ASIO)
#include "mfx/adrv/DAsio.h"
#elif (MAIN_API == MAIN_API_MANUAL)
#include "mfx/adrv/DManual.h"
#else
#error Wrong MAIN_API value
#endif
#include <Windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#if defined (_MSC_VER)
#include <crtdbg.h>
#include <new.h>
#include <new>
#endif // _MSC_VER
#else // fstb_SYS
#error Unsupported operating system
#endif // fstb_SYS
#if defined (MAIN_USE_VOID)
#include "mfx/ui/DisplayVoid.h"
#include "mfx/ui/LedVoid.h"
#include "mfx/ui/UserInputVoid.h"
#endif // MAIN_USE_VOID
#if defined (MAIN_REC_VIDEO)
#include "mfx/VideoRecorder.h"
#endif // MAIN_REC_VIDEO
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <memory>
#include <mutex>
#include <thread>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if (fstb_SYS == fstb_SYS_LINUX) && ! defined (MAIN_USE_VOID)
static const int MAIN_pin_reset = 18;
#endif // fstb_SYS_LINUX, MAIN_USE_VOID
class Context
: public mfx::ModelObserverDefault
, public mfx::adrv::CbInterface
{
public:
mfx::Stop & _stop;
double _sample_freq;
int _max_block_size;
#if (fstb_SYS == fstb_SYS_LINUX)
mfx::ui::TimeShareThread
_thread_spi;
#endif // fstb_SYS_LINUX
const int _tuner_subspl = 4;
// Audio engine
mfx::ProcessingContext
_proc_ctx;
mfx::ProcessingContext
_tune_ctx;
mfx::ui::UserInputInterface::MsgQueue
_queue_input_to_gui;
mfx::ui::UserInputInterface::MsgQueue
_queue_input_to_cmd;
mfx::ui::UserInputInterface::MsgQueue
_queue_input_to_audio;
// Controller
#if defined (MAIN_USE_VOID)
mfx::ui::DisplayVoid
_display;
mfx::ui::UserInputVoid
_user_input;
mfx::ui::LedVoid
_leds;
#elif (fstb_SYS == fstb_SYS_LINUX)
#if (MAIN_DISP == MAIN_DISP_LINUXFB)
mfx::hw::DisplayLinuxFrameBuf
#elif (MAIN_DISP == MAIN_DISP_PCD8544)
mfx::hw::DisplayPi3Pcd8544
#else
mfx::hw::DisplayPi3St7920
#endif
_display;
mfx::hw::UserInputPi3
_user_input;
mfx::hw::LedPi3
_leds;
#else // fstb_SYS
mfx::hw::IoWindows
_all_io;
mfx::ui::DisplayInterface &
_display;
mfx::ui::UserInputInterface &
_user_input;
mfx::ui::LedInterface &
_leds;
#endif
#if defined (MAIN_REC_VIDEO)
mfx::VideoRecorder
_vid_rec;
#endif // MAIN_REC_VIDEO
#if (fstb_SYS == fstb_SYS_LINUX)
mfx::hw::FileIOPi3
_file_io;
#else // fstb_SYS_LINUX
mfx::hw::FileIOWindows
_file_io;
#endif // fstb_SYS_LINUX
mfx::Model _model;
// View
mfx::View _view;
mfx::PageSet _page_set;
explicit Context (mfx::adrv::DriverInterface &snd_drv, mfx::Stop &stop);
void set_proc_info (double sample_freq, int max_block_size);
protected:
// mfx::ModelObserverDefault
void do_set_tuner (bool active_flag) final;
// mfx::adrv:CbInterface
void do_process_block (float * const * dst_arr, const float * const * src_arr, int nbr_spl) noexcept final;
void do_notify_dropout () noexcept final;
void do_request_exit () noexcept final;
private:
static void init_empty_bank (mfx::doc::Bank &bank);
#if (fstb_SYS == fstb_SYS_LINUX)
static void signal_handler (int sig);
static Context *
_instance_ptr;
#endif
};
#if (fstb_SYS == fstb_SYS_LINUX)
Context * Context::_instance_ptr = nullptr;
void Context::signal_handler (int sig)
{
fprintf (stderr, "\nSignal %d received, exiting...\n", sig);
_instance_ptr->request_exit ();
}
#endif
Context::Context (mfx::adrv::DriverInterface &snd_drv, mfx::Stop &stop)
: _stop (stop)
, _sample_freq (0)
, _max_block_size (0)
#if (fstb_SYS == fstb_SYS_LINUX)
, _thread_spi (std::chrono::milliseconds (10))
#endif // fstb_SYS_LINUX
, _proc_ctx ()
, _queue_input_to_gui ()
, _queue_input_to_cmd ()
, _queue_input_to_audio ()
#if defined (MAIN_USE_VOID)
, _display ()
, _user_input ()
, _leds ()
#elif (fstb_SYS == fstb_SYS_LINUX)
#if (MAIN_DISP == MAIN_DISP_LINUXFB)
, _display ("/dev/fb0")
#else // MAIN_DISP
, _display (_thread_spi)
#endif // MAIN_DISP
, _user_input (_thread_spi)
, _leds ()
#else // fstb_SYS
, _all_io (_stop)
, _display (_all_io)
, _user_input (_all_io)
, _leds (_all_io)
#endif // fstb_SYS
#if defined (MAIN_REC_VIDEO)
, _vid_rec (_display)
#endif // MAIN_REC_VIDEO
, _file_io (_leds)
, _model (_queue_input_to_cmd, _queue_input_to_audio, _user_input, _file_io)
, _view ()
, _page_set (
_model, _view,
#if defined (MAIN_REC_VIDEO)
_vid_rec,
#else // MAIN_REC_VIDEO
_display,
#endif // MAIN_REC_VIDEO
_queue_input_to_gui, _user_input, _leds, _stop, snd_drv
)
{
#if (fstb_SYS == fstb_SYS_LINUX)
_instance_ptr = this;
signal (SIGINT, &signal_handler);
signal (SIGTERM, &signal_handler);
signal (SIGQUIT, &signal_handler);
signal (SIGHUP, &signal_handler);
#endif
#if ! (fstb_SYS == fstb_SYS_LINUX)
_all_io.set_model (_model);
#endif
// First, scans the input queue to check if the ESC button
// is pressed. If it is the case, we request exiting the program.
_user_input.set_msg_recipient (
mfx::ui::UserInputType_SW,
1 /*** To do: constant ***/,
&_queue_input_to_gui
);
mfx::ui::UserInputInterface::MsgCell * cell_ptr = nullptr;
bool scan_flag = true;
do
{
cell_ptr = _queue_input_to_gui.dequeue ();
if (cell_ptr != nullptr)
{
const mfx::ui::UserInputType type = cell_ptr->_val.get_type ();
const int index = cell_ptr->_val.get_index ();
const float val = cell_ptr->_val.get_val ();
if (type == mfx::ui::UserInputType_SW && index == 1 /*** To do: constant ***/)
{
fprintf (stderr, "Reading ESC button...\n");
if (val > 0.5f)
{
stop.request (mfx::Stop::Type::QUIT);
fprintf (stderr, "Exit requested.\n");
}
scan_flag = false;
}
_user_input.return_cell (*cell_ptr);
}
}
while (cell_ptr != nullptr && scan_flag);
// Assigns message queues to input devices
_user_input.assign_queues_to_input_dev (
_queue_input_to_cmd,
_queue_input_to_gui,
_queue_input_to_audio
);
// Lists public plug-ins
_model.create_plugin_lists ();
_model.set_observer (&_view);
_view.add_observer (*this);
_view.set_pi_lists (_model.use_aud_pi_list (), _model.use_sig_pi_list ());
const int ret_val = _model.load_from_disk ();
if (ret_val != 0)
{
/*** To do: error message? ***/
mfx::doc::PedalboardLayout layout;
layout.set_default_conf ();
_model.set_pedalboard_layout (layout);
mfx::doc::Bank bank;
init_empty_bank (bank);
for (int b = 0; b < mfx::Cst::_nbr_banks; ++b)
{
_model.set_bank (b, bank);
}
_model.select_bank (0);
_model.activate_preset (0);
}
#if 0
{
// Serialization consistency test
mfx::doc::SerWText ser_w;
ser_w.clear ();
_view.use_setup ().ser_write (ser_w);
ser_w.terminate ();
const std::string result = ser_w.use_content ();
mfx::doc::SerRText ser_r;
ser_r.start (result);
#if __cplusplus >= 201402
auto sss_uptr (std::make_unique <mfx::doc::Setup> ());
#else // __cplusplus
std::unique_ptr <mfx::doc::Setup> sss_uptr (new mfx::doc::Setup);
#endif // __cplusplus
sss_uptr->ser_read (ser_r);
ser_r.terminate ();
ser_w.clear ();
_view.use_setup ().ser_write (ser_w);
ser_w.terminate ();
const std::string result2 = ser_w.use_content ();
assert (result == result2);
}
#endif
// _model.set_chn_mode (mfx::ChnMode_1M_1S);
mfx::uitk::PageSwitcher & page_switcher = _page_set.use_page_switcher ();
page_switcher.switch_to (mfx::uitk::pg::PageType_PROG_CUR, nullptr);
/**********************************************************************************************************************************************************************************************************************************/
// Debugging code
// _model.select_bank (2);
// _model.activate_preset (3);
/**********************************************************************************************************************************************************************************************************************************/
}
void Context::set_proc_info (double sample_freq, int max_block_size)
{
_sample_freq = sample_freq;
_max_block_size = max_block_size;
_model.set_process_info (_sample_freq, _max_block_size);
}
void Context::do_set_tuner (bool active_flag)
{
if (active_flag)
{
mfx::uitk::PageSwitcher & page_switcher =
_page_set.use_page_switcher ();
const mfx::uitk::Page & page_mgr = _page_set.use_page_mgr ();
page_switcher.call_page (
mfx::uitk::pg::PageType_TUNER,
nullptr,
page_mgr.get_cursor_node ()
);
}
}
void Context::do_process_block (float * const * dst_arr, const float * const * src_arr, int nbr_spl) noexcept
{
_model.process_block (dst_arr, src_arr, nbr_spl);
}
void Context::do_notify_dropout () noexcept
{
mfx::MeterResultSet & meters = _model.use_meters ();
meters._dsp_overload_flag.exchange (true);
}
void Context::do_request_exit () noexcept
{
_stop.request (mfx::Stop::Type::QUIT);
}
void Context::init_empty_bank (mfx::doc::Bank &bank)
{
for (auto &preset : bank._preset_arr)
{
preset._name = mfx::Cst::_empty_preset_name;
}
}
static int MAIN_main_loop (Context &ctx, mfx::adrv::DriverInterface &snd_drv)
{
fprintf (stderr, "Entering main loop...\n");
int ret_val = 0;
int loop_count = 0;
int overload_count = 0;
const int overload_limit = 10;
int recovery_count = 0;
const int recovery_limit = 10;
const int recovery_limit2 = 50; // For the restart
int restart_count = 0;
int restart_limit = 32;
while (ret_val == 0 && ! ctx._stop.is_exit_requested ())
{
int wait_ms = 100; // Milliseconds
#if 0 // When doing manual time sharing
while (! ctx._thread_spi.process_single_task ())
{
continue;
}
#endif
ctx._model.process_messages ();
const bool tuner_flag = ctx._view.is_tuner_active ();
mfx::MeterResultSet & meters = ctx._model.use_meters ();
// Watchdog for audio overloads
const bool overload_flag = meters._dsp_overload_flag.exchange (false);
if (overload_flag)
{
wait_ms = 10;
recovery_count = 0;
++ overload_count;
if ( overload_count > overload_limit
&& restart_count < restart_limit)
{
snd_drv.restart ();
overload_count = 0;
++ restart_count;
}
}
else
{
++ recovery_count;
if (recovery_count > recovery_limit)
{
if (recovery_count > recovery_limit2)
{
restart_count = 0;
}
overload_count = 0;
}
}
// LEDs
if (! tuner_flag)
{
constexpr int nbr_led = 3;
std::array <float, nbr_led> lum_arr = { 0, 0, 0 };
if (meters.check_signal_clipping ())
{
lum_arr [0] = 1;
}
if (overload_flag)
{
if (restart_count >= restart_limit)
{
lum_arr [0] = sqrtf (0.375f);
lum_arr [1] = sqrtf (0.125f);
lum_arr [2] = sqrtf (0.5f );
}
else
{
lum_arr [2] = 1;
}
}
for (int led_index = 0; led_index < nbr_led; ++led_index)
{
float val = lum_arr [led_index];
val = val * val; // Gamma 2.0
ctx._leds.set_led (led_index, val);
}
}
// Pollutes the logs when run in init.d
#if defined (MAIN_USE_VOID) || ! (fstb_SYS == fstb_SYS_LINUX)
const float usage_max = meters._dsp_use._peak;
const float usage_avg = meters._dsp_use._rms;
const float period_now = ctx._model.get_audio_period_ratio ();
char cpu_0 [127+1] = "Time usage: ------ % / ------ %";
if (usage_max >= 0 && usage_avg >= 0)
{
fstb::snprintf4all (
cpu_0, sizeof (cpu_0),
"Time usage: %6.2f %% / %6.2f %%, Speed: %6.2f %%",
usage_avg * 100, usage_max * 100, 100 / period_now
);
}
fprintf (stderr, "%s\r", cpu_0);
fflush (stderr);
#endif
ctx._page_set.use_page_mgr ().process_messages ();
bool wait_flag = true;
#if 1
if (wait_flag)
{
static const std::chrono::milliseconds wait_duration (wait_ms);
std::this_thread::sleep_for (wait_duration);
}
#if (MAIN_API == MAIN_API_MANUAL)
{
mfx::adrv::DManual & snd_drv_man =
dynamic_cast <mfx::adrv::DManual &> (snd_drv);
size_t sample_index = snd_drv_man.get_sample_index ();
const int nbr_spl = ctx._max_block_size;
const int nbr_blocks = fstb::ceil_int (ctx._sample_freq * wait_ms / (1000.0 * nbr_spl));
#if 0
const int sec = int (sample_index / size_t (ctx._sample_freq));
const size_t sec_spl = sec * size_t (ctx._sample_freq);
if (sec_spl <= sample_index && sample_index < sec_spl + nbr_spl * nbr_blocks)
{
printf ("%d ", sec);
fflush (stdout);
}
#endif
float * in_ptr_arr [mfx::adrv::DriverInterface::_nbr_chn];
const float * out_ptr_arr [mfx::adrv::DriverInterface::_nbr_chn];
snd_drv_man.get_buffers (in_ptr_arr, out_ptr_arr);
const double freq = 82.40689; // E
const double mul = 2 * fstb::PI * freq / ctx._sample_freq;
const float amp = 0.1f;
for (int b = 0; b < nbr_blocks; ++b)
{
for (int i = 0; i < nbr_spl; ++i)
{
const float val = float (sin ((sample_index + i) * mul)) * amp;
for (int chn = 0; chn < mfx::adrv::DriverInterface::_nbr_chn; ++ chn)
{
in_ptr_arr [chn] [i] = val;
}
}
snd_drv_man.process_block ();
sample_index += nbr_spl;
}
}
#endif
#else
/********************************************* TEMP *********************************/
const int nbr_spl = 64;
float buf [4] [nbr_spl];
#if 0
memset (&buf [0] [0], 0, sizeof (buf [0]));
memset (&buf [1] [0], 0, sizeof (buf [1]));
#else
static double angle_pos = 0;
const double angle_step = 2 * fstb::PI * 200 / ctx._sample_freq;
for (int i = 0; i < nbr_spl; ++i)
{
const float val = float (sin (angle_pos));
buf [0] [i] = val;
buf [1] [i] = val;
angle_pos += angle_step;
}
angle_pos = fmod (angle_pos, 2 * fstb::PI);
#endif
const float * src_arr [2] = { buf [0], buf [1] };
float * dst_arr [2] = { buf [2], buf [3] };
ctx._model.process_block (dst_arr, src_arr, nbr_spl);
/********************************************* TEMP *********************************/
#endif
/********************************************* TEMP *********************************/
#if 0
if (loop_count == 10)
{
ctx._user_input.send_message (0, mfx::ui::UserInputType_POT, 0, 0.5f);
// ctx._user_input.send_message (0, mfx::ui::UserInputType_SW, 2, 1);
}
#endif
/********************************************* TEMP *********************************/
++ loop_count;
}
fprintf (stderr, "Exiting main loop.\n");
return ret_val;
}
#if defined (_MSC_VER)
static int __cdecl MAIN_new_handler_cb (size_t dummy)
{
fstb::unused (dummy);
throw std::bad_alloc ();
// return (0);
}
void MAIN_prog_init ()
{
::_set_new_handler (::MAIN_new_handler_cb);
#if ! defined (NDEBUG)
const int mode = (1 * _CRTDBG_MODE_DEBUG)
| (1 * _CRTDBG_MODE_WNDW);
::_CrtSetReportMode (_CRT_WARN, mode);
::_CrtSetReportMode (_CRT_ERROR, mode);
::_CrtSetReportMode (_CRT_ASSERT, mode);
const int old_flags = ::_CrtSetDbgFlag (_CRTDBG_REPORT_FLAG);
::_CrtSetDbgFlag ( old_flags
| (1 * _CRTDBG_LEAK_CHECK_DF)
| (0 * _CRTDBG_CHECK_ALWAYS_DF));
::_CrtSetBreakAlloc (-1); // Specify here a memory bloc number
#endif // NDEBUG
}
void MAIN_prog_end ()
{
#if defined (_MSC_VER) && ! defined (NDEBUG)
const int mode = (1 * _CRTDBG_MODE_DEBUG)
| (0 * _CRTDBG_MODE_WNDW);
::_CrtSetReportMode (_CRT_WARN, mode);
::_CrtSetReportMode (_CRT_ERROR, mode);
::_CrtSetReportMode (_CRT_ASSERT, mode);
::_CrtMemState mem_state;
::_CrtMemCheckpoint (&mem_state);
::_CrtMemDumpStatistics (&mem_state);
#endif // _MSC_VER, NDEBUG
}
#endif // _MSC_VER
#if (fstb_SYS == fstb_SYS_LINUX)
int main (int argc, char *argv [], char *envp [])
{
#else
int WINAPI WinMain (::HINSTANCE instance, ::HINSTANCE prev_instance, ::LPSTR cmdline_0, int cmd_show)
{
fstb::unused (instance, prev_instance, cmdline_0, cmd_show);
#endif
#if defined (_MSC_VER)
MAIN_prog_init ();
#endif
mfx::Stop stop;
int ret_val = 0;
try
{
#if fstb_SYS == fstb_SYS_LINUX
stop.use_cmd_line ().set (argc, argv, envp);
mfx::hw::UniqueRscLinux unique_lock ("pedalevite-unique");
#endif
#if fstb_SYS == fstb_SYS_LINUX && ! defined (MAIN_USE_VOID)
::wiringPiSetupPhys ();
::pinMode (22, INPUT);
if (::digitalRead (22) == LOW)
{
fprintf (stderr, "Emergency exit\n");
throw 0;
}
::pinMode (MAIN_pin_reset, OUTPUT);
::digitalWrite (MAIN_pin_reset, LOW);
std::this_thread::sleep_for (std::chrono::milliseconds (100));
::digitalWrite (MAIN_pin_reset, HIGH);
std::this_thread::sleep_for (std::chrono::milliseconds (100));
#endif
mfx::dsp::mix::Align::setup ();
int chn_idx_in = 0;
int chn_idx_out = 0;
#if (MAIN_API == MAIN_API_JACK)
mfx::adrv::DJack snd_drv;
#elif (MAIN_API == MAIN_API_ALSA)
mfx::adrv::DAlsa snd_drv;
#elif (MAIN_API == MAIN_API_ASIO)
mfx::adrv::DAsio snd_drv;
chn_idx_in = 2;
#elif (MAIN_API == MAIN_API_MANUAL)
mfx::adrv::DManual snd_drv;
#elif (MAIN_API == MAIN_API_PVAB)
mfx::adrv::DPvabI2sDma snd_drv;
#else
#error
#endif
#if __cplusplus >= 201402
auto ctx_uptr (std::make_unique <Context> (snd_drv, stop));
#else // __cplusplus
std::unique_ptr <Context> ctx_uptr (new Context (snd_drv, stop));
#endif // __cplusplus
Context & ctx = *ctx_uptr;
if (! ctx._stop.is_exit_requested ())
{
double sample_freq;
int max_block_size;
ret_val = snd_drv.init (
sample_freq,
max_block_size,
ctx,
nullptr,
chn_idx_in,
chn_idx_out
);
if (ret_val == 0)
{
ctx.set_proc_info (sample_freq, max_block_size);
ret_val = snd_drv.start ();
}
if (ret_val == 0)
{
ret_val = MAIN_main_loop (ctx, snd_drv);
}
snd_drv.stop ();
}
// Flushes all message queues
while ( ctx._model.process_messages ()
|| ctx._page_set.use_page_mgr ().process_messages ())
{
continue;
}
ctx_uptr.reset ();
} // try
#if (fstb_SYS == fstb_SYS_LINUX)
catch (mfx::hw::UniqueRscLinux::Error &e)
{
fprintf (stderr, "Pedale Vite is already running!\n");
}
#endif
catch (int e)
{
fprintf (stderr, "Exception: int = %d\n", e);
ret_val = e;
}
catch (...)
{
fprintf (stderr, "Exception caught.\n");
}
fprintf (stderr, "Exiting with code %d.\n", ret_val);
stop.process_request ();
#if defined (_MSC_VER)
MAIN_prog_end ();
#endif
return ret_val;
}
|
#define SECURITY_WIN32 // For sspi.h
#define QCC_OS_GROUP_WINDOWS
#include "intrinfix.h"
#include "windows.fixed.h"
#include <sdkddkver.h>
#define D3D11_NO_HELPERS
#include <d3d11on12.h>
|
/******************************************************************************
*
* Purpose: Implementation of MSGCommand class. Parse the src_dataset
* string that is meant for the MSG driver.
* Author: Bas Retsios, retsios@itc.nl
*
******************************************************************************
* Copyright (c) 2004, ITC
*
* 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 "cpl_port.h" // Must be first.
#include "msgcommand.h"
#include <cstdlib>
#include <cstdio>
CPL_CVSID("$Id$")
using namespace std;
#ifdef _WIN32
#define PATH_SEP '\\'
#else
#define PATH_SEP '/'
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#define min(a,b) (((a)<(b))?(a):(b))
MSGCommand::MSGCommand() :
cDataConversion('N'),
iNrCycles(1),
sRootFolder(""),
sTimeStamp(""),
iStep(1),
fUseTimestampFolder(true)
{
for (int i = 0; i < 12; ++i)
channel[i] = 0;
}
MSGCommand::~MSGCommand() {}
std::string MSGCommand::sTrimSpaces(std::string const& str)
{
std::string::size_type iStart = 0;
while ((iStart < str.length()) && (str[iStart] == ' '))
++iStart;
std::string::size_type iLength = str.length() - iStart;
while ((iLength > 0) && (str[iStart + iLength - 1] == ' '))
--iLength;
return str.substr(iStart, iLength);
}
std::string MSGCommand::sNextTerm(std::string const& str, int & iPos)
{
std::string::size_type iOldPos = iPos;
iPos = static_cast<int>(str.find(',', iOldPos));
// FIXME: the int vs size_t is messy !
iPos = static_cast<int>(min(static_cast<size_t>(iPos), str.find(')', iOldPos)));
if (static_cast<size_t>(iPos) > iOldPos)
{
std::string sRet = str.substr(iOldPos, iPos - iOldPos);
if (str[iPos] != ')')
++iPos;
return sTrimSpaces(sRet);
}
else
return "";
}
static
bool fTimeStampCorrect(std::string const& sTimeStamp)
{
if (sTimeStamp.length() != 12)
return false;
for (int i = 0; i < 12; ++i)
{
if (sTimeStamp[i] < '0' || sTimeStamp[i] > '9')
return false;
}
return true;
}
std::string MSGCommand::parse(std::string const& command_line)
{
// expected:
// MSG(folder,timestamp,channel,in_same_folder,data_conversion,nr_cycles,step)
// or
// MSG(folder,timestamp,(channel,channel,...,channel),in_same_folder,data_conversion,nr_cycles,step)
// or
// <path>\H-000-MSG1__-MSG1________.....
std::string sErr ("");
std::string sID = command_line.substr(0, 4);
if (sID.compare("MSG(") == 0)
{
int iPos = 4; // after bracket open
sRootFolder = sNextTerm(command_line, iPos);
if (sRootFolder.length() > 0)
{
if (sRootFolder[sRootFolder.length() - 1] != PATH_SEP)
sRootFolder += PATH_SEP;
sTimeStamp = sNextTerm(command_line, iPos);
if (fTimeStampCorrect(sTimeStamp))
{
try // for eventual exceptions
{
while ((iPos < static_cast<int>(command_line.length())) && (command_line[iPos] == ' '))
++iPos;
if (command_line[iPos] == '(')
{
++iPos; // skip the ( bracket
int i = 1;
std::string l_sChannel = sNextTerm(command_line, iPos);
while (command_line[iPos] != ')')
{
int iChan = atoi(l_sChannel.c_str());
if (iChan >= 1 && iChan <= 12)
channel[iChan - 1] = i;
else
sErr = "Channel numbers must be between 1 and 12";
l_sChannel = sNextTerm(command_line, iPos);
++i;
}
int iChan = atoi(l_sChannel.c_str());
if (iChan >= 1 && iChan <= 12)
channel[iChan - 1] = i;
else
sErr = "Channel numbers must be between 1 and 12";
++iPos; // skip the ) bracket
while ((iPos < static_cast<int>(command_line.length())) && (command_line[iPos] == ' '))
++iPos;
if (command_line[iPos] == ',')
++iPos;
}
else
{
std::string l_sChannel = sNextTerm(command_line, iPos);
int iChan = atoi(l_sChannel.c_str());
if (iChan >= 1 && iChan <= 12)
channel[iChan - 1] = 1;
else
sErr = "Channel numbers must be between 1 and 12";
}
std::string sInRootFolder = sNextTerm(command_line, iPos);
if ((sInRootFolder.compare("N") != 0) && (sInRootFolder.compare("Y") != 0))
sErr = "Please specify N for data that is in a date dependent folder or Y for data that is in specified folder.";
else
fUseTimestampFolder = (sInRootFolder.compare("N") == 0);
std::string sDataConversion = sNextTerm(command_line, iPos);
cDataConversion = (sDataConversion.length()>0)?sDataConversion[0]:'N';
std::string sNrCycles = sNextTerm(command_line, iPos);
iNrCycles = atoi(sNrCycles.c_str());
if (iNrCycles < 1)
iNrCycles = 1;
std::string sStep = sNextTerm(command_line, iPos);
iStep = atoi(sStep.c_str());
if (iStep < 1)
iStep = 1;
while ((iPos < static_cast<int>(command_line.length())) && (command_line[iPos] == ' '))
++iPos;
// additional correctness checks
if (command_line[iPos] != ')')
sErr = "Invalid syntax. Please review the MSG(...) statement.";
else if ((iNrChannels() > 1) && (channel[11] != 0))
sErr = "It is not possible to combine channel 12 (HRV) with the other channels.";
else if (iNrChannels() == 0 && sErr.length() == 0)
sErr = "At least one channel should be specified.";
else if ((cDataConversion != 'N') && (cDataConversion != 'B') && (cDataConversion != 'R') && (cDataConversion != 'L') && (cDataConversion != 'T'))
sErr = "Please specify N(o change), B(yte conversion), R(adiometric calibration), L(radiometric using central wavelength) or T(reflectance or temperature) for data conversion.";
}
catch(...)
{
sErr = "Invalid syntax. Please review the MSG(...) statement.";
}
}
else
sErr = "Timestamp should be exactly 12 digits.";
}
else
sErr = "A folder must be filled in indicating the root of the image data folders.";
}
else if (command_line.find("H-000-MSG") != std::string::npos)
{
const size_t iPos = command_line.find("H-000-MSG");
if ((command_line.length() - iPos) == 61)
{
fUseTimestampFolder = false;
sRootFolder = command_line.substr(0, iPos);
sTimeStamp = command_line.substr(iPos + 46, 12);
if (fTimeStampCorrect(sTimeStamp))
{
int iChan = iChannel(command_line.substr(iPos + 26, 9));
if (iChan >= 1 && iChan <= 12)
{
channel[iChan - 1] = 1;
cDataConversion = 'N';
iNrCycles = 1;
iStep = 1;
}
else
sErr = "Channel numbers must be between 1 and 12";
}
else
sErr = "Timestamp should be exactly 12 digits.";
}
else
sErr = "-"; // the source data set it is not for the MSG driver
}
else
sErr = "-"; // the source data set it is not for the MSG driver
return sErr;
}
int MSGCommand::iNrChannels() const
{
int iRet = 0;
for (int i=0; i<12; ++i)
if (channel[i] != 0)
++iRet;
return iRet;
}
int MSGCommand::iChannel(int iChannelNumber) const
{
// return the iChannelNumber-th channel
// iChannelNumber is a value between 1 and 12
// note that channels are ordered. their order number is the value in the array
// As we can't combine channel 12 with channels 1 to 11, it does not make sense to inquire for iNr == 12
int iRet = 0;
if (iChannelNumber <= iNrChannels())
{
while ((iRet < 12) && (channel[iRet] != iChannelNumber))
++iRet;
}
// will return a number between 1 and 12
return iRet + 1;
}
int MSGCommand::iNrStrips(int iChannel)
{
if (iChannel == 12)
return 24;
else if (iChannel >= 1 && iChannel <= 11)
return 8;
else
return 0;
}
int MSGCommand::iChannel(std::string const& sChannel)
{
if (sChannel.compare("VIS006___") == 0)
return 1;
else if (sChannel.compare("VIS008___") == 0)
return 2;
else if (sChannel.compare("IR_016___") == 0)
return 3;
else if (sChannel.compare("IR_039___") == 0)
return 4;
else if (sChannel.compare("WV_062___") == 0)
return 5;
else if (sChannel.compare("WV_073___") == 0)
return 6;
else if (sChannel.compare("IR_087___") == 0)
return 7;
else if (sChannel.compare("IR_097___") == 0)
return 8;
else if (sChannel.compare("IR_108___") == 0)
return 9;
else if (sChannel.compare("IR_120___") == 0)
return 10;
else if (sChannel.compare("IR_134___") == 0)
return 11;
else if (sChannel.compare("HRV______") == 0)
return 12;
else
return 0;
}
std::string MSGCommand::sChannel(int iChannel)
{
switch (iChannel)
{
case 1:
return "VIS006___";
break;
case 2:
return "VIS008___";
break;
case 3:
return "IR_016___";
break;
case 4:
return "IR_039___";
break;
case 5:
return "WV_062___";
break;
case 6:
return "WV_073___";
break;
case 7:
return "IR_087___";
break;
case 8:
return "IR_097___";
break;
case 9:
return "IR_108___";
break;
case 10:
return "IR_120___";
break;
case 11:
return "IR_134___";
break;
case 12:
return "HRV______";
break;
default:
return "_________";
break;
}
}
std::string MSGCommand::sTimeStampToFolder(std::string & sTimeStamp)
{
std::string sYear (sTimeStamp.substr(0,4));
std::string sMonth (sTimeStamp.substr(4, 2));
std::string sDay (sTimeStamp.substr(6, 2));
return sYear + PATH_SEP + sMonth + PATH_SEP + sDay + PATH_SEP;
}
int MSGCommand::iDaysInMonth(int iMonth, int iYear)
{
int iDays;
if ((iMonth == 4) || (iMonth == 6) || (iMonth == 9) || (iMonth == 11))
iDays = 30;
else if (iMonth == 2)
{
iDays = 28;
if (iYear % 100 == 0) // century year
{
if (iYear % 400 == 0) // century leap year
++iDays;
}
else
{
if (iYear % 4 == 0) // normal leap year
++iDays;
}
}
else
iDays = 31;
return iDays;
}
std::string MSGCommand::sCycle(int iCycle)
{
// find nth full quarter
// e.g. for n = 1, 200405311114 should result in 200405311115
// 200405311115 should result in 200405311130
// 200405311101 should result in 200405311115
// 200412312345 should result in 200501010000
std::string sYear (sTimeStamp.substr(0, 4));
std::string sMonth (sTimeStamp.substr(4, 2));
std::string sDay (sTimeStamp.substr(6, 2));
std::string sHours (sTimeStamp.substr(8, 2));
std::string sMins (sTimeStamp.substr(10, 2));
int iYear = atoi(sYear.c_str());
int iMonth = atoi(sMonth.c_str());
int iDay = atoi(sDay.c_str());
int iHours = atoi(sHours.c_str());
int iMins = atoi(sMins.c_str());
iMins += (iCycle - 1)*15*iStep;
// round off the mins found down to a multiple of 15 mins
iMins = ((int)(iMins / 15)) * 15;
// now handle the whole chain back to the year ...
while (iMins >= 60)
{
iMins -= 60;
++iHours;
}
while (iHours >= 24)
{
iHours -= 24;
++iDay;
}
while (iDay > iDaysInMonth(iMonth, iYear))
{
iDay -= iDaysInMonth(iMonth, iYear);
++iMonth;
}
while (iMonth > 12)
{
iMonth -= 12;
++iYear;
}
char sRet [100];
snprintf(sRet, sizeof(sRet), "%.4d%.2d%.2d%.2d%.2d", iYear, iMonth, iDay, iHours, iMins);
return sRet;
}
std::string MSGCommand::sFileName(int iSatellite, int iSequence, int iStrip)
{
int iNr = iNrChannels();
int iChannelNumber = 1 + (iSequence - 1) % iNr;
int iCycle = 1 + (iSequence - 1) / iNr;
char sRet [4096];
std::string siThCycle (sCycle(iCycle));
if (fUseTimestampFolder)
snprintf(sRet, sizeof(sRet), "%s%sH-000-MSG%d__-MSG%d________-%s-%.6d___-%s-C_", sRootFolder.c_str(), sTimeStampToFolder(siThCycle).c_str(), iSatellite, iSatellite, sChannel(iChannel(iChannelNumber)).c_str(), iStrip, siThCycle.c_str());
else
snprintf(sRet, sizeof(sRet), "%sH-000-MSG%d__-MSG%d________-%s-%.6d___-%s-C_", sRootFolder.c_str(), iSatellite, iSatellite, sChannel(iChannel(iChannelNumber)).c_str(), iStrip, siThCycle.c_str());
return sRet;
}
std::string MSGCommand::sPrologueFileName(int iSatellite, int iSequence)
{
int iCycle = 1 + (iSequence - 1) / iNrChannels();
char sRet [4096];
std::string siThCycle (sCycle(iCycle));
if (fUseTimestampFolder)
snprintf(sRet, sizeof(sRet), "%s%sH-000-MSG%d__-MSG%d________-_________-PRO______-%s-__", sRootFolder.c_str(), sTimeStampToFolder(siThCycle).c_str(), iSatellite, iSatellite, siThCycle.c_str());
else
snprintf(sRet, sizeof(sRet), "%sH-000-MSG%d__-MSG%d________-_________-PRO______-%s-__", sRootFolder.c_str(), iSatellite, iSatellite, siThCycle.c_str());
return sRet;
}
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2016-2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/opengl/rendering/texturequadrenderer.h>
#include <inviwo/core/datastructures/image/image.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/util/zip.h>
#include <modules/opengl/geometry/meshgl.h>
#include <modules/opengl/image/imagegl.h>
#include <modules/opengl/image/layergl.h>
#include <modules/opengl/openglutils.h>
#include <modules/opengl/sharedopenglresources.h>
#include <modules/opengl/texture/texture2d.h>
#include <modules/opengl/texture/textureutils.h>
namespace inviwo {
TextureQuadRenderer::TextureQuadRenderer() : shader_(getDefaultShader()) {}
TextureQuadRenderer::TextureQuadRenderer(const Shader &shader)
: shader_(std::make_shared<Shader>(shader)) {}
TextureQuadRenderer::TextureQuadRenderer(Shader &&shader)
: shader_(std::make_shared<Shader>(std::move(shader))) {}
TextureQuadRenderer::~TextureQuadRenderer() = default;
Shader &TextureQuadRenderer::getShader() { return *shader_; }
const Shader &TextureQuadRenderer::getShader() const { return *shader_; }
std::shared_ptr<Shader> TextureQuadRenderer::getDefaultShader() {
static std::weak_ptr<Shader> shader_;
if (auto shader = shader_.lock()) {
return shader;
} else {
shader = std::make_shared<Shader>("rendertexturequad.vert", "rendertexturequad.frag");
shader_ = shader;
return shader;
}
}
void TextureQuadRenderer::render(const Image &image, const ivec2 &pos, const size2_t &canvasSize,
LayerType layerType, const mat4 &transformation,
const mat4 &texTransform) {
if (auto layer = image.getLayer(layerType)) {
render(layer->getRepresentation<LayerGL>()->getTexture(), pos, canvasSize, transformation,
texTransform);
}
}
void TextureQuadRenderer::render(const Image &image, const std::vector<ivec2> &pos,
const std::vector<mat4> &texTransform, const size2_t &canvasSize,
LayerType layerType, const mat4 &transformation) {
if (auto layer = image.getLayer(layerType)) {
render(layer->getRepresentation<LayerGL>()->getTexture(), pos, texTransform, canvasSize,
transformation);
}
}
void TextureQuadRenderer::render(const std::shared_ptr<Image> &image, const ivec2 &pos,
const size2_t &canvasSize, LayerType layerType,
const mat4 &transformation, const mat4 &texTransform) {
if (image) {
if (auto layer = image->getLayer(layerType)) {
render(layer->getRepresentation<LayerGL>()->getTexture(), pos, canvasSize,
transformation, texTransform);
}
}
}
void TextureQuadRenderer::render(const std::shared_ptr<Image> &image, const std::vector<ivec2> &pos,
const std::vector<mat4> &texTransform, const size2_t &canvasSize,
LayerType layerType, const mat4 &transformation) {
if (image) {
if (auto layer = image->getLayer(layerType)) {
render(layer->getRepresentation<LayerGL>()->getTexture(), pos, texTransform, canvasSize,
transformation);
}
}
}
void TextureQuadRenderer::render(const Image &image, const ivec2 &pos, const size2_t &canvasSize,
std::size_t colorLayerIndex, const mat4 &transformation,
const mat4 &texTransform) {
if (auto layer = image.getLayer(LayerType::Color, colorLayerIndex)) {
render(layer->getRepresentation<LayerGL>()->getTexture(), pos, canvasSize, transformation,
texTransform);
}
}
void TextureQuadRenderer::render(const Image &image, const std::vector<ivec2> &pos,
const std::vector<mat4> &texTransform, const size2_t &canvasSize,
std::size_t colorLayerIndex, const mat4 &transformation) {
if (auto layer = image.getLayer(LayerType::Color, colorLayerIndex)) {
render(layer->getRepresentation<LayerGL>()->getTexture(), pos, texTransform, canvasSize,
transformation);
}
}
void TextureQuadRenderer::render(const std::shared_ptr<Image> &image, const ivec2 &pos,
const size2_t &canvasSize, std::size_t colorLayerIndex,
const mat4 &transformation, const mat4 &texTransform) {
if (image) {
if (auto layer = image->getLayer(LayerType::Color, colorLayerIndex)) {
render(layer->getRepresentation<LayerGL>()->getTexture(), pos, canvasSize,
transformation, texTransform);
}
}
}
void TextureQuadRenderer::render(const std::shared_ptr<Image> &image, const std::vector<ivec2> &pos,
const std::vector<mat4> &texTransform, const size2_t &canvasSize,
std::size_t colorLayerIndex, const mat4 &transformation) {
if (image) {
if (auto layer = image->getLayer(LayerType::Color, colorLayerIndex)) {
render(layer->getRepresentation<LayerGL>()->getTexture(), pos, texTransform, canvasSize,
transformation);
}
}
}
void TextureQuadRenderer::render(const Layer &layer, const ivec2 &pos, const size2_t &canvasSize,
const mat4 &transformation, const mat4 &texTransform) {
render(layer.getRepresentation<LayerGL>()->getTexture(), pos, canvasSize, transformation,
texTransform);
}
void TextureQuadRenderer::render(const Layer &layer, const std::vector<ivec2> &pos,
const std::vector<mat4> &texTransform, const size2_t &canvasSize,
const mat4 &transformation) {
render(layer.getRepresentation<LayerGL>()->getTexture(), pos, texTransform, canvasSize,
transformation);
}
void TextureQuadRenderer::render(const std::shared_ptr<Layer> &layer, const ivec2 &pos,
const size2_t &canvasSize, const mat4 &transformation,
const mat4 &texTransform) {
if (layer) {
render(layer->getRepresentation<LayerGL>()->getTexture(), pos, canvasSize, transformation,
texTransform);
}
}
void TextureQuadRenderer::render(const std::shared_ptr<Layer> &layer, const std::vector<ivec2> &pos,
const std::vector<mat4> &texTransform, const size2_t &canvasSize,
const mat4 &transformation) {
if (layer) {
render(layer->getRepresentation<LayerGL>()->getTexture(), pos, texTransform, canvasSize,
transformation);
}
}
void TextureQuadRenderer::render(const Texture2D &texture, const ivec2 &pos,
const size2_t &canvasSize, const mat4 &transformation,
const mat4 &texTransform) {
renderToRect(texture, pos, ivec2(texture.getDimensions()), canvasSize, transformation,
texTransform);
}
void TextureQuadRenderer::render(const Texture2D &texture, const std::vector<ivec2> &pos,
const std::vector<mat4> &texTransform, const size2_t &canvasSize,
const mat4 &transformation) {
renderToRect(texture, pos, std::vector<ivec2>(pos.size(), ivec2(texture.getDimensions())),
texTransform, canvasSize, transformation);
}
void TextureQuadRenderer::render(const std::shared_ptr<Texture2D> &texture, const ivec2 &pos,
const size2_t &canvasSize, const mat4 &transformation,
const mat4 &texTransform) {
renderToRect(texture, pos, ivec2(texture->getDimensions()), canvasSize, transformation,
texTransform);
}
void TextureQuadRenderer::render(const std::shared_ptr<Texture2D> &texture,
const std::vector<ivec2> &pos,
const std::vector<mat4> &texTransform, const size2_t &canvasSize,
const mat4 &transformation) {
renderToRect(texture, pos, std::vector<ivec2>(pos.size(), ivec2(texture->getDimensions())),
texTransform, canvasSize, transformation);
}
void TextureQuadRenderer::renderToRect(const Image &image, const ivec2 &pos, const ivec2 &extent,
const size2_t &canvasSize, LayerType layerType,
const mat4 &transformation, const mat4 &texTransform) {
if (auto layer = image.getLayer(layerType)) {
renderToRect(layer->getRepresentation<LayerGL>()->getTexture(), pos, extent, canvasSize,
transformation, texTransform);
}
}
void TextureQuadRenderer::renderToRect(const Image &image, const std::vector<ivec2> &pos,
const std::vector<ivec2> &extent,
const std::vector<mat4> &texTransform,
const size2_t &canvasSize, LayerType layerType,
const mat4 &transformation) {
if (auto layer = image.getLayer(layerType)) {
renderToRect(layer->getRepresentation<LayerGL>()->getTexture(), pos, extent, texTransform,
canvasSize, transformation);
}
}
void TextureQuadRenderer::renderToRect(const std::shared_ptr<Image> &image, const ivec2 &pos,
const ivec2 &extent, const size2_t &canvasSize,
LayerType layerType, const mat4 &transformation,
const mat4 &texTransform) {
if (image) {
if (auto layer = image->getLayer(layerType)) {
renderToRect(layer->getRepresentation<LayerGL>()->getTexture(), pos, extent, canvasSize,
transformation, texTransform);
}
}
}
void TextureQuadRenderer::renderToRect(const std::shared_ptr<Image> &image,
const std::vector<ivec2> &pos,
const std::vector<ivec2> &extent,
const std::vector<mat4> &texTransform,
const size2_t &canvasSize, LayerType layerType,
const mat4 &transformation) {
if (image) {
if (auto layer = image->getLayer(layerType)) {
renderToRect(layer->getRepresentation<LayerGL>()->getTexture(), pos, extent,
texTransform, canvasSize, transformation);
}
}
}
void TextureQuadRenderer::renderToRect(const Image &image, const ivec2 &pos, const ivec2 &extent,
const size2_t &canvasSize, std::size_t colorLayerIndex,
const mat4 &transformation, const mat4 &texTransform) {
if (auto layer = image.getLayer(LayerType::Color, colorLayerIndex)) {
renderToRect(layer->getRepresentation<LayerGL>()->getTexture(), pos, extent, canvasSize,
transformation, texTransform);
}
}
void TextureQuadRenderer::renderToRect(const Image &image, const std::vector<ivec2> &pos,
const std::vector<ivec2> &extent,
const std::vector<mat4> &texTransform,
const size2_t &canvasSize, std::size_t colorLayerIndex,
const mat4 &transformation) {
if (auto layer = image.getLayer(LayerType::Color, colorLayerIndex)) {
renderToRect(layer->getRepresentation<LayerGL>()->getTexture(), pos, extent, texTransform,
canvasSize, transformation);
}
}
void TextureQuadRenderer::renderToRect(const std::shared_ptr<Image> &image, const ivec2 &pos,
const ivec2 &extent, const size2_t &canvasSize,
std::size_t colorLayerIndex, const mat4 &transformation,
const mat4 &texTransform) {
if (image) {
if (auto layer = image->getLayer(LayerType::Color, colorLayerIndex)) {
renderToRect(layer->getRepresentation<LayerGL>()->getTexture(), pos, extent, canvasSize,
transformation, texTransform);
}
}
}
void TextureQuadRenderer::renderToRect(const std::shared_ptr<Image> &image,
const std::vector<ivec2> &pos,
const std::vector<ivec2> &extent,
const std::vector<mat4> &texTransform,
const size2_t &canvasSize, std::size_t colorLayerIndex,
const mat4 &transformation) {
if (image) {
if (auto layer = image->getLayer(LayerType::Color, colorLayerIndex)) {
renderToRect(layer->getRepresentation<LayerGL>()->getTexture(), pos, extent,
texTransform, canvasSize, transformation);
}
}
}
void TextureQuadRenderer::renderToRect(const Layer &layer, const ivec2 &pos, const ivec2 &extent,
const size2_t &canvasSize, const mat4 &transformation,
const mat4 &texTransform) {
renderToRect(layer.getRepresentation<LayerGL>()->getTexture(), pos, extent, canvasSize,
transformation, texTransform);
}
void TextureQuadRenderer::renderToRect(const Layer &layer, const std::vector<ivec2> &pos,
const std::vector<ivec2> &extent,
const std::vector<mat4> &texTransform,
const size2_t &canvasSize, const mat4 &transformation) {
renderToRect(layer.getRepresentation<LayerGL>()->getTexture(), pos, extent, texTransform,
canvasSize, transformation);
}
void TextureQuadRenderer::renderToRect(const std::shared_ptr<Layer> &layer, const ivec2 &pos,
const ivec2 &extent, const size2_t &canvasSize,
const mat4 &transformation, const mat4 &texTransform) {
if (layer) {
renderToRect(layer->getRepresentation<LayerGL>()->getTexture(), pos, extent, canvasSize,
transformation, texTransform);
}
}
void TextureQuadRenderer::renderToRect(const std::shared_ptr<Layer> &layer,
const std::vector<ivec2> &pos,
const std::vector<ivec2> &extent,
const std::vector<mat4> &texTransform,
const size2_t &canvasSize, const mat4 &transformation) {
if (layer) {
renderToRect(layer->getRepresentation<LayerGL>()->getTexture(), pos, extent, texTransform,
canvasSize, transformation);
}
}
void TextureQuadRenderer::renderToRect(const Texture2D &texture, const ivec2 &pos,
const ivec2 &extent, const size2_t &canvasSize,
const mat4 &transformation, const mat4 &texTransform) {
renderToRect(texture, {pos}, {extent}, {texTransform}, canvasSize, transformation);
}
void TextureQuadRenderer::renderToRect(const std::shared_ptr<Texture2D> &texture,
const std::vector<ivec2> &pos,
const std::vector<ivec2> &extent,
const std::vector<mat4> &texTransform,
const size2_t &canvasSize, const mat4 &transformation) {
if (texture) {
renderToRect(*texture, pos, extent, texTransform, canvasSize, transformation);
}
}
void TextureQuadRenderer::renderToRect(const std::shared_ptr<Texture2D> &texture, const ivec2 &pos,
const ivec2 &extent, const size2_t &canvasSize,
const mat4 &transformation, const mat4 &texTransform) {
if (texture) {
renderToRect(texture, {pos}, {extent}, {texTransform}, canvasSize, transformation);
}
}
void TextureQuadRenderer::renderToRect(const Texture2D &texture, const std::vector<ivec2> &pos,
const std::vector<ivec2> &extent,
const std::vector<mat4> &texTransform,
const size2_t &canvasSize, const mat4 &transformation) {
utilgl::DepthFuncState depth(GL_ALWAYS);
TextureUnit texUnit;
texUnit.activate();
texture.bind();
shader_->activate();
shader_->setUniform("tex", texUnit);
auto rect = SharedOpenGLResources::getPtr()->imagePlaneRect();
utilgl::Enable<MeshGL> enable(rect);
// scaling factor from screen coords to normalized dev coords
const vec2 scaling(vec2(2.0f) / vec2(canvasSize));
for (auto &&elem : util::zip(pos, extent, texTransform)) {
const auto p = vec2{elem.first()} * scaling;
const auto ext = vec2{elem.second()};
const auto dataToWorld = glm::translate(vec3{-1.0f + p.x, -1.0f + p.y, -1.0f}) *
glm::scale(vec3{scaling, 1.f}) * transformation *
glm::scale(vec3{ext, 1.f});
shader_->setUniform("geometry_.dataToWorld", dataToWorld);
shader_->setUniform("texCoordTransform", elem.third());
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
shader_->deactivate();
}
void TextureQuadRenderer::renderToRect(const Texture2D &texture,
const std::vector<ivec2> &positions,
const std::vector<ivec2> &extent,
const std::vector<mat4> &texTransform,
const size2_t &canvasSize,
const std::vector<mat4> &transformations) {
utilgl::DepthFuncState depth(GL_ALWAYS);
TextureUnit texUnit;
texUnit.activate();
texture.bind();
shader_->activate();
shader_->setUniform("tex", texUnit);
auto rect = SharedOpenGLResources::getPtr()->imagePlaneRect();
utilgl::Enable<MeshGL> enable(rect);
// scaling factor from screen coords to normalized dev coords
const vec2 scaling(vec2(2.0f) / vec2(canvasSize));
const auto toNDC = glm::translate(vec3(-1.0f, -1.0f, -1.0f)) * glm::scale(vec3{scaling, 1.f});
for (auto &&elem : util::zip(positions, extent, texTransform, transformations)) {
const auto ext = vec2{elem.second()};
const auto pos = vec3{elem.first().x, elem.first().y, 0.0f};
const auto dataToWorld =
toNDC * glm::translate(pos) * get<3>(elem) * glm::scale(vec3{ext, 1.f});
shader_->setUniform("geometry_.dataToWorld", dataToWorld);
shader_->setUniform("texCoordTransform", elem.third());
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
shader_->deactivate();
}
void TextureQuadRenderer::renderToRect3D(const Camera &camera, const Texture2D &texture,
const vec3 &pos, const ivec2 &extent,
const size2_t &canvasSize, const vec2 &anchor,
const mat4 &transformation, const mat4 &texTransform) {
renderToRect3D(camera, texture, {pos}, {extent}, {texTransform}, canvasSize, anchor,
transformation);
}
void TextureQuadRenderer::renderToRect3D(
const Camera &camera, const std::shared_ptr<Texture2D> &texture, const std::vector<vec3> &pos,
const std::vector<ivec2> &extent, const std::vector<mat4> &texTransform,
const size2_t &canvasSize, const vec2 &anchor, const mat4 &transformation) {
if (texture) {
renderToRect3D(camera, *texture, pos, extent, texTransform, canvasSize, anchor,
transformation);
}
}
void TextureQuadRenderer::renderToRect3D(const Camera &camera,
const std::shared_ptr<Texture2D> &texture, const vec3 &pos,
const ivec2 &extent, const size2_t &canvasSize,
const vec2 &anchor, const mat4 &transformation,
const mat4 &texTransform) {
if (texture) {
renderToRect3D(camera, texture, {pos}, {extent}, {texTransform}, canvasSize, anchor,
transformation);
}
}
void TextureQuadRenderer::renderToRect3D(const Camera &camera, const Texture2D &texture,
const std::vector<vec3> &pos,
const std::vector<ivec2> &extent,
const std::vector<mat4> &texTransform,
const size2_t &canvasSize, const vec2 &anchor,
const mat4 &transformation) {
utilgl::DepthFuncState depth(GL_LESS);
TextureUnit texUnit;
texUnit.activate();
texture.bind();
shader_->activate();
shader_->setUniform("tex", texUnit);
auto rect = SharedOpenGLResources::getPtr()->imagePlaneRect();
utilgl::Enable<MeshGL> enable(rect);
// scaling factor from screen coords to normalized dev coords
const vec2 scaling(vec2(2.0f) / vec2(canvasSize));
const mat4 viewprojMatrix(camera.getProjectionMatrix() * camera.getViewMatrix());
for (auto &&elem : util::zip(pos, extent, texTransform)) {
// transform position from world space into normalized dev coords
vec4 p = viewprojMatrix * vec4{elem.first(), 1.0f};
p /= p.w;
const auto ext = vec2{elem.second()};
// consider anchor position
const auto offset = 0.5f * ext * scaling * (anchor + vec2{1.0f, 1.0f});
// ensure that the lower left position is pixel aligned
const vec3 origin{
glm::round(vec2{p.x - offset.x, p.y - offset.y} * vec2{canvasSize} * 0.5f) * scaling,
p.z};
const mat4 dataToWorld = glm::translate(origin) * glm::scale(vec3{scaling, 1.f}) *
transformation * glm::scale(vec3{ext, 1.f});
shader_->setUniform("geometry_.dataToWorld", dataToWorld);
shader_->setUniform("texCoordTransform", get<2>(elem));
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
shader_->deactivate();
}
} // namespace inviwo
|
// Copyright 2019 The Goma Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "blob/file_service_blob_uploader.h"
#include "glog/logging.h"
#include "goma_data_util.h"
namespace devtools_goma {
FileServiceBlobUploader::FileServiceBlobUploader(
string filename,
std::unique_ptr<FileServiceHttpClient> file_service)
: BlobClient::Uploader(std::move(filename)),
file_service_(std::move(file_service)),
blob_(absl::make_unique<FileBlob>()) {}
bool FileServiceBlobUploader::ComputeKey() {
bool success = file_service_->CreateFileBlob(filename_, false, blob_.get());
if (success && IsValidFileBlob(*blob_)) {
hash_key_ = ComputeFileBlobHashKey(*blob_);
return true;
}
return success;
}
bool FileServiceBlobUploader::Upload() {
blob_->Clear();
bool success = file_service_->CreateFileBlob(filename_, true, blob_.get());
if (success && IsValidFileBlob(*blob_)) {
hash_key_ = ComputeFileBlobHashKey(*blob_);
need_blob_ = true;
return true;
}
return false;
}
bool FileServiceBlobUploader::Embed() {
if (!hash_key_.empty()) {
// already loaded into blob_.
need_blob_ = true;
return true;
}
blob_->Clear();
bool success = file_service_->CreateFileBlob(filename_, false, blob_.get());
if (success && IsValidFileBlob(*blob_)) {
hash_key_ = ComputeFileBlobHashKey(*blob_);
need_blob_ = true;
return true;
}
return false;
}
bool FileServiceBlobUploader::GetInput(ExecReq_Input* input) const {
// |input| should have filename.
// |this->filename_| is abspath, so should not be used here.
CHECK(input->has_filename());
input->set_hash_key(hash_key_);
if (!need_blob_) {
return true;
}
*input->mutable_content() = *blob_;
return IsValidFileBlob(input->content());
}
bool FileServiceBlobUploader::Store() const {
if (!blob_) {
return false;
}
if (!IsValidFileBlob(*blob_)) {
return false;
}
return file_service_->StoreFileBlob(*blob_);
}
} // namespace devtools_goma
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <_target_monster_contsf_allinform_zocl.hpp>
START_ATF_NAMESPACE
namespace Info
{
using _target_monster_contsf_allinform_zoclInit2_ptr = void (WINAPIV*)(struct _target_monster_contsf_allinform_zocl*);
using _target_monster_contsf_allinform_zoclInit2_clbk = void (WINAPIV*)(struct _target_monster_contsf_allinform_zocl*, _target_monster_contsf_allinform_zoclInit2_ptr);
using _target_monster_contsf_allinform_zoclIsSame4_ptr = bool (WINAPIV*)(struct _target_monster_contsf_allinform_zocl*, struct _target_monster_contsf_allinform_zocl*);
using _target_monster_contsf_allinform_zoclIsSame4_clbk = bool (WINAPIV*)(struct _target_monster_contsf_allinform_zocl*, struct _target_monster_contsf_allinform_zocl*, _target_monster_contsf_allinform_zoclIsSame4_ptr);
using _target_monster_contsf_allinform_zoclctor__target_monster_contsf_allinform_zocl6_ptr = void (WINAPIV*)(struct _target_monster_contsf_allinform_zocl*);
using _target_monster_contsf_allinform_zoclctor__target_monster_contsf_allinform_zocl6_clbk = void (WINAPIV*)(struct _target_monster_contsf_allinform_zocl*, _target_monster_contsf_allinform_zoclctor__target_monster_contsf_allinform_zocl6_ptr);
using _target_monster_contsf_allinform_zoclsize8_ptr = int (WINAPIV*)(struct _target_monster_contsf_allinform_zocl*);
using _target_monster_contsf_allinform_zoclsize8_clbk = int (WINAPIV*)(struct _target_monster_contsf_allinform_zocl*, _target_monster_contsf_allinform_zoclsize8_ptr);
}; // end namespace Info
END_ATF_NAMESPACE
|
#include <iostream>
#include "highgui.h"
int main()
{
cvNamedWindow("test2", CV_WINDOW_AUTOSIZE);
CvCapture* capture = cvCreateFileCapture("julia.avi");
IplImage* frame;
while(1)
{
frame = cvQueryFrame(capture);
if(!frame)
break;
cvShowImage("test2", frame);
// 程序暂停33毫秒,获取下一帧图片
// c被设置成按键的ASCII码,否则c被设置成-1.
char c = cvWaitKey(1);
if(c == 27) // ESC(ASCII 27)
break;
}
cvReleaseCapture(&capture);
cvDestroyWindow("test2");
system("pause");
return 0;
}
|
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <openmp/TestOpenMP_Category.hpp>
#include <TestViewSubview.hpp>
namespace Test {
TEST_F( TEST_CATEGORY, view_subview_3d_from_5d_right_atomic )
{
TestViewSubview::test_3d_subview_5d_right< TEST_EXECSPACE, Kokkos::MemoryTraits<Kokkos::Atomic> >();
}
} // namespace Test
|
/*!
* @copyright
* Copyright (c) 2015-2017 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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.
*
*
* @file ssdp_service_impl.cpp
*
* @brief SsdpService implementation.
* */
#include "ssdp/ssdp_service_impl.hpp"
#include "ssdp/ssdp_packet_parser.hpp"
#include "ssdp/ssdp_packet_validator.hpp"
#include "ssdp/uri.hpp"
#include "logger/logger_factory.hpp"
#include <algorithm>
#include <set>
#include <sstream>
using namespace ssdp;
namespace {
constexpr const char SSDP_ALL_STR[] = "ssdp:all";
constexpr const int PACKET_SIZE = 1536;
bool supports_mcast_address(const SocketAddress& ssdp_address, const NetworkInterface& iface) {
if (AF_INET == ssdp_address.af()) {
return iface.supports_ipv4();
}
else if (AF_INET6 == ssdp_address.af()) {
return iface.supports_ipv6();
}
return false;
}
void leave_or_join_mcast_group(MulticastSocket& listen_socket,
const SocketAddress& ssdp_address,
const NetworkInterface& cached_iface,
const NetworkInterface& updated_iface) {
auto is_joined = supports_mcast_address(ssdp_address, cached_iface);
auto should_join = supports_mcast_address(ssdp_address, updated_iface);
if (!is_joined && should_join) {
listen_socket.join_group(ssdp_address.get_host(), updated_iface);
}
else if (is_joined && !should_join) {
listen_socket.leave_group(ssdp_address.get_host(), cached_iface);
}
}
MulticastSocket open_ssdp_listen_socket(std::uint16_t port) {
return MulticastSocket(SocketAddress(port), /*reuse_address*/true);
}
MulticastSocket open_ssdp_notify_socket(unsigned char ttl,
const NetworkInterface& iface,
const IpAddress& address) {
SocketAddress socket_address(address, 0);
MulticastSocket mcast_socket(socket_address);
mcast_socket.set_loopback(false);
mcast_socket.set_broadcast(true);
mcast_socket.set_blocking(false);
mcast_socket.set_interface(iface);
mcast_socket.set_ttl(ttl);
return mcast_socket;
}
constexpr unsigned long MAX_MX = 5;
constexpr uint DELAY_INCREMENT = 50;
constexpr uint SCHEDULED_DELAY = 250;
std::chrono::milliseconds calculate_delay(const std::string& mx_str) {
unsigned long mx{1};
try {
auto mx_val = std::stoul(mx_str);
if (mx_val > 0 && mx_val < MAX_MX) {
mx = mx_val;
}
}
catch(...) {/*ignore*/}
return std::chrono::milliseconds(std::rand() / (1 + RAND_MAX / (1000 * mx)));
}
std::chrono::milliseconds get_check_interval(const SsdpServiceConfig& config) {
if (config.get_announce_interval() > std::chrono::seconds(0)) {
return config.get_announce_interval();
}
return std::chrono::minutes(30);
}
bool is_iface_ignored(const std::unordered_set<std::string>& iface_names, const std::string& name) {
return iface_names.cend() == iface_names.find(name);
}
std::set<IpAddress> get_addresses_for_mcast(const SocketAddress& mcast_address, const NetworkInterface& iface) {
std::set<IpAddress> addresses{};
for (const auto& address : iface.get_address_list()) {
const auto& ip_address = std::get<net::NetworkInterface::IP_ADDRESS>(address);
if (mcast_address.family() == ip_address.get_address_family()) {
addresses.emplace(ip_address);
}
}
return addresses;
}
std::tuple<std::set<IpAddress>, std::set<IpAddress>> addresses_difference(
const NetworkInterface& cached, const NetworkInterface& updated) {
auto cached_addresses = get_addresses_for_mcast(SsdpService::SSDP_MCAST_ADDRESS, cached);
auto updated_addresses = get_addresses_for_mcast(SsdpService::SSDP_MCAST_ADDRESS, updated);
std::set<IpAddress> added{};
std::set_difference(updated_addresses.begin(), updated_addresses.end(),
cached_addresses.begin(), cached_addresses.end(),
std::inserter(added, added.begin()));
std::set<IpAddress> removed{};
std::set_difference(cached_addresses.begin(), cached_addresses.end(),
updated_addresses.begin(), updated_addresses.end(),
std::inserter(removed, removed.begin()));
return std::make_tuple(std::move(added), std::move(removed));
}
void update_mcast_notify_sockets_list(std::vector<MulticastSocket>& notify_sockets,
const NetworkInterface& cached_iface,
const NetworkInterface& updated_iface,
unsigned char ttl) {
const auto diff = addresses_difference(cached_iface, updated_iface);
const auto& removed_addresses = std::get<1>(diff);
notify_sockets.erase(std::remove_if(notify_sockets.begin(), notify_sockets.end(),
[&removed_addresses](MulticastSocket & socket) {
return removed_addresses.cend() != removed_addresses.find(socket.get_address().get_host());
}
), notify_sockets.end());
const auto& new_addresses = std::get<0>(diff);
for (const auto& address : new_addresses) {
notify_sockets.emplace_back(open_ssdp_notify_socket(ttl, updated_iface, address));
}
}
}
SsdpServiceImpl::SsdpServiceImpl(std::shared_ptr<const SsdpServiceConfig> config)
: m_config(config),
m_ssdp_packet_factory(m_config),
m_notification_pipe(net::PairedSocket::create_socket_pair()) {}
SsdpServiceImpl::~SsdpServiceImpl() {
stop();
}
namespace {
bool same_subnet(const IpAddress& peer, const IpAddress& nic_ip, const IpAddress& mask) {
return (peer & mask) == (nic_ip & mask);
}
}
IpAddress SsdpServiceImpl::find_lan_of_peer(const IpAddress& peer) {
for (const auto& iface : m_network_interfaces) {
for (const auto& address : iface.second.get_address_list()) {
const auto& iface_ip = std::get<NetworkInterface::IP_ADDRESS>(address);
const auto& iface_subnet_mask = std::get<NetworkInterface::SUBNET_MASK>(address);
if (peer.get_address_family() == iface_ip.get_address_family()
&& same_subnet(peer, iface_ip, iface_subnet_mask)) {
return iface_ip;
}
}
}
return IpAddress();
}
void SsdpServiceImpl::process_ssdp_m_search(const SsdpPacket& packet,
const SocketAddress& sender,
const IpAddress& lan_address) {
const auto& st_header = packet.get_header(SsdpPacket::ST);
if (st_header == SSDP_ALL_STR || st_header == m_config->get_service_urn()) {
auto delay = calculate_delay(packet.get_header(SsdpPacket::MX));
auto search_response = m_ssdp_packet_factory.create_ssdp_packet(
SsdpPacket::Type::SEARCH_RESPONSE);
URI service_uri{m_config->get_service_url()};
service_uri.set_host(lan_address.to_string());
search_response.set_header(SsdpPacket::AL, service_uri.to_string());
ScheduledMessage msg(m_listen_socket, sender,
std::make_shared<const std::string>(search_response.to_string()));
m_queue.send_or_enqueue(msg, delay);
m_queue.send_or_enqueue(msg, delay + Ms(DELAY_INCREMENT));
}
else {
log_debug(GET_LOGGER("ssdp"),
"ignoring SSDP " << packet.get_type().to_string() << " packet.");
}
}
void SsdpServiceImpl::send_alive() {
if (!m_config->is_announcement_enabled() || m_notify_sockets.empty()) {
return;
}
log_debug(GET_LOGGER("ssdp"), "sending ssdp notifies");
auto ssdp_alive_packet = m_ssdp_packet_factory.create_ssdp_packet(
SsdpPacket::Type::NOTIFY);
URI service_uri{ssdp_alive_packet.get_header(SsdpPacket::AL)};
for (auto& sock: m_notify_sockets) {
service_uri.set_host(sock.get_address().get_host().to_string());
ssdp_alive_packet.set_header(SsdpPacket::AL, service_uri.to_string());
ScheduledMessage msg(sock, SsdpService::SSDP_MCAST_ADDRESS,
std::make_shared<const std::string>(ssdp_alive_packet.to_string()));
m_queue.send_or_enqueue(msg);
m_queue.send_or_enqueue(msg, Ms(SCHEDULED_DELAY));
}
}
void SsdpServiceImpl::send_byebye() {
if (!m_config->is_announcement_enabled() || m_notify_sockets.empty()) {
return;
}
log_info(GET_LOGGER("ssdp"), "sending ssdp byebye");
try {
auto bye_payload = std::make_shared<const std::string>(m_ssdp_packet_factory.create_ssdp_packet(
SsdpPacketKey{SsdpPacket::Type::NOTIFY,
SsdpPacket::SSDP_BYEBYE_STR}).to_string());
for (auto& sock : m_notify_sockets) {
ScheduledMessage msg(sock, SsdpService::SSDP_MCAST_ADDRESS, bye_payload);
msg.try_send();
}
std::this_thread::sleep_for(Ms(SCHEDULED_DELAY));
for (auto& sock : m_notify_sockets) {
ScheduledMessage msg(sock, SsdpService::SSDP_MCAST_ADDRESS, bye_payload);
msg.try_send();
}
}
catch (const std::exception& e) {
log_error(GET_LOGGER("ssdp"), "Failed to send byebye: " << e.what()
<< "\n" << get_debug_network_status_info());
}
catch (...) {
log_error(GET_LOGGER("ssdp"), "Failed to send byebye.\n"
<< get_debug_network_status_info());
}
}
void SsdpServiceImpl::process_ssdp_request() {
try {
SocketAddress sender;
auto packet = receive_packet(sender);
log_debug(GET_LOGGER("ssdp"), "from:" << sender << " packet:\n"
<< packet.to_string());
auto lan_address = find_lan_of_peer(sender.get_host());
if (lan_address.is_any_address()) {
log_debug(GET_LOGGER("ssdp"),
"ignoring packet on non SSDP enabled interface.");
return;
}
if (!validate_ssdp_packet(packet)) {
log_debug(GET_LOGGER("ssdp"), "ignoring invalid SSDP packet.");
return;
}
if (!packet.is_search_request()) {
log_debug(GET_LOGGER("ssdp"),
"ignoring SSDP " << packet.get_type().to_string() << " packet.");
return;
}
process_ssdp_m_search(packet, sender, lan_address);
}
catch (std::exception e) {
log_error(GET_LOGGER("ssdp"), e.what());
}
catch (...) {
log_error(GET_LOGGER("ssdp"), "Unknown exception :(");
}
}
SsdpPacket SsdpServiceImpl::receive_packet(SocketAddress& sender) {
static std::vector<char> buffer(PACKET_SIZE);
std::fill(buffer.begin(), buffer.end(), 0);
auto n = m_listen_socket.receive_from(buffer.data(), buffer.size(), sender);
SsdpPacketParser<decltype(buffer)> parser(buffer, n);
return parser.parse();
}
void SsdpServiceImpl::init() {
m_listen_socket = open_ssdp_listen_socket(
SsdpService::SSDP_MCAST_ADDRESS.get_port());
try {
const auto iface_list = NetworkInterface::get_interfaces();
const auto& iface_names = m_config->get_nic_names();
for (const auto& iface : iface_list) {
if (!is_iface_ignored(iface_names, iface.get_name())
&& iface.is_up()
&& iface.is_running()) {
try {
link_insert_or_update(m_network_interfaces.end(), iface);
}
catch (const std::exception& e) {
log_error(GET_LOGGER("ssdp"), "SSDP configuration on network interface "
<< iface.get_name() << " failed: " << e.what());
}
}
}
}
catch (const std::exception& e) {
log_error(GET_LOGGER("ssdp"), "SSDP network configuration error: " << e.what());
}
log_info(GET_LOGGER("ssdp"), get_debug_network_status_info());
std::srand(uint(std::time(0)));
}
void SsdpServiceImpl::start() {
if (!m_config->is_ssdp_service_enabled()) {
log_info(GET_LOGGER("ssdp"), "SSDP service is disabled.");
return;
}
if (!is_running()) {
m_is_running = true;
m_thread = std::thread(&SsdpServiceImpl::execute, this);
}
}
void SsdpServiceImpl::stop() {
if (is_running()) {
post_notification(ShutDownNotification{});
m_is_running = false;
if (m_thread.joinable()) {
m_thread.join();
}
}
}
void SsdpServiceImpl::link_update(NetworkInterfaceMap::iterator it, const NetworkInterface& updated_iface) {
if (it != m_network_interfaces.end()) {
auto& cached_iface = it->second;
if (m_config->is_announcement_enabled()) {
const auto diff = addresses_difference(cached_iface, updated_iface);
update_mcast_notify_sockets_list(m_notify_sockets, cached_iface, updated_iface, m_config->get_socket_ttl());
}
leave_or_join_mcast_group(m_listen_socket, SsdpService::SSDP_MCAST_ADDRESS, cached_iface, updated_iface);
// update cache
cached_iface = updated_iface;
}
}
void SsdpServiceImpl::link_remove(NetworkInterfaceMap::iterator it) {
if (it != m_network_interfaces.end()) {
NetworkInterface empty;
link_update(it, empty);
m_network_interfaces.erase(it);
log_info(GET_LOGGER("ssdp"), get_debug_network_status_info());
}
}
void SsdpServiceImpl::link_insert_or_update(NetworkInterfaceMap::iterator it,
const NetworkInterface& updated_iface) {
if (it == m_network_interfaces.end()) {
it = m_network_interfaces.emplace(updated_iface.get_index(), NetworkInterface{}).first;
}
link_update(it, updated_iface);
log_info(GET_LOGGER("ssdp"), get_debug_network_status_info());
}
void SsdpServiceImpl::on_network_change(unsigned iface_index,
net::NetworkChangeNotifier::ChangeType) {
auto cached_iface = m_network_interfaces.find(iface_index);
const auto ifaces = NetworkInterface::get_interfaces_map();
auto ifaces_iterator = ifaces.find(iface_index);
if (ifaces_iterator == ifaces.cend()) {
link_remove(cached_iface);
}
else {
const auto& updated_iface = ifaces_iterator->second;
if (is_iface_ignored(m_config->get_nic_names(), updated_iface.get_name())) {
return;
}
if (!(updated_iface.is_up() && updated_iface.is_running())) {
link_remove(cached_iface);
}
else {
link_insert_or_update(cached_iface, updated_iface);
}
}
}
void SsdpServiceImpl::post_notification(const Notification& notification) {
if (is_running()) {
auto bytes = notification.serialize();
m_notification_pipe.first.send_bytes(bytes.data(), bytes.size());
}
}
void SsdpServiceImpl::process_notification() {
Notification::Bytes bytes(Notification::MAX_SERIALIZED_SIZE);
auto n = m_notification_pipe.second.receive_bytes(bytes.data(), bytes.size());
if(bytes.empty()) {
log_error(GET_LOGGER("ssdp"), "Received empty notification");
return;
}
const auto notification_type = static_cast<Notification::Type>(bytes[0]);
switch (notification_type) {
case Notification::Type::SHUT_DOWN:
on_shutdown(bytes, n);
break;
case Notification::Type::NETWORK_CHANGE:
on_network_change(bytes, n);
break;
default:
log_error(GET_LOGGER("ssdp"), "Received unknown notification type:"
<< static_cast<int>(notification_type));
break;
}
}
void SsdpServiceImpl::on_network_change(const Notification::Bytes& bytes,
const Notification::Bytes::size_type bytes_length) {
NetworkChangeNotification notification;
notification.deserialize(bytes, bytes_length);
on_network_change(notification.get_iface_index(), notification.get_change_type());
}
void SsdpServiceImpl::on_shutdown(const Notification::Bytes& bytes,
const Notification::Bytes::size_type bytes_length) {
ShutDownNotification notification;
notification.deserialize(bytes, bytes_length);
m_is_running = false;
}
void SsdpServiceImpl::execute() {
try {
init();
log_info(GET_LOGGER("ssdp"), "SSDP service started.");
}
catch (...) {
log_error(GET_LOGGER("ssdp"), "Failed to initialize SSDP service.");
return;
}
Socket::List readable{}, writable{}, except{};
const auto check_interval = get_check_interval(*m_config);
Ms timeout = check_interval;
auto last_announce_time =
std::chrono::time_point_cast<Ms>(std::chrono::steady_clock::now())
- check_interval;
auto& notification_socket = m_notification_pipe.second;
while (is_running()) {
try {
readable.clear();
writable.clear();
except.clear();
timeout = check_interval;
auto now = std::chrono::time_point_cast<Ms>(std::chrono::steady_clock::now());
auto elapsed = now - last_announce_time;
if (elapsed >= check_interval) {
send_alive();
last_announce_time += elapsed;
}
else {
timeout -= elapsed;
}
m_queue.select_ready_messages(writable, now, timeout);
readable.push_back(m_listen_socket);
readable.push_back(notification_socket);
if (Socket::select(readable, writable, except, timeout)) {
for (const auto& socket : readable) {
if (socket == m_listen_socket) {
process_ssdp_request();
}
else if (socket == notification_socket) {
process_notification();
}
}
}
m_queue.send_ready_messages(writable);
}
catch (const std::exception& e) {
log_error(GET_LOGGER("ssdp"), "Exception: " << e.what()
<< "\n" << get_debug_network_status_info());
}
catch (...) {
log_error(GET_LOGGER("ssdp"), "Unknown exception :("
<< "\n" << get_debug_network_status_info());
}
}
send_byebye();
log_info(GET_LOGGER("ssdp"), "SSDP service stopped.");
}
std::string SsdpServiceImpl::get_debug_network_status_info() const {
std::ostringstream ostream;
ostream << "SSDP active on interfaces:";
auto it = m_network_interfaces.cbegin();
for (; it != m_network_interfaces.cend(); ++it) {
ostream << "\n " << it->second.get_name()
<< " #" << it->second.get_index();
for (const auto& address : it->second.get_address_list()) {
ostream << "\n " << std::get<net::NetworkInterface::IP_ADDRESS>(address);
}
}
ostream << "\n open notification sockets:\n";
for (auto socket = m_notify_sockets.cbegin(); socket != m_notify_sockets.cend(); ++socket) {
ostream << " " << socket->get_address() << "\n";
}
return ostream.str();
}
|
constexpr int N = 1e8;
vector<bool> isPrime(N + 1, true);
vector<int> primeNumbers;
void sieveOfEratosthenes() {
isPrime[0] = isPrime[1] = false;
for (int i = 2; i <= N; ++i) {
if (isPrime[i]) {
primeNumbers.push_back(i);
for (int j = 2 * i; j <= N; j += i) {
isPrime[j] = false;
}
}
}
}
|
//
// FILE NAME: CIDXML_EntityDecl.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 08/21/1999
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the header file for the CIDXML_EntityDecl.Cpp file, which
// implements the TXMLEntityDecl class. This class is the basic abstraction
// that all entity declarations used by any validator must implement. This
// is the abstraction through which the core parser can deal with any
// validator's entity declaration variations.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TXMLEntityDecl
// PREFIX: xdecl
// ---------------------------------------------------------------------------
class CIDXMLEXP TXMLEntityDecl : public TObject
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
~TXMLEntityDecl();
// -------------------------------------------------------------------
// Public, virtual methods
// -------------------------------------------------------------------
virtual tCIDLib::TVoid FormatTo
(
TTextOutStream& strmDest
, const TXMLValidator& xvalPools
) const = 0;
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bIsExternal() const;
tCIDLib::TBoolean bIsInternal() const;
tCIDLib::TBoolean bIsSpecial() const;
tCIDLib::TBoolean bIsSpecial
(
const tCIDLib::TBoolean bNewValue
);
tCIDLib::TBoolean bIsUnparsed() const;
tCIDLib::TCard4 c4Id() const;
tCIDLib::TCard4 c4Id
(
const tCIDLib::TCard4 c4NewId
);
const TString& strName() const;
const TString& strName
(
const TString& strName
);
const TString& strName
(
const tCIDLib::TCh* const pszName
);
const TString& strValue() const;
const TString& strValue
(
const TString& strValue
);
const TString& strValue
(
const tCIDLib::TCh* const pszValue
);
const TString& strNotationName() const;
const TString& strNotationName
(
const TString& strName
);
const TString& strNotationName
(
const tCIDLib::TCh* const pszName
);
const TString& strPublicId() const;
const TString& strPublicId
(
const TString& strId
);
const TString& strPublicId
(
const tCIDLib::TCh* const pszId
);
const TString& strSystemId() const;
const TString& strSystemId
(
const TString& strId
);
const TString& strSystemId
(
const tCIDLib::TCh* const pszId
);
protected :
// -------------------------------------------------------------------
// Hidden constructors and operators
// -------------------------------------------------------------------
TXMLEntityDecl();
TXMLEntityDecl
(
const TString& strName
);
TXMLEntityDecl
(
const TString& strName
, const TString& strValue
);
TXMLEntityDecl
(
const tCIDLib::TCh* const pszEntityName
);
TXMLEntityDecl
(
const tCIDLib::TCh* const pszEntityName
, const tCIDLib::TCh* const pszEntityValue
);
TXMLEntityDecl
(
const TXMLEntityDecl& xdeclToCopy
);
TXMLEntityDecl& operator=
(
const TXMLEntityDecl& xdeclToAssign
);
private :
// -------------------------------------------------------------------
// Private data members
//
// m_bSpecial
// This is set if the entity is one of the special intrinsic
// character entities.
//
// m_c4Id
// The id of this entity in its pool. This will be set by the
// pool when this object is inserted.
//
// m_c4ValueLen
// If the entity is internal, then m_pstrValue holds its
// value, and this holds its length. Since this is needed in
// order to quickly create a spoolers, we do it once and store
// it.
//
// m_strName
// This is the name of the entity, which is defined in the DTD
// or Schema (or whatever type of validator) text.
//
// m_strValue
// This is the entity value if the entity is internal. If the
// entity is an external one, then this never gets created.
//
// m_strNotationName
// If the entity declaration referenced a notation, then it is
// stored here. Otherwise its empty.
//
// m_strPublicId
// The public id (if any) that was parsed from the entity decl.
// It can be empty since only the system id is required.
//
// m_strSystemId
// The system id that was parsed from the entity decl. It is
// required so it will not be empty in a valid parse.
// -------------------------------------------------------------------
tCIDLib::TBoolean m_bSpecial;
tCIDLib::TCard4 m_c4Id;
tCIDLib::TCard4 m_c4ValueLen;
TString m_strName;
TString m_strValue;
TString m_strNotationName;
TString m_strPublicId;
TString m_strSystemId;
// -------------------------------------------------------------------
// Do any needed magic macros
// -------------------------------------------------------------------
RTTIDefs(TXMLEntityDecl,TObject)
};
#pragma CIDLIB_POPPACK
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020 The Bitcoin Global developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/fees.h>
#include <util/system.h>
#include <wallet/coincontrol.h>
#include <wallet/wallet.h>
CAmount GetRequiredFee(const CWallet& wallet, unsigned int nTxBytes)
{
return GetRequiredFeeRate(wallet).GetFee(nTxBytes);
}
CAmount GetMinimumFee(const CWallet& wallet, unsigned int nTxBytes, const CCoinControl& coin_control, FeeCalculation* feeCalc)
{
return GetMinimumFeeRate(wallet, coin_control, feeCalc).GetFee(nTxBytes);
}
CFeeRate GetRequiredFeeRate(const CWallet& wallet)
{
return std::max(wallet.m_min_fee, wallet.chain().relayMinFee());
}
CFeeRate GetMinimumFeeRate(const CWallet& wallet, const CCoinControl& coin_control, FeeCalculation* feeCalc)
{
/* User control of how to calculate fee uses the following parameter precedence:
1. coin_control.m_feerate
2. coin_control.m_confirm_target
3. m_pay_tx_fee (user-set member variable of wallet)
4. m_confirm_target (user-set member variable of wallet)
The first parameter that is set is used.
*/
CFeeRate feerate_needed;
if (coin_control.m_feerate) { // 1.
feerate_needed = *(coin_control.m_feerate);
if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
// Allow to override automatic min/max check over coin control instance
if (coin_control.fOverrideFeeRate) return feerate_needed;
}
else if (!coin_control.m_confirm_target && wallet.m_pay_tx_fee != CFeeRate(0)) { // 3. TODO: remove magic value of 0 for wallet member m_pay_tx_fee
feerate_needed = wallet.m_pay_tx_fee;
if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
}
else { // 2. or 4.
// We will use smart fee estimation
unsigned int target = coin_control.m_confirm_target ? *coin_control.m_confirm_target : wallet.m_confirm_target;
// By default estimates are economical iff we are signaling opt-in-RBF
bool conservative_estimate = !coin_control.m_signal_bip125_rbf.get_value_or(wallet.m_signal_rbf);
// Allow to override the default fee estimate mode over the CoinControl instance
if (coin_control.m_fee_mode == FeeEstimateMode::CONSERVATIVE) conservative_estimate = true;
else if (coin_control.m_fee_mode == FeeEstimateMode::ECONOMICAL) conservative_estimate = false;
feerate_needed = wallet.chain().estimateSmartFee(target, conservative_estimate, feeCalc);
if (feerate_needed == CFeeRate(0)) {
// if we don't have enough data for estimateSmartFee, then use fallback fee
feerate_needed = wallet.m_fallback_fee;
if (feeCalc) feeCalc->reason = FeeReason::FALLBACK;
// directly return if fallback fee is disabled (feerate 0 == disabled)
if (wallet.m_fallback_fee == CFeeRate(0)) return feerate_needed;
}
// Obey mempool min fee when using smart fee estimation
CFeeRate min_mempool_feerate = wallet.chain().mempoolMinFee();
if (feerate_needed < min_mempool_feerate) {
feerate_needed = min_mempool_feerate;
if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN;
}
}
// prevent user from paying a fee below the required fee rate
CFeeRate required_feerate = GetRequiredFeeRate(wallet);
if (required_feerate > feerate_needed) {
feerate_needed = required_feerate;
if (feeCalc) feeCalc->reason = FeeReason::REQUIRED;
}
return feerate_needed;
}
CFeeRate GetDiscardRate(const CWallet& wallet)
{
unsigned int highest_target = wallet.chain().estimateMaxBlocks();
CFeeRate discard_rate = wallet.chain().estimateSmartFee(highest_target, false /* conservative */);
// Don't let discard_rate be greater than longest possible fee estimate if we get a valid fee estimate
discard_rate = (discard_rate == CFeeRate(0)) ? wallet.m_discard_rate : std::min(discard_rate, wallet.m_discard_rate);
// Discard rate must be at least dustRelayFee
discard_rate = std::max(discard_rate, wallet.chain().relayDustFee());
return discard_rate;
}
|
#include "PapyrusForm.h"
#include "GameForms.h"
#include "GameRTTI.h"
#include "PapyrusVM.h"
#include "PapyrusEvents.h"
#include "GameMenus.h"
namespace papyrusForm
{
UInt32 GetType(TESForm* thisForm)
{
return (thisForm) ? thisForm->GetFormType() : 0;
}
BSFixedString GetName(TESForm* thisForm)
{
if (!thisForm)
return NULL;
TESFullName* pFullName = DYNAMIC_CAST(thisForm, TESForm, TESFullName);
if (pFullName)
return pFullName->name.data;
return NULL;
}
void SetName(TESForm* thisForm, BSFixedString nuName)
{
TESFullName* pFullName = DYNAMIC_CAST(thisForm, TESForm, TESFullName);
// is a const string, so have to just reassign it.
if (pFullName) {
pFullName->name = nuName;
}
}
float GetWeight(TESForm* thisForm)
{
if (!thisForm)
return 0.0;
TESWeightForm* pWeight = DYNAMIC_CAST(thisForm, TESForm, TESWeightForm);
if (pWeight)
return pWeight->weight;
return 0.0;
}
void SetWeight(TESForm* thisForm, float nuWeight)
{
if (!thisForm)
return;
TESWeightForm* pWeight = DYNAMIC_CAST(thisForm, TESForm, TESWeightForm);
if (pWeight)
pWeight->weight = nuWeight;
}
UInt32 GetBaseDamage(TESForm* thisForm)
{
if (!thisForm)
return 0;
TESAttackDamageForm* pAttack = DYNAMIC_CAST(thisForm, TESForm, TESAttackDamageForm);
if (pAttack)
return pAttack->GetAttackDamage();
return 0;
}
UInt32 GetValue(TESForm* thisForm)
{
if (!thisForm)
return 0;
TESValueForm* pValue = DYNAMIC_CAST(thisForm, TESForm, TESValueForm);
if (pValue)
return pValue->value;
return 0;
}
void SetGoldValue(TESForm* thisForm, UInt32 value)
{
if (!thisForm)
return;
TESValueForm* pValue = DYNAMIC_CAST(thisForm, TESForm, TESValueForm);
if (pValue)
pValue->value = value;
}
UInt32 GetNumKeywords(TESForm* thisForm)
{
if (!thisForm)
return 0;
BGSKeywordForm* pKeywords = DYNAMIC_CAST(thisForm, TESForm, BGSKeywordForm);
if (pKeywords)
return pKeywords->numKeywords;
return 0;
}
BGSKeyword* GetNthKeyword(TESForm* thisForm, UInt32 index)
{
if (!thisForm)
return NULL;
BGSKeywordForm* pKeywords = DYNAMIC_CAST(thisForm, TESForm, BGSKeywordForm);
if (pKeywords && index < pKeywords->numKeywords) {
return pKeywords->keywords[index];
}
return NULL;
}
void RegisterForKey(TESForm * thisForm, UInt32 key)
{
g_inputEventRegs.Register(thisForm, key);
}
void UnregisterFromKey(TESForm * thisForm, UInt32 key)
{
g_inputEventRegs.Unregister(thisForm, key);
}
void UnregisterFromAllKeys(TESForm * thisForm)
{
g_inputEventRegs.UnregisterFromAll(thisForm);
}
void UpdateKeys(UInt8 * data)
{
/*static UInt8 oldState[0x100] = { 0 };
if(!*g_skyrimVM) return;
// ### this is off because it's a super temp hack
BSFixedString eventName("OnKeyDown");
VMClassRegistry * registry = (*g_skyrimVM)->GetClassRegistry();
for(UInt32 i = 0; i < 0x100; i++)
{
if(!oldState[i] && data[i])
{
RegisteredKeyMap::iterator registeredHandles = g_regKeyMap.find(i);
if(registeredHandles != g_regKeyMap.end())
{
for(HandleList::iterator iter = registeredHandles->second.begin(); iter != registeredHandles->second.end(); ++iter)
{
OneIntArg args(i);
registry->QueueEvent(*iter, &eventName, &args);
}
}
}
oldState[i] = data[i];
}*/
}
void RegisterForMenu(TESForm * thisForm, BSFixedString menuName)
{
if (!menuName.data)
return;
// Will only be added once. TODO move this somewhere else.
MenuManager * mm = MenuManager::GetSingleton();
if (mm)
mm->MenuOpenCloseEventDispatcher()->AddEventSink(&g_skseEventHandler);
if (*g_inputEventDispatcher)
(*g_inputEventDispatcher)->AddEventSink(&g_skseEventHandler);
g_menuOpenCloseRegs.Register(thisForm, menuName);
}
void UnregisterFromMenu(TESForm * thisForm, BSFixedString menuName)
{
if (!menuName.data)
return;
g_menuOpenCloseRegs.Unregister(thisForm, menuName);
}
void UnregisterFromAllMenus(TESForm * thisForm)
{
g_menuOpenCloseRegs.UnregisterFromAll(thisForm);
}
void RegisterForModEvent(TESForm * thisForm, BSFixedString eventName, BSFixedString callbackName)
{
if (!eventName.data || !callbackName.data)
return;
// TODO
g_modCallbackEventDispatcher.AddEventSink(&g_skseEventHandler);
ModCallbackParameters params;
params.callbackName = callbackName;
g_modCallbackRegs.Register(thisForm, eventName, ¶ms);
}
void UnregisterFromModEvent(TESForm * thisForm, BSFixedString eventName)
{
if (!eventName.data)
return;
g_modCallbackRegs.Unregister(thisForm, eventName);
}
void UnregisterFromAllModEvents(TESForm * thisForm)
{
g_modCallbackRegs.UnregisterFromAll(thisForm);
}
void SendModEvent(TESForm * thisForm, BSFixedString eventName, BSFixedString message)
{
if (!eventName.data)
return;
SKSEModCallbackEvent evn(eventName, message);
g_modCallbackEventDispatcher.SendEvent(&evn);
}
}
#include "PapyrusVM.h"
#include "PapyrusNativeFunctions.h"
void papyrusForm::RegisterFuncs(VMClassRegistry* registry)
{
registry->RegisterFunction(
new NativeFunction0 <TESForm, UInt32> ("GetType", "Form", papyrusForm::GetType, registry));
registry->RegisterFunction(
new NativeFunction0 <TESForm, BSFixedString> ("GetName", "Form", papyrusForm::GetName, registry));
registry->RegisterFunction(
new NativeFunction1 <TESForm, void, BSFixedString> ("SetName", "Form", papyrusForm::SetName, registry));
registry->RegisterFunction(
new NativeFunction0 <TESForm, float> ("GetWeight", "Form", papyrusForm::GetWeight, registry));
registry->RegisterFunction(
new NativeFunction1 <TESForm, void, float> ("SetWeight", "Form", papyrusForm::SetWeight, registry));
registry->RegisterFunction(
new NativeFunction1 <TESForm, void, UInt32> ("SetGoldValue", "Form", papyrusForm::SetGoldValue, registry));
registry->RegisterFunction(
new NativeFunction0 <TESForm, UInt32> ("GetNumKeywords", "Form", papyrusForm::GetNumKeywords, registry));
registry->RegisterFunction(
new NativeFunction1 <TESForm, BGSKeyword *, UInt32> ("GetNthKeyword", "Form", papyrusForm::GetNthKeyword, registry));
registry->RegisterFunction(
new NativeFunction1 <TESForm, void, UInt32> ("RegisterForKey", "Form", papyrusForm::RegisterForKey, registry));
registry->RegisterFunction(
new NativeFunction1 <TESForm, void, UInt32> ("UnregisterFromKey", "Form", papyrusForm::UnregisterFromKey, registry));
registry->RegisterFunction(
new NativeFunction0 <TESForm, void> ("UnregisterFromAllKeys", "Form", papyrusForm::UnregisterFromAllKeys, registry));
registry->RegisterFunction(
new NativeFunction1 <TESForm, void, BSFixedString> ("RegisterForMenu", "Form", papyrusForm::RegisterForMenu, registry));
registry->RegisterFunction(
new NativeFunction1 <TESForm, void, BSFixedString> ("UnregisterFromMenu", "Form", papyrusForm::UnregisterFromMenu, registry));
registry->RegisterFunction(
new NativeFunction0 <TESForm, void> ("UnregisterFromAllMenus", "Form", papyrusForm::UnregisterFromAllMenus, registry));
registry->RegisterFunction(
new NativeFunction2 <TESForm, void, BSFixedString, BSFixedString> ("RegisterForModEvent", "Form", papyrusForm::RegisterForModEvent, registry));
registry->RegisterFunction(
new NativeFunction2 <TESForm, void, BSFixedString, BSFixedString> ("SendModEvent", "Form", papyrusForm::SendModEvent, registry));
registry->RegisterFunction(
new NativeFunction1 <TESForm, void, BSFixedString> ("UnregisterFromModEvent", "Form", papyrusForm::UnregisterFromModEvent, registry));
registry->RegisterFunction(
new NativeFunction0 <TESForm, void> ("UnregisterFromAllModEvents", "Form", papyrusForm::UnregisterFromAllModEvents, registry));
}
|
#include "physics_helpers.h"
//---------------------------------------------------------
double physics_helpers::current_speed(double dx, double dy)
{
return std::sqrt(dx*dx + dy*dy);
}
|
#include "lua_helper.h"
#include "storm.h"
#include <base/path/service.h>
#include <base/path/helper.h>
#include <base/util/unicode.h>
#include <boost/assign.hpp>
namespace base { namespace warcraft3 { namespace lua_engine {
int storm_load(lua::state* ls)
{
const char* path = ls->tostring(1);
if (!path)
{
ls->pushnil();
return 1;
}
const void* buf_data = nullptr;
size_t buf_size = 0;
storm&s = storm_s::instance();
if (!s.load_file(path, &buf_data, &buf_size))
{
ls->pushnil();
return 1;
}
ls->pushlstring((const char*)buf_data, buf_size);
s.unload_file(buf_data);
return 1;
}
bool storm_path_valid(const boost::filesystem::path& root_path, const boost::filesystem::path& file_path)
{
static std::set<std::wstring> s_blacklist = boost::assign::list_of
(L"mix")(L"asi")(L"m3d")(L"flt")(L"flt")
(L"exe")(L"dll")
;
std::wstring ext = file_path.extension().wstring().substr(1, 4);
std::transform(ext.begin(), ext.end(), ext.begin(), ::towlower);
if (s_blacklist.find(ext) != s_blacklist.end())
{
return false;
}
for (boost::filesystem::path p = file_path.parent_path(); !p.empty(); p = p.parent_path())
{
if (base::path::equal(p, root_path))
{
return true;
}
}
return false;
}
int storm_save(lua::state* ls)
{
const char* path = ls->tostring(1);
const char* buf_data = ls->tostring(2);
size_t buf_size = ls->rawlen(2);
try {
if (path && buf_data && buf_size)
{
boost::filesystem::path root_path = base::path::get(base::path::DIR_EXE).remove_filename();
boost::filesystem::path file_path = root_path / base::util::u2w(path);
if (storm_path_valid(root_path, file_path))
{
std::fstream fs(file_path.c_str(), std::ios::binary | std::ios::out);
if (fs.is_open())
{
std::copy(buf_data, buf_data + buf_size, std::ostreambuf_iterator<char>(fs));
ls->pushboolean(1);
return 1;
}
}
}
} catch (...) { }
ls->pushboolean(0);
return 1;
}
int jass_storm(lua::state* ls)
{
ls->newtable();
{
ls->pushstring("load");
ls->pushcclosure(storm_load, 0);
ls->rawset(-3);
ls->pushstring("save");
ls->pushcclosure(storm_save, 0);
ls->rawset(-3);
}
return 1;
}
}}}
|
/*
* Copyright (C) 2003-2005 Tommi Maekitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tnt/ecpp/parser.h"
#include "tnt/ecpp/parsehandler.h"
#include <sstream>
#include <fstream>
#include <cctype>
#include <cxxtools/log.h>
log_define("tntnet.parser")
namespace tnt
{
namespace
{
inline bool isVariableNameChar(char ch)
{
return std::isalnum(ch) || ch == '_';
}
}
namespace ecpp
{
static const char split_start = '{';
static const char split_end = '}';
void Parser::doInclude(const std::string& file)
{
log_debug("include \"" << file << '"');
std::string fullname = file;
std::ifstream inp(file.c_str());
for (includes_type::const_iterator it = includes.begin();
!inp && it != includes.end(); ++it)
{
fullname = *it + '/' + file;
log_debug("try include \"" << fullname << '"');
inp.open(fullname.c_str());
}
if (!inp)
{
std::ostringstream msg;
throw std::runtime_error("cannot open include file \"" + file + '"');
}
std::string curfileSave = curfile;
unsigned curlineSave = curline;
curfile = fullname;
curline = 0;
log_debug("onInclude(\"" << fullname << "\")");
handler.onInclude(fullname);
parsePriv(inp);
curfile = curfileSave;
curline = curlineSave;
log_debug("onIncludeEnd(\"" << fullname << "\")");
handler.onIncludeEnd(fullname);
}
void Parser::parsePriv(std::istream& in)
{
enum state_type {
state_html0, // 0
state_html,
state_htmlesc,
state_tagstart,
state_expr,
state_expre0,
state_tag,
state_tagarg0,
state_tagarg,
state_tagarge,
state_defarg0, // 10
state_defarg,
state_defargdefval0,
state_defargdefval,
state_defarg_end,
state_cpp,
state_cppse,
state_cppe0,
state_cppe1,
state_cppetag,
state_cppstring, // 20
state_cppstringesc,
state_cppchar,
state_cppcharesc,
state_cppchare,
state_cppcomment0,
state_cppcomment,
state_cppcommentc,
state_cppcommentce,
state_nl,
state_cpp1,
state_args0,
state_args0comment,
state_argsvar, // 30
state_argsvare,
state_argsval,
state_argsvalstring,
state_argscomment0,
state_argscomment,
state_argsvalcomment0,
state_attr0,
state_attr0comment,
state_attrvar,
state_attrvare, // 40
state_attrval,
state_attrvalstring,
state_attrcomment0,
state_attrcomment,
state_attrvalcomment0,
state_call0,
state_callname_expr,
state_callname_string,
state_callname,
state_call_cpparg0, // 50
state_call_cpparg1,
state_call_cpparg_pe,
state_call_cpparg_sp,
state_call_cpparg_e,
state_callend,
state_callarg0,
state_callarg,
state_callarge,
state_callval_expr,
state_callval_string, // 60
state_callval_word,
state_callval0,
state_callvale,
state_comment,
state_commente,
state_compe0,
state_compe,
state_cond0,
state_cond,
state_condexpr,
state_condexpre, // 70
state_include0,
state_include1,
state_scopearg0,
state_scopearg,
state_scopeargeq,
state_scopeargval0,
state_scopeargval,
state_scopevale,
state_scope0,
state_scope, // 80
state_scopeinit,
state_scopeiniteq,
state_scopee,
state_scopee0,
state_scopecomment0,
state_scopecomment,
state_endcall0,
state_endcall,
state_endcalle,
state_doc, // 90
state_doce
};
state_type state = state_nl;
std::string tag, etag, tagarg;
std::string html, code, arg, argtype, value;
std::string comp;
std::string cond, expr;
comp_args_type comp_args;
std::string pass_cgi;
std::string defarg, defval, paramname;
cppargs_type cppargs;
paramargs_type paramargs;
unsigned bracket_count = 0;
std::string scopetype, scopevar, scopeinit;
scope_container_type scope_container = application_container;
scope_type scope = global_scope;
bool inComp = false;
bool inClose = false;
bool htmlExpr = false;
bool splitBar = false;
handler.start();
char ch;
while (in.get(ch))
{
if (ch == '\n')
++curline;
switch(state)
{
case state_html0:
if (ch == ' ' || ch == '\t')
std::cerr << curfile << ':' << curline + 1 << ": warning: trailing white space after closing tag" << std::endl;
else if (ch == '\r')
std::cerr << curfile << ':' << curline + 1 << ": warning: trailing cr after closing tag (dos format?)" << std::endl;
// no break - continue with state_html
case state_html:
if (ch == '<')
{
state = state_tagstart;
}
else if (ch == '\n')
{
if (state == state_html || !html.empty())
html += ch;
state = state_nl;
}
else if (splitBar && (ch == split_start|| ch == split_end))
{
if (!html.empty() || ch == split_end)
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
html.clear();
}
handler.tokenSplit(ch == split_start);
}
else if (ch == '\\')
state = state_htmlesc;
else
{
html += ch;
state = state_html;
}
break;
case state_htmlesc:
if (ch != '\n')
html += ch;
state = state_html;
break;
case state_tagstart:
if (ch == '%')
{
if (!html.empty())
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
html.clear();
}
tag.clear();
handler.onLine(curline, curfile); //#
state = state_tag;
}
else if (ch == '$')
{
if (!html.empty())
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
html.clear();
}
handler.onLine(curline, curfile); //#
state = state_expr;
}
else if (ch == '&')
{
if (!html.empty())
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
html.clear();
}
handler.onLine(curline, curfile); //#
state = state_call0;
}
else if (ch == '#')
{
if (!html.empty())
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
html.clear();
}
state = state_comment;
}
else if (ch == '{')
{
if (!html.empty())
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
html.clear();
}
handler.onLine(curline, curfile); //#
state = state_cpp;
}
else if (ch == '?')
{
if (!html.empty())
{
handler.onHtml(html);
html.clear();
}
handler.onLine(curline, curfile); //#
state = state_cond0;
}
else if (ch == '/')
{
state = state_compe0;
}
else if (ch == '\\')
{
html += '<';
state = state_html;
}
else
{
html += '<';
html += ch;
state = state_html;
}
break;
case state_expr:
if (ch == '$')
{
if (!htmlExpr && code.empty())
// <$$ ... $>
htmlExpr = true;
else
// expression might end
state = state_expre0;
}
else
code += ch;
break;
case state_expre0:
if (ch == '>')
{
// expression ends, html continues
if (htmlExpr)
{
log_debug("onHtmlExpression(\"" << code << "\")");
handler.onHtmlExpression(code);
htmlExpr = false;
}
else
{
log_debug("onExpression(\"" << code << "\")");
handler.onExpression(code);
}
code.clear();
state = state_html;
}
else
{
// expression does not end
code += '$';
code += ch;
if (ch != '$')
state = state_expr;
}
break;
case state_tag:
if (ch == '>')
{
if (tag == "args" || tag == "get" || tag == "post" || tag == "config")
state = state_args0;
else if (tag == "attr")
state = state_attr0;
else if (tag == "include")
state = state_include0;
else if (tag == "application")
{
scope_container = application_container;
scope = component_scope;
state = state_scope0;
}
else if (tag == "thread")
{
scope_container = thread_container;
scope = component_scope;
state = state_scope0;
}
else if (tag == "session")
{
scope_container = session_container;
scope = component_scope;
state = state_scope0;
}
else if (tag == "securesession")
{
scope_container = secure_session_container;
scope = component_scope;
state = state_scope0;
}
else if (tag == "request")
{
scope_container = request_container;
scope = component_scope;
state = state_scope0;
}
else if (tag == "param")
{
scope_container = param_container;
scope = component_scope;
state = state_scope0;
}
else if (!inClose && tag == "close")
{
handler.startClose();
state = state_html0;
inClose = true;
}
else if (tag == "i18n")
{
splitBar = true;
handler.startI18n();
state = state_html0;
}
else if (tag == "doc")
state = state_doc;
else
state = state_cpp;
}
else if (!inComp && tag == "def" && std::isspace(ch))
state = state_tagarg0;
else if (std::isspace(ch))
{
if (tag == "application")
{
scope_container = application_container;
state = state_scopearg0;
}
else if (tag == "thread")
{
scope_container = thread_container;
state = state_scopearg0;
}
else if (tag == "session")
{
scope_container = session_container;
state = state_scopearg0;
}
else if (tag == "securesession")
{
scope_container = secure_session_container;
state = state_scopearg0;
}
else if (tag == "request")
{
scope_container = request_container;
state = state_scopearg0;
}
else if (tag == "param")
{
scope_container = param_container;
state = state_scopearg0;
}
else
{
state_type s = state;
state = state_html0;
throw parse_error("unknown tag " + tag, s, curfile, curline);
}
}
else
tag += ch;
break;
case state_tagarg0:
if (ch == '>')
state = state_cpp;
else if (!std::isspace(ch))
{
tagarg = ch;
state = state_tagarg;
}
break;
case state_tagarg:
if (std::isspace(ch))
state = state_tagarge;
else if (tag == "def" && ch == '(')
state = state_defarg0;
else if (ch == '>')
{
if (tag == "args" || tag == "get" || tag == "post")
state = state_args0;
else if (tag == "attr")
state = state_attr0;
else if (tag == "def")
{
handler.startComp(tagarg, cppargs);
state = state_html0;
inComp = true;
}
else if (tag == "close")
{
handler.startClose();
state = state_html0;
inClose = true;
}
else if (tag == "i18n")
{
splitBar = true;
handler.startI18n();
state = state_html0;
}
else
state = state_cpp;
}
else
tagarg += ch;
break;
case state_tagarge:
if (ch == '>')
{
if (tag == "args" || tag == "get" || tag == "post")
state = state_args0;
else if (tag == "attr")
state = state_attr0;
else if (tag == "def")
{
handler.startComp(tagarg, cppargs);
state = state_html0;
inComp = true;
}
else if (tag == "close")
{
handler.startClose();
state = state_html0;
inClose = true;
}
else if (tag == "i18n")
{
splitBar = true;
handler.startI18n();
state = state_html0;
}
else
state = state_cpp;
}
else if (tag == "def" && ch == '(')
state = state_defarg0;
break;
case state_defarg0:
if (ch == ')')
state = state_defarg_end;
else if (!std::isspace(ch))
{
defarg += ch;
state = state_defarg;
}
break;
case state_defarg:
if (ch == '=')
state = state_defargdefval0;
else if (ch == ')')
{
cppargs.push_back(std::make_pair(defarg, std::string()));
defarg.clear();
state = state_defarg_end;
}
else if (ch == ',')
{
cppargs.push_back(std::make_pair(defarg, std::string()));
defarg.clear();
state = state_defarg0;
}
else
defarg += ch;
break;
case state_defargdefval0:
if (!std::isspace(ch))
{
defval = ch;
state = state_defargdefval;
}
break;
case state_defargdefval:
if (ch == ')')
{
cppargs.push_back(std::make_pair(defarg, defval));
defarg.clear();
defval.clear();
state = state_defarg_end;
}
else if (ch == ',')
{
cppargs.push_back(std::make_pair(defarg, defval));
defarg.clear();
defval.clear();
state = state_defarg;
}
else
defval += ch;
break;
case state_defarg_end:
if (ch == '>')
{
handler.startComp(tagarg, cppargs);
inComp = true;
cppargs.clear();
state = state_html0;
}
else if (!std::isspace(ch))
{
state_type s = state;
state = state_html0;
throw parse_error("def", s, curfile, curline);
}
break;
case state_cppcomment0:
if (ch == '/')
{
code += "//";
state = state_cppcomment;
break;
}
else if (state == '*')
{
code += "/*";
state = state_cppcommentc;
break;
}
code += '/';
state = state_cpp;
// no break
case state_cpp:
if (ch == '<')
state = state_cppe0;
else if (ch == '}')
state = state_cppse;
else if (ch == '/')
state = state_cppcomment0;
else
{
code += ch;
if (ch == '"')
state = state_cppstring;
else if (ch == '\'')
state = state_cppchar;
}
break;
case state_cppstring:
code += ch;
if (ch == '"')
state = state_cpp;
else if (ch == '\\')
state = state_cppstringesc;
break;
case state_cppstringesc:
code += ch;
state = state_cppstring;
break;
case state_cppchar:
code += ch;
if (ch == '\\')
state = state_cppcharesc;
else
state = state_cppchare;
break;
case state_cppcharesc:
code += ch;
state = state_cppchare;
break;
case state_cppchare:
code += ch;
if (ch == '\'')
state = state_cpp;
break;
case state_cppcomment:
code += ch;
if (ch == '\n')
state = state_cpp;
break;
case state_cppcommentc:
code += ch;
if (ch == '*')
state = state_cppcommentce;
break;
case state_cppcommentce:
code += ch;
if (ch == '/')
state = state_cpp;
break;
case state_cppse:
if (ch == '>')
{
log_debug("onCpp(\"" << code << "\")");
handler.onCpp(code);
code.clear();
state = state_html;
}
else
{
code += '}';
code += ch;
state = state_cpp;
}
break;
case state_cppe0:
if (ch == '/')
{
etag.clear();
state = state_cppe1;
}
else
{
code += '<';
code += ch;
state = state_cpp;
}
break;
case state_cppe1:
if (ch == '%')
state = state_cppetag;
else
{
code += "</";
code += ch;
state = state_cpp;
}
break;
case state_cppetag:
if (ch == '>')
{
if (tag != etag)
{
state_type s = state;
state = state_html0;
throw parse_error("invalid end-tag - "
+ tag + " expected, "
+ etag + " found", s, curfile, curline);
}
else if (tag == "pre")
{
log_debug("onPre(\"" << code << "\")");
handler.onPre(code);
}
else if (tag == "init")
{
log_debug("onInit(\"" << code << "\")");
handler.onInit(code);
}
else if (tag == "cleanup")
{
log_debug("onCleanup(\"" << code << "\")");
handler.onCleanup(code);
}
else if (tag == "shared")
{
log_debug("onShared(\"" << code << "\")");
handler.onShared(code);
}
else if (tag == "cpp")
{
log_debug("onCpp(\"" << code << "\")");
handler.onCpp(code);
}
else if (tag == "out")
{
handler.onHtmlExpression(code);
}
else if (tag == "sout")
{
handler.onExpression(code);
}
else if (tag == "args"
|| tag == "get"
|| tag == "post"
|| tag == "attr"
|| tag == "config"
|| tag == "include"
|| tag == "session"
|| tag == "securesession"
|| tag == "application"
|| tag == "thread"
|| tag == "request"
|| tag == "param"
|| tag == "doc")
;
else
{
state_type s = state;
state = state_html0;
throw parse_error("unknown tag " + tag, s, curfile, curline);
}
code.clear();
state = state_html0;
}
else
{
etag += ch;
}
break;
case state_nl:
if (ch == '<')
{
state = state_tagstart;
}
else if (ch == '%')
{
// start of oneline-cpp
handler.onLine(curline, curfile); //#
if (!html.empty())
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
html.clear();
}
state = state_cpp1;
}
else if (ch == '\\')
state = state_htmlesc;
else if (splitBar && (ch == split_start|| ch == split_end))
{
if (!html.empty())
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
html.clear();
}
handler.tokenSplit(ch == split_start);
state = state_html;
}
else
{
html += ch;
if (ch != '\n')
state = state_html;
}
break;
case state_cpp1:
if (ch == '\n')
{
code += '\n';
log_debug("onCpp(\"" << code << "\")");
handler.onCpp(code);
code.clear();
state = state_nl;
}
else
{
code += ch;
}
break;
case state_args0:
if (ch == '<')
state = state_cppe0;
else if (ch == '/')
state = state_args0comment;
else if (!std::isspace(ch))
{
arg = ch;
state = state_argsvar;
}
break;
case state_args0comment:
if (ch == '/')
state = state_argscomment;
else
throw parse_error("7", state, curfile, curline);
break;
case state_argsvar:
if (ch == '=')
{
value.clear();
state = state_argsval;
}
else if (ch == '/')
{
processNV(tag, arg, std::string());
arg.clear();
state = state_argscomment0;
}
else if (ch == ';')
{
processNV(tag, arg, std::string());
arg.clear();
state = state_args0;
}
else
arg += ch;
break;
case state_argsvare:
if (ch == '=')
{
value.clear();
state = state_argsval;
}
else if (ch == '\n' || ch == ';')
{
processNV(tag, arg, std::string());
arg.clear();
state = state_args0;
if (ch == '\n')
std::cerr << curfile << ':' << curline + 1 << ": warning: old syntax: ';' missing" << std::endl;
}
else if (!std::isspace(ch))
{
processNV(tag, arg, std::string());
arg.clear();
if (ch == '<')
state = state_cppe0;
else if (ch == '/')
state = state_argscomment0;
else
{
arg = ch;
state = state_argsvar;
}
}
break;
case state_argsval:
if (ch == '\n' || ch == ';')
{
processNV(tag, arg, value);
arg.clear();
value.clear();
state = state_args0;
if (ch == '\n')
std::cerr << curfile << ':' << curline << ": warning: old syntax: ';' missing" << std::endl;
}
else if (ch == '"')
{
value += ch;
state = state_argsvalstring;
}
else if (ch == '/')
state = state_argsvalcomment0;
else
value += ch;
break;
case state_argsvalstring:
if (ch == '"')
state = state_argsval;
value += ch;
break;
case state_argscomment0:
if (ch == '/')
state = state_argscomment;
else
throw parse_error("6", state, curfile, curline);
break;
case state_argscomment:
if (ch == '\n')
state = state_args0;
break;
case state_argsvalcomment0:
if (ch == '/')
{
processNV(tag, arg, value);
arg.clear();
value.clear();
state = state_argscomment;
if (ch == '\n')
std::cerr << curfile << ':' << curline << ": warning: old syntax: ';' missing" << std::endl;
}
else
{
value += '/';
value += ch;
state = state_argsval;
}
break;
case state_attr0:
if (ch == '<')
state = state_cppe0;
else if (ch == '/')
state = state_attr0comment;
else if (!std::isspace(ch))
{
arg = ch;
state = state_attrvar;
}
break;
case state_attr0comment:
if (ch == '/')
state = state_attrcomment;
else
throw parse_error("7", state, curfile, curline);
break;
case state_attrvar:
if (ch == '=')
{
value.clear();
state = state_attrval;
}
else if (std::isspace(ch))
state = state_attrvare;
else
arg += ch;
break;
case state_attrvare:
if (ch == '=')
{
if (arg.empty())
throw parse_error("name expected", state, curfile, curline);
value.clear();
state = state_attrval;
}
else if (!std::isspace(ch))
throw parse_error("'=' expected", state, curfile, curline);
break;
case state_attrval:
if (ch == '\n' || ch == ';')
{
if (value.empty())
throw parse_error("value expected", state, curfile, curline);
log_debug("onAttr(\"" << arg << "\", \"" << value << "\")");
handler.onAttr(arg, value);
arg.clear();
value.clear();
state = state_attr0;
if (ch == '\n')
std::cerr << curfile << ':' << curline << ": warning: old syntax: ';' missing" << std::endl;
}
else if (ch == '"')
{
value += ch;
state = state_attrvalstring;
}
else if (ch == '/')
state = state_attrvalcomment0;
else
value += ch;
break;
case state_attrvalstring:
if (ch == '"')
state = state_attrval;
value += ch;
break;
case state_attrcomment0:
if (ch == '/')
state = state_attrcomment;
else
throw parse_error("6", state, curfile, curline);
break;
case state_attrcomment:
if (ch == '\n')
state = state_attr0;
break;
case state_attrvalcomment0:
if (ch == '/')
{
if (value.empty())
throw parse_error("value expected", state, curfile, curline);
log_debug("onAttr(\"" << arg << "\", \"" << value << "\")");
handler.onAttr(arg, value);
arg.clear();
value.clear();
state = state_attrcomment;
}
else
{
value += '/';
value += ch;
state = state_attrval;
}
break;
case state_call0:
if (ch == '(')
{
comp = ch;
bracket_count = 1;
state = state_callname_expr;
}
else if (ch == '"')
{
comp = ch;
state = state_callname_string;
}
else if (!std::isspace(ch))
{
comp = ch;
state = state_callname;
}
break;
case state_callname_expr:
comp += ch;
if (ch == '(')
++bracket_count;
else if (ch == ')' && --bracket_count == 0)
state = state_callarg0;
break;
case state_callname_string:
comp += ch;
if (ch == '"')
state = state_callarg0;
else if (std::isspace(ch))
throw parse_error("invalid componentname", state, curfile, curline);
break;
case state_callname:
if (ch == '&' || ch == '>')
{
log_debug("onCall(\"" << comp << "comp_args (" << comp_args.size() << "), \"" << pass_cgi << "\", paramargs (" << paramargs.size() << "), defarg (" << defarg.size() << "))");
handler.onCall(comp, comp_args, pass_cgi, paramargs, defarg);
comp.clear();
comp_args.clear();
pass_cgi.clear();
paramargs.clear();
defarg.clear();
state = ch == '>' ? state_html : state_callend;
}
else if (std::isspace(ch))
state = state_callarg0;
else if (ch == '(')
{
state = state_call_cpparg0;
expr.clear();
paramargs.clear();
}
else
comp += ch;
break;
case state_call_cpparg0:
if (ch == ')')
state = state_callarg;
else if (std::isalpha(ch) || ch == '_')
{
expr = ch;
state = state_call_cpparg_pe;
}
else if (!std::isspace(ch))
{
expr = ch;
if (ch == '(')
bracket_count = 1;
state = state_call_cpparg_e;
}
break;
case state_call_cpparg1:
if (ch == ')')
throw parse_error("')' unexpected", state, curfile, curline);
else if (std::isalpha(ch) || ch == '_')
{
expr = ch;
state = state_call_cpparg_pe;
}
else if (!std::isspace(ch))
{
expr = ch;
if (ch == '(')
bracket_count = 1;
state = state_call_cpparg_e;
}
break;
case state_call_cpparg_pe:
if (isVariableNameChar(ch))
expr += ch;
else if (std::isspace(ch))
{
paramname = expr;
state = state_call_cpparg_sp;
}
else if (ch == '=')
{
paramname = expr;
expr.clear();
bracket_count = 0;
state = state_call_cpparg_e;
}
else if (ch == ')')
{
if (!defarg.empty())
defarg += ',';
defarg += expr;
expr.clear();
state = state_callarg0;
}
else
{
expr += ch;
if (ch == '(')
bracket_count = 1;
state = state_call_cpparg_e;
}
break;
case state_call_cpparg_sp:
if (std::isspace(ch))
expr += ch;
else if (ch == '=')
{
expr.clear();
bracket_count = 0;
state = state_call_cpparg_e;
}
else
{
expr += ch;
paramname.clear();
if (ch == '(')
bracket_count = 1;
state = state_call_cpparg_e;
}
break;
case state_call_cpparg_e:
if (ch == ')' && bracket_count > 0)
{
--bracket_count;
expr += ch;
}
else if (ch == ',' || ch == ')')
{
if (paramname.empty())
{
if (!defarg.empty())
defarg += ',';
defarg += expr;
expr.clear();
state = ch == ',' ? state_call_cpparg1 : state_callarg0;
}
else
{
if (paramargs.find(paramname) != paramargs.end())
throw parse_error("duplicate parameter " + paramname, state, curfile, curline);
paramargs[paramname] = expr;
paramname.clear();
expr.clear();
state = ch == ',' ? state_call_cpparg1 : state_callarg0;
}
}
else
{
if (ch == '(')
++bracket_count;
expr += ch;
}
break;
case state_callend:
if (ch == '>')
state = state_html;
else
throw parse_error("3", state, curfile, curline);
break;
case state_callarg0:
if (std::isalpha(ch) || ch == '_')
{
arg = ch;
state = state_callarg;
}
else if (ch == '&' || ch == '/' || ch == '>')
{
log_debug("onCall(\"" << comp << "comp_args (" << comp_args.size() << "), \"" << pass_cgi << "\", paramargs (" << paramargs.size() << "), defarg (" << defarg.size() << "))");
handler.onCall(comp, comp_args, pass_cgi, paramargs, defarg);
arg.clear();
comp.clear();
comp_args.clear();
pass_cgi.clear();
paramargs.clear();
defarg.clear();
state = ch == '>' ? state_html : state_callend;
}
else if (ch == '(' && arg.empty() && pass_cgi.empty())
state = state_call_cpparg0;
else if (!std::isspace(ch))
throw parse_error(std::string("invalid argumentname (") + ch + ')', state, curfile, curline);
break;
case state_callarg:
if (isVariableNameChar(ch))
arg += ch;
else if (std::isspace(ch))
state = state_callarge;
else if (ch == '=')
state = state_callval0;
else if ((pass_cgi.empty() && ch == '&') || ch == '/' || ch == '>')
{
log_debug("onCall(\"" << comp << "comp_args (" << comp_args.size() << "), \"" << pass_cgi << "\", paramargs (" << paramargs.size() << "), defarg (" << defarg.size() << "))");
handler.onCall(comp, comp_args, arg, paramargs, defarg);
arg.clear();
comp.clear();
comp_args.clear();
paramargs.clear();
defarg.clear();
state = ch == '>' ? state_html : state_callend;
}
else
throw parse_error(std::string("invalid argumentname (") + ch + ')', state, curfile, curline);
break;
case state_callarge:
if (ch == '=')
state = state_callval0;
else if (pass_cgi.empty() && (isVariableNameChar(ch)))
{
pass_cgi = arg;
arg = ch;
state = state_callarg;
}
else if ((pass_cgi.empty() && ch == '&') || ch == '/' || ch == '>')
{
log_debug("onCall(\"" << comp << "comp_args (" << comp_args.size() << "), \"" << pass_cgi << "\", paramargs (" << paramargs.size() << "), defarg (" << defarg.size() << "))");
handler.onCall(comp, comp_args, arg, paramargs, defarg);
arg.clear();
comp.clear();
comp_args.clear();
paramargs.clear();
defarg.clear();
state = ch == '>' ? state_html : state_callend;
}
else if (!std::isspace(ch))
throw parse_error("5", state, curfile, curline);
break;
case state_callval0:
if (ch == '(')
{
value = ch;
state = state_callval_expr;
bracket_count = 1;
}
else if (ch == '"')
{
value = ch;
state = state_callval_string;
}
else if (!std::isspace(ch))
{
value = ch;
state = state_callval_word;
}
break;
case state_callval_expr:
value += ch;
if (ch == '(')
++bracket_count;
else if (ch == ')' && --bracket_count == 0)
{
comp_args.insert(comp_args_type::value_type(arg, value));
arg.clear();
value.clear();
state = state_callarg0;
}
break;
case state_callval_string:
value += ch;
if (ch == '"')
{
comp_args.insert(comp_args_type::value_type(arg, value));
arg.clear();
value.clear();
state = state_callarg0;
}
break;
case state_callval_word:
if (std::isspace(ch))
{
comp_args.insert(comp_args_type::value_type(arg, value));
arg.clear();
value.clear();
state = state_callarg0;
}
else
value += ch;
break;
case state_callvale:
if (ch == '>')
{
comp_args.insert(comp_args_type::value_type(arg, value));
arg.clear();
value.clear();
log_debug("onCall(\"" << comp << "comp_args (" << comp_args.size() << "), \"" << pass_cgi << "\", paramargs (" << paramargs.size() << "), defarg (" << defarg.size() << "))");
handler.onCall(comp, comp_args, pass_cgi, paramargs, defarg);
comp.clear();
comp_args.clear();
pass_cgi.clear();
paramargs.clear();
defarg.clear();
state = state_html;
}
else
throw parse_error("ivalid value", state, curfile, curline);
break;
case state_comment:
if (ch == '#')
state = state_commente;
break;
case state_commente:
if (ch == '>')
state = state_html;
else if (ch != '#')
state = state_comment;
break;
case state_compe0:
if (ch == '%')
{
if (!html.empty())
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
html.clear();
}
state = state_compe;
tag.clear();
}
else if (ch == '&')
{
state = state_endcall0;
}
else
{
html += "</";
html += ch;
state = state_html;
}
break;
case state_compe:
if (ch == '>')
{
if (inComp && tag == "def")
{
log_debug("onComp(\"" << code << "\")");
handler.onComp(code);
inComp = false;
state = state_html0;
}
else if (inClose && tag == "close")
{
handler.endClose();
inClose = false;
state = state_html0;
}
else if (splitBar && tag == "i18n")
{
splitBar = false;
handler.endI18n();
state = state_html0;
}
else
{
html += "</%";
html += tag;
state = state_html;
}
}
else
{
tag += ch;
if (tag.size() > 5)
{
html += "</%";
html += tag;
state = state_html;
}
}
break;
case state_cond0:
if (ch == '?')
htmlExpr = true;
else
cond += ch;
state = state_cond;
break;
case state_cond:
if (ch == '?')
state = state_condexpr;
else
cond += ch;
break;
case state_condexpr:
if (ch == '?')
state = state_condexpre;
else if (expr.empty() && ch == '>')
{
// special case for xml-header (<?xml ... ?>)
handler.onHtml("<?" + cond + "?>");
cond.clear();
state = state_html;
}
else
expr += ch;
break;
case state_condexpre:
if (ch == '>')
{
log_debug("onCondExpression(\"" << cond << ", " << code << "\")");
handler.onCondExpr(cond, expr, htmlExpr);
htmlExpr = false;
cond.clear();
expr.clear();
state = state_html;
}
else
{
expr += '?';
expr += ch;
state = state_condexpr;
}
break;
case state_include0:
if (ch == '<')
state = state_cppe0;
else if (!std::isspace(ch))
{
expr = ch;
state = state_include1;
}
break;
case state_include1:
if (std::isspace(ch) || ch == '<')
{
doInclude(expr);
expr.clear(),
state = (ch == '<' ? state_cppe0 : state_include0);
}
else
expr += ch;
break;
case state_scopearg0:
if (ch == '>')
{
state = state_scope0;
scope = component_scope;
}
else if (!std::isspace(ch))
{
tagarg = ch;
state = state_scopearg;
}
break;
case state_scopearg:
if (ch == '=')
{
state = state_scopeargval0;
if (tagarg != "scope")
throw parse_error("argument \"scope\" expected", state, curfile, curline);
tagarg.clear();
}
else if (std::isspace(ch))
{
state = state_scopeargeq;
if (tagarg != "scope")
throw parse_error("argument \"scope\" expected", state, curfile, curline);
tagarg.clear();
}
else
tagarg += ch;
break;
case state_scopeargeq:
if (ch == '=')
state = state_scopeargval0;
else if (!std::isspace(ch))
throw parse_error("\"=\" expected", state, curfile, curline);
break;
case state_scopeargval0:
if (ch == '"')
state = state_scopeargval;
else if (!std::isspace(ch))
throw parse_error("argument expected", state, curfile, curline);
break;
case state_scopeargval:
if (ch == '"')
{
if (value == "global")
scope = global_scope;
else if (value == "page")
scope = page_scope;
else if (value == "component")
scope = component_scope;
else
throw parse_error("global|page|component expected", state, curfile, curline);
value.clear();
state = state_scopevale;
}
else if (ch == '\n')
throw parse_error("'\"' expected", state, curfile, curline);
else
value += ch;
break;
case state_scopevale:
if (ch == '>')
state = state_scope0;
else if (!std::isspace(ch))
throw parse_error("'>' expected", state, curfile, curline);
break;
case state_scope0:
if (ch == '<')
state = state_scopee;
else if (ch == '/')
state = state_scopecomment0;
else if (!std::isspace(ch))
{
handler.onLine(curline, curfile); //#
scopevar = ch;
state = state_scope;
}
break;
case state_scope:
if (ch == ';')
{
// scopetype contains type-definition
// scopevar contains variable-definition
// scopeinit is empty
if (scopetype.size() > 0
&& std::isspace(scopetype.at(scopetype.size() - 1)))
scopetype.erase(scopetype.size() - 1);
log_debug("onScope(" << scope_container << ", " << scope << ", "
<< scopetype << ", " << scopevar << ", " << scopeinit << ')');
handler.onScope(scope_container, scope, scopetype, scopevar, scopeinit);
scopetype.clear();
scopevar.clear();
state = state_scope0;
}
else if (ch == '(')
{
state = state_scopeinit;
bracket_count = 0;
}
else if (ch == '=')
{
state = state_scopeiniteq;
bracket_count = 0;
}
else if (std::isspace(ch))
scopevar += ch;
else if (!isVariableNameChar(scopevar.at(scopevar.size() - 1)))
{
scopetype += scopevar;
scopevar = ch;
}
else
scopevar += ch;
break;
case state_scopee:
if (ch == '/')
{
etag.clear();
state = state_cppe1;
}
else
{
scopevar += '<';
scopevar += ch;
state = state_scope;
}
break;
case state_scopeinit:
if (bracket_count == 0 && ch == ')')
{
// scopevar contains variable-definition
// scopeinit contains constructorparameter
while (scopetype.size() > 0
&& std::isspace(scopetype.at(scopetype.size() - 1)))
scopetype.erase(scopetype.size() - 1);
while (scopevar.size() > 0
&& std::isspace(scopevar.at(scopevar.size() - 1)))
scopevar.erase(scopevar.size() - 1);
log_debug("onScope(" << scope_container << ", " << scope << ", "
<< scopetype << ", " << scopevar << ", " << scopeinit << ')');
handler.onScope(scope_container, scope, scopetype, scopevar, scopeinit);
scopetype.clear();
scopevar.clear();
scopeinit.clear();
state = state_scopee0;
}
else
{
scopeinit += ch;
if (ch == '(')
++bracket_count;
else if (ch == ')')
{
if (bracket_count == 0)
throw parse_error("unexpected ')'", state, curfile, curline);
--bracket_count;
}
}
break;
case state_scopeiniteq:
if (bracket_count == 0 && ch == ';')
{
// scopevar contains variable-definition
// scopeinit contains constructorparameter
while (scopetype.size() > 0
&& std::isspace(scopetype.at(scopetype.size() - 1)))
scopetype.erase(scopetype.size() - 1);
while (scopevar.size() > 0
&& std::isspace(scopevar.at(scopevar.size() - 1)))
scopevar.erase(scopevar.size() - 1);
log_debug("onScope(" << scope_container << ", " << scope << ", "
<< scopetype << ", " << scopevar << ", " << scopeinit << ')');
handler.onScope(scope_container, scope, scopetype, scopevar, scopeinit);
scopetype.clear();
scopevar.clear();
scopeinit.clear();
state = state_scope0;
}
else
{
scopeinit += ch;
if (ch == '(')
++bracket_count;
else if (ch == ')')
{
if (bracket_count == 0)
throw parse_error("unexpected ')'", state, curfile, curline);
--bracket_count;
}
}
break;
case state_scopee0:
if (ch == ';')
state = state_scope0;
else if (!std::isspace(ch))
throw parse_error("invalid scopedefinition", state, curfile, curline);
break;
case state_scopecomment0:
if (ch == '/')
state = state_scopecomment;
else
throw parse_error("invalid scopedefinition - '/' expexted", state, curfile, curline);
break;
case state_scopecomment:
if (ch == '\n')
state = state_scope0;
break;
case state_endcall0:
if (isVariableNameChar(ch))
{
comp = ch;
state = state_endcall;
}
else if ('>')
{
if (!html.empty())
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
html.clear();
}
log_debug("onEndCall(\"" << comp << "\")");
handler.onEndCall(comp);
comp.clear();
state = state_html;
}
else if (!std::isspace(ch))
throw parse_error(std::string("character expected, \'") + ch
+ "\' found", state, curfile, curline);
break;
case state_endcall:
if (ch == '>')
{
if (!html.empty())
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
html.clear();
}
log_debug("onEndCall(\"" << comp << "\")");
handler.onEndCall(comp);
comp.clear();
state = state_html;
}
else if (std::isspace(ch))
{
log_debug("onEndCall(\"" << comp << "\")");
handler.onEndCall(comp);
comp.clear();
state = state_endcalle;
}
else if (isVariableNameChar(ch) || ch == '@')
comp += ch;
else
throw parse_error("character expected", state, curfile, curline);
break;
case state_endcalle:
if (ch == '>')
state = state_html;
else if (!std::isspace(ch))
throw parse_error("'>' expected", state, curfile, curline);
break;
case state_doc:
if (ch == '<')
{
etag.clear();
state = state_doce;
}
break;
case state_doce:
if (ch == '>')
{
if (etag == "/%doc")
state = state_html0;
else
state = state_doc;
}
else if (ch == '<')
etag.clear();
else
etag += ch;
break;
} // switch(state)
log_debug("line " << curline << " char " << ch << " state " << state << " bc " << bracket_count);
} // while(in.get(ch))
if (state != state_html && state != state_html0 && state != state_nl)
throw parse_error("parse error", state, curfile, curline);
if (inComp)
throw parse_error("</%def> missing", state, curfile, curline);
if (inClose)
throw parse_error("</%close> missing", state, curfile, curline);
if (!html.empty())
{
log_debug("onHtml(\"" << html << "\")");
handler.onHtml(html);
}
}
void Parser::parse(std::istream& in)
{
parsePriv(in);
handler.end();
}
void Parser::processNV(const std::string& tag, const std::string& name,
const std::string& value)
{
if (tag == "args")
handler.onArg(name, value);
if (tag == "get")
handler.onGet(name, value);
if (tag == "post")
handler.onPost(name, value);
else if (tag == "config")
handler.onConfig(name, value);
}
parse_error::parse_error(const std::string& txt, int state, const std::string& file, unsigned curline)
: runtime_error(std::string())
{
std::ostringstream m;
m << file << ':' << (curline + 1) << ": error: " << txt << " (state " << state << ')';
msg = m.str();
}
const char* parse_error::what() const throw()
{
return msg.c_str();
}
}
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkQtStringToImage.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkQtStringToImage.h"
#include "vtkQImageToImageSource.h"
#include "vtkStdString.h"
#include "vtkUnicodeString.h"
#include "vtkTextProperty.h"
#include "vtkVector.h"
#include "vtkImageData.h"
#include "vtkObjectFactory.h"
// Qt classes
#include <QApplication>
#include <QString>
#include <QFont>
#include <QFontMetrics>
#include <QImage>
#include <QPainter>
#include <QPixmap>
#include <QTextDocument>
#include <QTextStream>
namespace
{
struct vtkQtLabelMapEntry
{
QString Text;
QColor Color;
QFont Font;
};
} // End of anonymous namespace
class vtkQtStringToImage::Internals
{
public:
QFont TextPropertyToFont(vtkTextProperty* tprop)
{
QFont fontSpec(tprop->GetFontFamilyAsString());
fontSpec.setBold(tprop->GetBold());
fontSpec.setItalic(tprop->GetItalic());
fontSpec.setPixelSize(tprop->GetFontSize());
return fontSpec;
}
QColor TextPropertyToColor(double* fc, double opacity)
{
QColor textColor(
static_cast<int>(fc[0]*255),
static_cast<int>(fc[1]*255),
static_cast<int>(fc[2]*255),
static_cast<int>(opacity*255));
return textColor;
}
};
//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkQtStringToImage);
//-----------------------------------------------------------------------------
vtkQtStringToImage::vtkQtStringToImage()
{
this->Implementation = new Internals;
this->QImageToImage = vtkSmartPointer<vtkQImageToImageSource>::New();
}
//-----------------------------------------------------------------------------
vtkQtStringToImage::~vtkQtStringToImage()
{
delete this->Implementation;
}
//-----------------------------------------------------------------------------
vtkVector2i vtkQtStringToImage::GetBounds(vtkTextProperty *property,
const vtkUnicodeString& string)
{
vtkVector2i recti;
if (!QApplication::instance())
{
vtkErrorMacro("You must initialize a QApplication before using this class.");
return recti;
}
if (!property)
{
return recti;
}
QFont fontSpec = this->Implementation->TextPropertyToFont(property);
QString text = QString::fromUtf8(string.utf8_str());
QRectF rect;
QPainterPath path;
path.addText(0, 0, fontSpec, text);
rect = path.boundingRect();
recti.SetX(static_cast<int>(rect.width()));
recti.SetY(static_cast<int>(rect.height()));
return recti;
}
//-----------------------------------------------------------------------------
vtkVector2i vtkQtStringToImage::GetBounds(vtkTextProperty *property,
const vtkStdString& string)
{
vtkVector2i recti;
if (!QApplication::instance())
{
vtkErrorMacro("You must initialize a QApplication before using this class.");
return recti;
}
if (!property)
{
return recti;
}
QFont fontSpec = this->Implementation->TextPropertyToFont(property);
QString text(string.c_str());
QRectF rect;
QPainterPath path;
path.addText(0, 0, fontSpec, text);
rect = path.boundingRect();
recti.SetX(static_cast<int>(rect.width()));
recti.SetY(static_cast<int>(rect.height()));
return recti;
}
int vtkQtStringToImage::RenderString(vtkTextProperty *property,
const vtkUnicodeString& string,
vtkImageData *data)
{
if (!QApplication::instance())
{
vtkErrorMacro("You must initialize a QApplication before using this class.");
return 0;
}
// Get the required size, and initialize a new QImage to draw on.
vtkVector2i box = this->GetBounds(property, string);
if (box.GetX() == 0 || box.GetY() == 0)
{
return 0;
}
QString text = QString::fromUtf8(string.utf8_str());
QFont fontSpec = this->Implementation->TextPropertyToFont(property);
QFontMetrics fontMetric(fontSpec);
// Get properties from text property
double rotation = -property->GetOrientation();
QColor textColor =
this->Implementation->TextPropertyToColor(property->GetColor(),
property->GetOpacity());
int shOff[2];
property->GetShadowOffset(shOff);
double pixelPadding = 2;
double pixelPaddingX = pixelPadding + shOff[0];
double pixelPaddingY = pixelPadding - shOff[1];
QPainterPath path;
path.addText(0, 0, fontSpec, text);
QRectF bounds = path.boundingRect();
bounds.setWidth(bounds.width() + pixelPaddingX);
bounds.setHeight(bounds.height() + pixelPaddingY);
QTransform trans;
trans.rotate(rotation);
QRectF rotBounds = trans.mapRect(bounds);
QImage image(static_cast<int>(ceil(rotBounds.width() + pixelPaddingX)),
static_cast<int>(ceil(rotBounds.height() + pixelPaddingY)),
QImage::Format_ARGB32_Premultiplied);
image.fill(qRgba(0,0,0,0));
QPainter p(&image);
p.setRenderHint(QPainter::TextAntialiasing, this->Antialias);
p.setRenderHint(QPainter::Antialiasing, this->Antialias);
p.translate(-rotBounds.left(), -rotBounds.top());
p.rotate(rotation);
if (property->GetShadow())
{
p.save();
p.translate(shOff[0], -shOff[1]);
double sc[3];
property->GetShadowColor(sc);
QColor shadowColor =
this->Implementation->TextPropertyToColor(sc, property->GetOpacity());
p.fillPath(path, shadowColor);
p.restore();
}
p.fillPath(path, textColor);
this->QImageToImage->SetQImage(&image);
this->QImageToImage->Modified();
this->QImageToImage->Update();
data->DeepCopy(
vtkImageData::SafeDownCast(this->QImageToImage->GetOutputDataObject(0)));
this->QImageToImage->SetQImage(NULL);
return 1;
}
int vtkQtStringToImage::RenderString(vtkTextProperty *property,
const vtkStdString& string,
vtkImageData *data)
{
return this->RenderString(property, vtkUnicodeString::from_utf8(string), data);
}
//-----------------------------------------------------------------------------
void vtkQtStringToImage::DeepCopy(vtkQtStringToImage *)
{
}
//-----------------------------------------------------------------------------
void vtkQtStringToImage::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
|
#include "mainwindow.h"
#include "QStringUtils.h"
#include "settingsdialog.h"
#include "memorycardmanagerdialog.h"
#include "S3FileBrowser.h"
#include "ui_shared/BootablesProcesses.h"
#include "ui_shared/StatsManager.h"
#include "openglwindow.h"
#include "GSH_OpenGLQt.h"
#ifdef HAS_GSH_VULKAN
#include "vulkanwindow.h"
#include "GSH_VulkanQt.h"
#endif
#include <QDateTime>
#include <QFileDialog>
#include <QTimer>
#include <QWindow>
#include <QMessageBox>
#include <QStorageInfo>
#include <ctime>
#include <QtGlobal>
#include "StdStreamUtils.h"
#include "string_format.h"
#ifdef _WIN32
#include "../../tools/PsfPlayer/Source/win32_ui/SH_WaveOut.h"
#ifdef DEBUGGER_INCLUDED
#include "win32/DebugSupport/Debugger.h"
#include "win32/DebugSupport/FrameDebugger/FrameDebugger.h"
#include "ui_debugmenu.h"
#endif
#else
#include "tools/PsfPlayer/Source/SH_OpenAL.h"
#endif
#include "input/PH_GenericInput.h"
#include "DiskUtils.h"
#include "PathUtils.h"
#include <zlib.h>
#include "CoverUtils.h"
#include "PreferenceDefs.h"
#include "PS2VM_Preferences.h"
#include "ScreenShotUtils.h"
#include "ui_mainwindow.h"
#include "vfsmanagerdialog.h"
#include "bootablelistdialog.h"
#include "ControllerConfig/controllerconfigdialog.h"
#ifdef __APPLE__
#include "macos/InputProviderMacOsHid.h"
#endif
#ifdef HAS_LIBEVDEV
#include "unix/InputProviderEvDev.h"
#endif
#ifdef WIN32
#include "win32/InputProviderDirectInput.h"
#include "win32/InputProviderXInput.h"
#endif
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
RegisterPreferences();
m_continuationChecker = new CContinuationChecker(this);
#ifdef PROFILE
{
m_profileStatsLabel = new QLabel(this);
QFont courierFont("Courier");
m_profileStatsLabel->setFont(courierFont);
m_profileStatsLabel->setAlignment(Qt::AlignTop);
ui->gridLayout->addWidget(m_profileStatsLabel, 0, 1);
}
#endif
m_pauseFocusLost = CAppConfig::GetInstance().GetPreferenceBoolean(PREF_UI_PAUSEWHENFOCUSLOST);
auto lastPath = CAppConfig::GetInstance().GetPreferencePath(PREF_PS2_CDROM0_PATH);
std::error_code lastPathExistsErrorCode;
if(fs::exists(lastPath, lastPathExistsErrorCode))
{
m_lastPath = lastPath.parent_path();
}
else
{
m_lastPath = QStringToPath(QDir::homePath());
}
CreateStatusBar();
UpdateUI();
ui->actionBoot_DiscImage_S3->setVisible(S3FileBrowser::IsAvailable());
InitVirtualMachine();
SetupGsHandler();
#ifdef DEBUGGER_INCLUDED
m_debugger = std::make_unique<CDebugger>(*m_virtualMachine);
m_frameDebugger = std::make_unique<CFrameDebugger>();
auto debugMenu = new QMenu(this);
debugMenuUi = new Ui::DebugMenu();
debugMenuUi->setupUi(debugMenu);
ui->menuBar->insertMenu(ui->menuHelp->menuAction(), debugMenu);
connect(debugMenuUi->actionShowDebugger, &QAction::triggered, this, std::bind(&MainWindow::ShowDebugger, this));
connect(debugMenuUi->actionShowFrameDebugger, &QAction::triggered, this, std::bind(&MainWindow::ShowFrameDebugger, this));
connect(debugMenuUi->actionDumpNextFrame, &QAction::triggered, this, std::bind(&MainWindow::DumpNextFrame, this));
connect(debugMenuUi->actionGsDrawEnabled, &QAction::triggered, this, std::bind(&MainWindow::ToggleGsDraw, this));
#endif
}
MainWindow::~MainWindow()
{
#ifdef DEBUGGER_INCLUDED
m_debugger.reset();
m_frameDebugger.reset();
delete debugMenuUi;
#endif
CAppConfig::GetInstance().Save();
if(m_virtualMachine != nullptr)
{
m_virtualMachine->Pause();
m_qtKeyInputProvider.reset();
m_virtualMachine->DestroyPadHandler();
m_virtualMachine->DestroyGSHandler();
m_virtualMachine->DestroySoundHandler();
m_virtualMachine->Destroy();
delete m_virtualMachine;
m_virtualMachine = nullptr;
}
delete ui;
}
void MainWindow::InitVirtualMachine()
{
assert(!m_virtualMachine);
m_virtualMachine = new CPS2VM();
m_virtualMachine->Initialize();
SetupSoundHandler();
{
m_virtualMachine->CreatePadHandler(CPH_GenericInput::GetFactoryFunction());
auto padHandler = static_cast<CPH_GenericInput*>(m_virtualMachine->GetPadHandler());
auto profile = CAppConfig::GetInstance().GetPreferenceString(PREF_INPUT_PAD1_PROFILE);
auto& bindingManager = padHandler->GetBindingManager();
bindingManager.Load(profile);
//Create QtKeyInputProvider
m_qtKeyInputProvider = std::make_shared<CInputProviderQtKey>();
bindingManager.RegisterInputProvider(m_qtKeyInputProvider);
#ifdef __APPLE__
bindingManager.RegisterInputProvider(std::make_shared<CInputProviderMacOsHid>());
#endif
#ifdef HAS_LIBEVDEV
bindingManager.RegisterInputProvider(std::make_shared<CInputProviderEvDev>());
#endif
#ifdef WIN32
bindingManager.RegisterInputProvider(std::make_shared<CInputProviderDirectInput>());
bindingManager.RegisterInputProvider(std::make_shared<CInputProviderXInput>());
#endif
if(!bindingManager.HasBindings())
{
ControllerConfigDialog::AutoConfigureKeyboard(&bindingManager);
}
}
#ifdef PROFILE
m_profileFrameDoneConnection = m_virtualMachine->ProfileFrameDone.Connect(std::bind(&CStatsManager::OnProfileFrameDone, &CStatsManager::GetInstance(), m_virtualMachine, std::placeholders::_1));
#endif
//OnExecutableChange might be called from another thread, we need to wrap it around a Qt signal
m_OnExecutableChangeConnection = m_virtualMachine->m_ee->m_os->OnExecutableChange.Connect(std::bind(&MainWindow::EmitOnExecutableChange, this));
connect(this, SIGNAL(onExecutableChange()), this, SLOT(HandleOnExecutableChange()));
}
void MainWindow::SetOutputWindowSize()
{
outputWindow_resized();
}
void MainWindow::SetupGsHandler()
{
assert(m_virtualMachine);
switch(CAppConfig::GetInstance().GetPreferenceInteger(PREF_VIDEO_GS_HANDLER))
{
#ifdef HAS_GSH_VULKAN
case SettingsDialog::GS_HANDLERS::VULKAN:
{
m_outputwindow = new VulkanWindow;
QWidget* container = QWidget::createWindowContainer(m_outputwindow);
m_outputwindow->create();
ui->gridLayout->addWidget(container, 0, 0);
m_virtualMachine->CreateGSHandler(CGSH_VulkanQt::GetFactoryFunction(m_outputwindow));
}
break;
case SettingsDialog::GS_HANDLERS::OPENGL:
#endif
default:
{
m_outputwindow = new OpenGLWindow;
QWidget* container = QWidget::createWindowContainer(m_outputwindow);
m_outputwindow->create();
ui->gridLayout->addWidget(container, 0, 0);
m_virtualMachine->CreateGSHandler(CGSH_OpenGLQt::GetFactoryFunction(m_outputwindow));
}
}
connect(m_outputwindow, SIGNAL(heightChanged(int)), this, SLOT(outputWindow_resized()));
connect(m_outputwindow, SIGNAL(widthChanged(int)), this, SLOT(outputWindow_resized()));
connect(m_outputwindow, SIGNAL(keyUp(QKeyEvent*)), this, SLOT(keyReleaseEvent(QKeyEvent*)));
connect(m_outputwindow, SIGNAL(keyDown(QKeyEvent*)), this, SLOT(keyPressEvent(QKeyEvent*)));
connect(m_outputwindow, SIGNAL(focusOut(QFocusEvent*)), this, SLOT(focusOutEvent(QFocusEvent*)));
connect(m_outputwindow, SIGNAL(focusIn(QFocusEvent*)), this, SLOT(focusInEvent(QFocusEvent*)));
connect(m_outputwindow, SIGNAL(doubleClick(QMouseEvent*)), this, SLOT(doubleClickEvent(QMouseEvent*)));
m_OnNewFrameConnection = m_virtualMachine->m_ee->m_gs->OnNewFrame.Connect(std::bind(&CStatsManager::OnNewFrame, &CStatsManager::GetInstance(), std::placeholders::_1));
}
void MainWindow::SetupSoundHandler()
{
assert(m_virtualMachine);
bool audioEnabled = CAppConfig::GetInstance().GetPreferenceBoolean(PREFERENCE_AUDIO_ENABLEOUTPUT);
if(audioEnabled)
{
#ifdef _WIN32
m_virtualMachine->CreateSoundHandler(&CSH_WaveOut::HandlerFactory);
#else
m_virtualMachine->CreateSoundHandler(&CSH_OpenAL::HandlerFactory);
#endif
}
else
{
m_virtualMachine->DestroySoundHandler();
}
}
void MainWindow::outputWindow_resized()
{
if(m_virtualMachine != nullptr && m_virtualMachine->m_ee != nullptr && m_virtualMachine->m_ee->m_gs != nullptr)
{
uint32 w = m_outputwindow->size().width(), h = m_outputwindow->size().height();
qreal scale = 1.0;
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
scale = devicePixelRatioF();
#endif
CGSHandler::PRESENTATION_PARAMS presentationParams;
presentationParams.mode = static_cast<CGSHandler::PRESENTATION_MODE>(CAppConfig::GetInstance().GetPreferenceInteger(PREF_CGSHANDLER_PRESENTATION_MODE));
presentationParams.windowWidth = w * scale;
presentationParams.windowHeight = h * scale;
m_virtualMachine->m_ee->m_gs->SetPresentationParams(presentationParams);
m_virtualMachine->m_ee->m_gs->Flip(true);
}
}
void MainWindow::on_actionBoot_DiscImage_triggered()
{
QFileDialog dialog(this);
dialog.setDirectory(PathToQString(m_lastPath));
dialog.setFileMode(QFileDialog::ExistingFile);
dialog.setNameFilter(tr("All supported types(*.iso *.bin *.isz *.cso);;UltraISO Compressed Disk Images (*.isz);;CISO Compressed Disk Images (*.cso);;All files (*.*)"));
if(dialog.exec())
{
auto filePath = QStringToPath(dialog.selectedFiles().first());
m_lastPath = filePath.parent_path();
CAppConfig::GetInstance().SetPreferencePath(PREF_PS2_CDROM0_PATH, filePath);
if(m_virtualMachine != nullptr)
{
try
{
TryRegisteringBootable(filePath);
m_lastOpenCommand = LastOpenCommand(BootType::CD, filePath);
BootCDROM();
}
catch(const std::exception& e)
{
QMessageBox messageBox;
messageBox.critical(nullptr, "Error", e.what());
messageBox.show();
}
}
}
}
void MainWindow::on_actionBoot_DiscImage_S3_triggered()
{
S3FileBrowser browser(this);
if(browser.exec())
{
auto filePath = browser.GetSelectedPath();
CAppConfig::GetInstance().SetPreferencePath(PREF_PS2_CDROM0_PATH, filePath);
if(m_virtualMachine != nullptr)
{
try
{
BootCDROM();
}
catch(const std::exception& e)
{
QMessageBox messageBox;
messageBox.critical(nullptr, "Error", e.what());
messageBox.show();
}
}
}
}
void MainWindow::on_actionBoot_cdrom0_triggered()
{
try
{
BootCDROM();
}
catch(const std::exception& e)
{
QMessageBox messageBox;
messageBox.critical(nullptr, "Error", e.what());
messageBox.show();
}
}
void MainWindow::on_actionBoot_ELF_triggered()
{
QFileDialog dialog(this);
dialog.setDirectory(PathToQString(m_lastPath));
dialog.setFileMode(QFileDialog::ExistingFile);
dialog.setNameFilter(tr("ELF files (*.elf)"));
if(dialog.exec())
{
auto filePath = QStringToPath(dialog.selectedFiles().first());
m_lastPath = filePath.parent_path();
if(m_virtualMachine != nullptr)
{
try
{
BootElf(filePath);
}
catch(const std::exception& e)
{
QMessageBox messageBox;
messageBox.critical(nullptr, "Error", e.what());
messageBox.show();
}
}
}
}
void MainWindow::BootElf(fs::path filePath)
{
BootablesDb::CClient::GetInstance().SetLastBootedTime(filePath, std::time(nullptr));
m_lastOpenCommand = LastOpenCommand(BootType::ELF, filePath);
m_virtualMachine->Pause();
m_virtualMachine->Reset();
m_virtualMachine->m_ee->m_os->BootFromFile(filePath);
#ifndef DEBUGGER_INCLUDED
m_virtualMachine->Resume();
#endif
m_msgLabel->setText(QString("Loaded executable '%1'.")
.arg(m_virtualMachine->m_ee->m_os->GetExecutableName()));
}
void MainWindow::LoadCDROM(fs::path filePath)
{
m_lastPath = filePath.parent_path();
CAppConfig::GetInstance().SetPreferencePath(PREF_PS2_CDROM0_PATH, filePath);
}
void MainWindow::BootCDROM()
{
auto filePath = CAppConfig::GetInstance().GetPreferencePath(PREF_PS2_CDROM0_PATH);
m_lastOpenCommand = LastOpenCommand(BootType::CD, filePath);
BootablesDb::CClient::GetInstance().SetLastBootedTime(filePath, std::time(nullptr));
m_virtualMachine->Pause();
m_virtualMachine->Reset();
m_virtualMachine->m_ee->m_os->BootFromCDROM();
#ifndef DEBUGGER_INCLUDED
m_virtualMachine->Resume();
#endif
m_msgLabel->setText(QString("Loaded executable '%1' from cdrom0.")
.arg(m_virtualMachine->m_ee->m_os->GetExecutableName()));
}
void MainWindow::on_actionExit_triggered()
{
close();
}
void MainWindow::keyPressEvent(QKeyEvent* event)
{
if((event->key() != Qt::Key_Escape) && m_qtKeyInputProvider)
{
m_qtKeyInputProvider->OnKeyPress(event->key());
}
}
void MainWindow::keyReleaseEvent(QKeyEvent* event)
{
if(event->key() == Qt::Key_Escape)
{
if(isFullScreen())
{
toggleFullscreen();
}
return;
}
if(m_qtKeyInputProvider)
{
m_qtKeyInputProvider->OnKeyRelease(event->key());
}
}
void MainWindow::CreateStatusBar()
{
m_fpsLabel = new QLabel("");
m_fpsLabel->setAlignment(Qt::AlignHCenter);
m_fpsLabel->setMinimumSize(m_fpsLabel->sizeHint());
m_msgLabel = new ElidedLabel();
m_msgLabel->setAlignment(Qt::AlignLeft);
QFontMetrics fm(m_msgLabel->font());
m_msgLabel->setMinimumSize(fm.boundingRect("...").size());
m_msgLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
statusBar()->addWidget(m_msgLabel, 1);
statusBar()->addWidget(m_fpsLabel);
#ifdef HAS_GSH_VULKAN
m_gsLabel = new QLabel("");
auto gs_index = CAppConfig::GetInstance().GetPreferenceInteger(PREF_VIDEO_GS_HANDLER);
UpdateGSHandlerLabel(gs_index);
m_gsLabel->setAlignment(Qt::AlignHCenter);
m_gsLabel->setMinimumSize(m_gsLabel->sizeHint());
//QLabel have no click event, so we're using ContextMenu event aka rightClick to toggle GS
m_gsLabel->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_gsLabel, &QLabel::customContextMenuRequested, [&]() {
auto gs_index = CAppConfig::GetInstance().GetPreferenceInteger(PREF_VIDEO_GS_HANDLER);
gs_index = (gs_index + 1) % SettingsDialog::GS_HANDLERS::MAX_HANDLER;
CAppConfig::GetInstance().SetPreferenceInteger(PREF_VIDEO_GS_HANDLER, gs_index);
SetupGsHandler();
UpdateGSHandlerLabel(gs_index);
});
statusBar()->addWidget(m_gsLabel);
#endif
m_msgLabel->setText(QString("Play! v%1 - %2").arg(PLAY_VERSION).arg(__DATE__));
m_fpsTimer = new QTimer(this);
connect(m_fpsTimer, SIGNAL(timeout()), this, SLOT(updateStats()));
m_fpsTimer->start(1000);
}
void MainWindow::updateStats()
{
uint32 frames = CStatsManager::GetInstance().GetFrames();
uint32 drawCalls = CStatsManager::GetInstance().GetDrawCalls();
uint32 dcpf = (frames != 0) ? (drawCalls / frames) : 0;
#ifdef PROFILE
m_profileStatsLabel->setText(QString::fromStdString(CStatsManager::GetInstance().GetProfilingInfo()));
#endif
m_fpsLabel->setText(QString("%1 f/s, %2 dc/f").arg(frames).arg(dcpf));
CStatsManager::GetInstance().ClearStats();
}
void MainWindow::on_actionSettings_triggered()
{
auto gs_index = CAppConfig::GetInstance().GetPreferenceInteger(PREF_VIDEO_GS_HANDLER);
SettingsDialog sd;
sd.exec();
SetupSoundHandler();
if(m_virtualMachine != nullptr)
{
m_virtualMachine->ReloadSpuBlockCount();
auto new_gs_index = CAppConfig::GetInstance().GetPreferenceInteger(PREF_VIDEO_GS_HANDLER);
if(gs_index != new_gs_index)
{
UpdateGSHandlerLabel(new_gs_index);
SetupGsHandler();
}
else
{
outputWindow_resized();
auto gsHandler = m_virtualMachine->GetGSHandler();
if(gsHandler)
{
gsHandler->NotifyPreferencesChanged();
}
}
}
}
void MainWindow::SetupSaveLoadStateSlots()
{
bool enable = (m_virtualMachine != nullptr ? (m_virtualMachine->m_ee->m_os->GetELF() != nullptr) : false);
ui->menuSave_States->clear();
ui->menuLoad_States->clear();
for(int i = 0; i < 10; i++)
{
QString info = enable ? GetSaveStateInfo(i) : "Empty";
QAction* saveaction = new QAction(this);
saveaction->setText(QString("Save Slot %1 - %2").arg(i).arg(info));
saveaction->setEnabled(enable);
ui->menuSave_States->addAction(saveaction);
QAction* loadaction = new QAction(this);
loadaction->setText(QString("Load Slot %1 - %2").arg(i).arg(info));
loadaction->setEnabled(enable);
ui->menuLoad_States->addAction(loadaction);
if(enable)
{
connect(saveaction, &QAction::triggered, std::bind(&MainWindow::saveState, this, i));
connect(loadaction, &QAction::triggered, std::bind(&MainWindow::loadState, this, i));
}
}
}
void MainWindow::saveState(int stateSlot)
{
auto stateFilePath = m_virtualMachine->GenerateStatePath(stateSlot);
auto future = m_virtualMachine->SaveState(stateFilePath);
m_continuationChecker->GetContinuationManager().Register(std::move(future),
[this, stateSlot = stateSlot](const bool& succeeded) {
if(succeeded)
{
m_msgLabel->setText(QString("Saved state to slot %1.").arg(stateSlot));
QString datetime = GetSaveStateInfo(stateSlot);
ui->menuSave_States->actions().at(stateSlot)->setText(QString("Save Slot %1 - %2").arg(stateSlot).arg(datetime));
ui->menuLoad_States->actions().at(stateSlot)->setText(QString("Load Slot %1 - %2").arg(stateSlot).arg(datetime));
}
else
{
m_msgLabel->setText(QString("Error saving state to slot %1.").arg(stateSlot));
}
});
}
void MainWindow::loadState(int stateSlot)
{
auto stateFilePath = m_virtualMachine->GenerateStatePath(stateSlot);
auto future = m_virtualMachine->LoadState(stateFilePath);
m_continuationChecker->GetContinuationManager().Register(std::move(future),
[this, stateSlot = stateSlot](const bool& succeeded) {
if(succeeded)
{
m_msgLabel->setText(QString("Loaded state from slot %1.").arg(stateSlot));
#ifndef DEBUGGER_INCLUDED
m_virtualMachine->Resume();
#endif
}
else
{
m_msgLabel->setText(QString("Error loading state from slot %1.").arg(stateSlot));
}
});
}
QString MainWindow::GetSaveStateInfo(int stateSlot)
{
auto stateFilePath = m_virtualMachine->GenerateStatePath(stateSlot);
QFileInfo file(PathToQString(stateFilePath));
if(file.exists() && file.isFile())
{
return file.lastModified().toString("hh:mm dd.MM.yyyy");
}
else
{
return "Empty";
}
}
void MainWindow::on_actionPause_Resume_triggered()
{
if(m_virtualMachine != nullptr)
{
if(m_virtualMachine->GetStatus() == CVirtualMachine::PAUSED)
{
m_msgLabel->setText("Virtual machine resumed.");
m_virtualMachine->Resume();
}
else
{
m_msgLabel->setText("Virtual machine paused.");
m_virtualMachine->Pause();
}
}
}
void MainWindow::closeEvent(QCloseEvent* event)
{
QMessageBox::StandardButton resBtn = QMessageBox::question(this, "Close Confirmation?",
tr("Are you sure you want to exit?\nHave you saved your progress?\n"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes);
if(resBtn != QMessageBox::Yes)
{
event->ignore();
}
else
{
event->accept();
}
}
void MainWindow::on_actionAbout_triggered()
{
auto about = QString("Version %1 (%2)\nQt v%3 - zlib v%4")
.arg(QString(PLAY_VERSION), __DATE__, QT_VERSION_STR, ZLIB_VERSION);
QMessageBox::about(this, this->windowTitle(), about);
}
void MainWindow::EmitOnExecutableChange()
{
emit onExecutableChange();
}
void MainWindow::HandleOnExecutableChange()
{
UpdateUI();
auto titleString = QString("Play! - [ %1 ] - %2").arg(m_virtualMachine->m_ee->m_os->GetExecutableName(), QString(PLAY_VERSION));
setWindowTitle(titleString);
}
void MainWindow::UpdateUI()
{
ui->actionPause_when_focus_is_lost->setChecked(m_pauseFocusLost);
ui->actionReset->setEnabled(!m_lastOpenCommand.path.empty());
SetOutputWindowSize();
SetupSaveLoadStateSlots();
}
void MainWindow::RegisterPreferences()
{
CAppConfig::GetInstance().RegisterPreferenceBoolean(PREFERENCE_AUDIO_ENABLEOUTPUT, true);
CAppConfig::GetInstance().RegisterPreferenceBoolean(PREF_UI_PAUSEWHENFOCUSLOST, true);
CAppConfig::GetInstance().RegisterPreferenceInteger(PREF_VIDEO_GS_HANDLER, SettingsDialog::GS_HANDLERS::OPENGL);
CAppConfig::GetInstance().RegisterPreferenceString(PREF_INPUT_PAD1_PROFILE, "default");
}
void MainWindow::focusOutEvent(QFocusEvent* event)
{
if(m_pauseFocusLost && m_virtualMachine->GetStatus() == CVirtualMachine::RUNNING)
{
if(!isActiveWindow() && !m_outputwindow->isActive())
{
if(m_virtualMachine != nullptr)
{
m_virtualMachine->Pause();
m_deactivatePause = true;
}
}
}
}
void MainWindow::focusInEvent(QFocusEvent* event)
{
if(m_pauseFocusLost && m_virtualMachine->GetStatus() == CVirtualMachine::PAUSED)
{
if(m_deactivatePause && (isActiveWindow() || m_outputwindow->isActive()))
{
if(m_virtualMachine != nullptr)
{
m_virtualMachine->Resume();
m_deactivatePause = false;
}
}
}
}
void MainWindow::doubleClickEvent(QMouseEvent* ev)
{
if(ev->button() == Qt::LeftButton)
{
toggleFullscreen();
}
}
void MainWindow::toggleFullscreen()
{
if(isFullScreen())
{
showNormal();
statusBar()->show();
menuBar()->show();
}
else
{
showFullScreen();
statusBar()->hide();
menuBar()->hide();
}
}
#ifdef DEBUGGER_INCLUDED
bool MainWindow::nativeEventFilter(const QByteArray&, void* message, long* result)
{
auto msg = reinterpret_cast<MSG*>(message);
HWND activeWnd = GetActiveWindow();
if(m_debugger && (activeWnd == m_debugger->m_hWnd) &&
TranslateAccelerator(m_debugger->m_hWnd, m_debugger->GetAccelerators(), msg))
{
return true;
}
if(m_frameDebugger && (activeWnd == m_frameDebugger->m_hWnd) &&
TranslateAccelerator(m_frameDebugger->m_hWnd, m_frameDebugger->GetAccelerators(), msg))
{
return true;
}
return false;
}
void MainWindow::ShowDebugger()
{
m_debugger->Show(SW_SHOWMAXIMIZED);
SetForegroundWindow(*m_debugger);
}
void MainWindow::ShowFrameDebugger()
{
m_frameDebugger->Show(SW_SHOWMAXIMIZED);
SetForegroundWindow(*m_frameDebugger);
}
fs::path MainWindow::GetFrameDumpDirectoryPath()
{
return CAppConfig::GetBasePath() / fs::path("framedumps/");
}
void MainWindow::DumpNextFrame()
{
m_virtualMachine->TriggerFrameDump(
[&](const CFrameDump& frameDump) {
try
{
auto frameDumpDirectoryPath = GetFrameDumpDirectoryPath();
Framework::PathUtils::EnsurePathExists(frameDumpDirectoryPath);
for(unsigned int i = 0; i < UINT_MAX; i++)
{
auto frameDumpFileName = string_format("framedump_%08d.dmp.zip", i);
auto frameDumpPath = frameDumpDirectoryPath / fs::path(frameDumpFileName);
if(!fs::exists(frameDumpPath))
{
auto dumpStream = Framework::CreateOutputStdStream(frameDumpPath.native());
frameDump.Write(dumpStream);
m_msgLabel->setText(QString("Dumped frame to '%1'.").arg(frameDumpFileName.c_str()));
return;
}
}
}
catch(...)
{
}
m_msgLabel->setText(QString("Failed to dump frame."));
});
}
void MainWindow::ToggleGsDraw()
{
auto gs = m_virtualMachine->GetGSHandler();
if(gs == nullptr) return;
bool newState = !gs->GetDrawEnabled();
gs->SetDrawEnabled(newState);
debugMenuUi->actionGsDrawEnabled->setChecked(newState);
m_msgLabel->setText(newState ? QString("GS Draw Enabled") : QString("GS Draw Disabled"));
}
#endif
void MainWindow::on_actionPause_when_focus_is_lost_triggered(bool checked)
{
m_pauseFocusLost = checked;
CAppConfig::GetInstance().SetPreferenceBoolean(PREF_UI_PAUSEWHENFOCUSLOST, m_pauseFocusLost);
}
void MainWindow::on_actionReset_triggered()
{
if(!m_lastOpenCommand.path.empty())
{
if(m_lastOpenCommand.type == BootType::CD)
{
BootCDROM();
}
else if(m_lastOpenCommand.type == BootType::ELF)
{
BootElf(m_lastOpenCommand.path);
}
}
}
void MainWindow::on_actionMemory_Card_Manager_triggered()
{
MemoryCardManagerDialog mcm(this);
mcm.exec();
}
void MainWindow::on_actionVFS_Manager_triggered()
{
VFSManagerDialog vfsmgr;
vfsmgr.exec();
}
void MainWindow::on_actionController_Manager_triggered()
{
auto padHandler = static_cast<CPH_GenericInput*>(m_virtualMachine->GetPadHandler());
if(!padHandler) return;
ControllerConfigDialog ccd(&padHandler->GetBindingManager(), m_qtKeyInputProvider.get(), this);
ccd.exec();
}
void MainWindow::on_actionCapture_Screen_triggered()
{
m_screenShotCompleteConnection = CScreenShotUtils::TriggerGetScreenshot(m_virtualMachine,
[&](int res, const char* msg) -> void {
m_msgLabel->setText(msg);
});
}
void MainWindow::on_actionList_Bootables_triggered()
{
BootableListDialog dialog(this);
if(dialog.exec())
{
try
{
BootablesDb::Bootable bootable = dialog.getResult();
if(IsBootableDiscImagePath(bootable.path))
{
LoadCDROM(bootable.path);
BootCDROM();
}
else if(IsBootableExecutablePath(bootable.path))
{
BootElf(bootable.path);
}
else
{
QMessageBox messageBox;
QString invalid("Invalid File Format.");
messageBox.critical(this, this->windowTitle(), invalid);
messageBox.show();
}
}
catch(const std::exception& e)
{
QMessageBox messageBox;
messageBox.critical(nullptr, "Error", e.what());
messageBox.show();
}
}
}
void MainWindow::UpdateGSHandlerLabel(int gs_index)
{
switch(gs_index)
{
default:
case SettingsDialog::GS_HANDLERS::OPENGL:
m_gsLabel->setText("OpenGL");
break;
#ifdef HAS_GSH_VULKAN
case SettingsDialog::GS_HANDLERS::VULKAN:
m_gsLabel->setText("Vulkan");
break;
#endif
}
}
|
// +----------------------------------------------------------------------
// | Project : ray.
// | All rights reserved.
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015.
// +----------------------------------------------------------------------
// | * Redistribution and use of this software in source and binary forms,
// | with or without modification, are permitted provided that the following
// | conditions are met:
// |
// | * Redistributions of source code must retain the above
// | copyright notice, this list of conditions and the
// | following disclaimer.
// |
// | * Redistributions in binary form must reproduce the above
// | copyright notice, this list of conditions and the
// | following disclaimer in the documentation and/or other
// | materials provided with the distribution.
// |
// | * Neither the name of the ray team, nor the names of its
// | contributors may be used to endorse or promote products
// | derived from this software without specific prior
// | written permission of the ray team.
// |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// +----------------------------------------------------------------------
#include <ray/physics_character.h>
#include <ray/physics_system.h>
#include "bullet_types.h"
_NAME_BEGIN
class CharacterController : public btKinematicCharacterController
{
public:
CharacterController(btPairCachingGhostObject* ghostObject, btConvexShape* convexShape, btScalar stepHeight) noexcept
: btKinematicCharacterController(ghostObject, convexShape, stepHeight)
{
}
~CharacterController() noexcept
{
}
virtual void setStepHeight(float height) noexcept
{
m_stepHeight = height;
}
virtual bool wasJumping() const noexcept
{
return m_wasJumping;
}
virtual void setJumpSpeed(float speed)
{
m_jumpSpeed = speed;
}
virtual void jump() noexcept
{
m_verticalVelocity = m_jumpSpeed;
m_wasJumping = true;
}
};
PhysicsCharacter::PhysicsCharacter() noexcept
: _ghostObject(nullptr)
, _character(nullptr)
, _capsule(nullptr)
, _stepHeight(1)
, _translate(Vector3::Zero)
, _radius(1)
, _height(1)
, _walkDirection(Vector3::Zero)
{
}
PhysicsCharacter::~PhysicsCharacter() noexcept
{
}
void
PhysicsCharacter::setup() noexcept
{
assert(!_character);
_capsule = std::make_unique<btCapsuleShape>(_radius, _height);
_ghostObject = std::make_unique<btPairCachingGhostObject>();
_ghostObject->setCollisionShape(_capsule.get());
_ghostObject->setCollisionFlags(btCollisionObject::CF_CHARACTER_OBJECT);
_character = std::make_unique<CharacterController>(_ghostObject.get(), _capsule.get(), _stepHeight);
this->setMovePosition(_translate);
this->setPhysicsScene(PhysicsSystem::instance()->getPhysicsScene());
}
void
PhysicsCharacter::close() noexcept
{
this->setPhysicsScene(nullptr);
_character.reset();
_ghostObject.reset();
_capsule.reset();
}
void
PhysicsCharacter::setRadius(float radius) noexcept
{
_radius = radius;
}
void
PhysicsCharacter::setHeight(float height) noexcept
{
_height = height;
}
void
PhysicsCharacter::setMovePosition(const Vector3& pos) noexcept
{
if (_character)
{
btVector3 origin(pos.x, pos.y, pos.z);
origin.setX(pos.x);
origin.setY(pos.y);
origin.setZ(pos.z);
_character->warp(origin);
}
_translate = pos;
}
void
PhysicsCharacter::setWalkDirection(const Vector3& direction) noexcept
{
if (_character)
{
btVector3 walkDirection;
walkDirection.setX(direction.x);
walkDirection.setY(direction.y);
walkDirection.setZ(direction.z);
_character->setWalkDirection(walkDirection);
}
_walkDirection = direction;
}
const Vector3&
PhysicsCharacter::getWalkDirection() const noexcept
{
return _walkDirection;
}
const Vector3&
PhysicsCharacter::getMovePosition() const noexcept
{
if (_character)
{
auto transform = _character->getGhostObject()->getWorldTransform();
auto origin = transform.getOrigin();
_translate.x = origin.x();
_translate.y = origin.y();
_translate.z = origin.z();
}
return _translate;
}
bool
PhysicsCharacter::canJumping() const noexcept
{
return _character->onGround() && !this->wasJumping();
}
bool
PhysicsCharacter::wasJumping() const noexcept
{
assert(_character);
return _character->wasJumping();
}
void
PhysicsCharacter::jump(float speed) noexcept
{
assert(_character);
_character->setJumpSpeed(10);
_character->jump();
}
void
PhysicsCharacter::setPhysicsScene(PhysicsScenePtr scene) noexcept
{
assert(_character);
if (_scene.lock())
{
_scene.lock()->removeAction(_character.get());
_scene.lock()->removeCharacter(_ghostObject.get());
}
_scene = scene;
if (scene)
{
scene->addAction(_character.get());
scene->addCharacter(_ghostObject.get());
}
}
_NAME_END
|
/*************************************************************************/
/* godot_linuxbsd.cpp */
/*************************************************************************/
/* This file is part of: */
/* Valjang Engine */
/* http://Valjang.fr */
/*************************************************************************/
/* Copyright (c) 2007-2020 Valjang. */
/* Copyright (c) 2014-2020 Valjang Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 <limits.h>
#include <locale.h>
#include <stdlib.h>
#include <unistd.h>
#include "main/main.h"
#include "os_linuxbsd.h"
int main(int argc, char *argv[]) {
OS_LinuxBSD os;
setlocale(LC_CTYPE, "");
// We must override main when testing is enabled
TEST_MAIN_OVERRIDE
char *cwd = (char *)malloc(PATH_MAX);
ERR_FAIL_COND_V(!cwd, ERR_OUT_OF_MEMORY);
char *ret = getcwd(cwd, PATH_MAX);
Error err = Main::setup(argv[0], argc - 1, &argv[1]);
if (err != OK) {
free(cwd);
return 255;
}
if (Main::start()) {
os.run(); // it is actually the OS that decides how to run
}
Main::cleanup();
if (ret) { // Previous getcwd was successful
if (chdir(cwd) != 0) {
ERR_PRINT("Couldn't return to previous working directory.");
}
}
free(cwd);
return os.get_exit_code();
}
|
/*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/address.hpp>
#include <bitcoin/constants.hpp>
#include <bitcoin/format.hpp>
#include <bitcoin/utility/base58.hpp>
#include <bitcoin/utility/ripemd.hpp>
#include <bitcoin/utility/sha256.hpp>
namespace libbitcoin {
payment_address::payment_address()
: version_(pubkey_version), hash_(null_short_hash)
{
}
payment_address::payment_address(uint8_t version, const short_hash& hash)
: payment_address()
{
set(version, hash);
}
payment_address::payment_address(const std::string& encoded_address)
: payment_address()
{
set_encoded(encoded_address);
}
void payment_address::set(uint8_t version, const short_hash& hash)
{
version_ = version;
hash_ = hash;
}
uint8_t payment_address::version() const
{
return version_;
}
const short_hash& payment_address::hash() const
{
return hash_;
}
bool payment_address::set_encoded(const std::string& encoded_address)
{
const data_chunk decoded_address = decode_base58(encoded_address);
// version + 20 bytes short hash + 4 bytes checksum
if (decoded_address.size() != 25)
return false;
version_ = decoded_address[0];
const data_chunk checksum_bytes(
decoded_address.end() - 4, decoded_address.end());
// version + short hash
const data_chunk main_body(
decoded_address.begin(), decoded_address.end() - 4);
// verify checksum bytes
if (generate_sha256_checksum(main_body) !=
cast_chunk<uint32_t>(checksum_bytes))
return false;
std::copy(main_body.begin() + 1, main_body.end(), hash_.begin());
return true;
}
std::string payment_address::encoded() const
{
data_chunk unencoded_address;
// Type, Hash, Checksum doth make thy address
unencoded_address.push_back(version_);
extend_data(unencoded_address, hash_);
uint32_t checksum = generate_sha256_checksum(unencoded_address);
extend_data(unencoded_address, uncast_type(checksum));
BITCOIN_ASSERT(unencoded_address.size() == 25);
return encode_base58(unencoded_address);
}
void set_public_key_hash(payment_address& address,
const short_hash& pubkey_hash)
{
address.set(payment_address::pubkey_version, pubkey_hash);
}
void set_script_hash(payment_address& address,
const short_hash& script_hash)
{
address.set(payment_address::script_version, script_hash);
}
void set_public_key(payment_address& address, const data_chunk& public_key)
{
address.set(payment_address::pubkey_version,
generate_ripemd_hash(public_key));
}
void set_script(payment_address& address, const script_type& eval_script)
{
address.set(payment_address::script_version,
generate_ripemd_hash(save_script(eval_script)));
}
bool extract(payment_address& address, const script_type& script)
{
// Cast a data_chunk to a short_hash and set the address
auto set_hash_data =
[&address](uint8_t version, const data_chunk& raw_hash)
{
short_hash hash_data;
BITCOIN_ASSERT(raw_hash.size() == hash_data.size());
std::copy(raw_hash.begin(), raw_hash.end(), hash_data.begin());
address.set(version, hash_data);
};
const operation_stack& ops = script.operations();
payment_type pay_type = script.type();
switch (pay_type)
{
case payment_type::pubkey:
BITCOIN_ASSERT(ops.size() == 2);
set_public_key(address, ops[0].data);
return true;
case payment_type::pubkey_hash:
BITCOIN_ASSERT(ops.size() == 5);
set_hash_data(payment_address::pubkey_version, ops[2].data);
return true;
case payment_type::script_hash:
BITCOIN_ASSERT(ops.size() == 3);
set_hash_data(payment_address::script_version, ops[1].data);
return true;
case payment_type::multisig:
// Unimplemented...
return false;
case payment_type::pubkey_hash_sig:
BITCOIN_ASSERT(ops.size() == 2);
set_public_key(address, ops[1].data);
return true;
case payment_type::script_code_sig:
// Should have at least 1 sig and the script code.
BITCOIN_ASSERT(ops.size() > 1);
set_script_hash(address,
generate_ripemd_hash(ops.back().data));
return true;
default:
return false;
}
// Should never happen!
return false;
}
bool operator==(const payment_address& lhs, const payment_address& rhs)
{
return lhs.hash() == rhs.hash() && lhs.version() == rhs.version();
}
} // namespace libbitcoin
|
#include "filltool.h"
#include "toonz/tframehandle.h"
#include "toonz/tcolumnhandle.h"
#include "toonz/tpalettehandle.h"
#include "toonz/preferences.h"
#include "toonz/txsheethandle.h"
#include "toonz/tobjecthandle.h"
#include "toonz/tscenehandle.h"
#include "tools/toolhandle.h"
#include "tools/toolutils.h"
#include "toonz/tonionskinmaskhandle.h"
#include "timagecache.h"
#include "tundo.h"
#include "tpalette.h"
#include "tcolorstyles.h"
#include "tvectorimage.h"
#include "tools/cursors.h"
#include "ttoonzimage.h"
#include "tproperty.h"
#include "tenv.h"
#include "tools/stylepicker.h"
#include "toonz/stage2.h"
#include "tstroke.h"
#include "drawutil.h"
#include "tsystem.h"
#include "tinbetween.h"
#include "tregion.h"
#include "tgl.h"
#include "trop.h"
#include "tropcm.h"
#include "toonz/onionskinmask.h"
#include "toonz/ttileset.h"
#include "toonz/ttilesaver.h"
#include "toonz/toonzimageutils.h"
#include "toonz/levelproperties.h"
#include "toonz/txshcell.h"
#include "toonzqt/imageutils.h"
#include "autofill.h"
#include "historytypes.h"
#include "toonz/autoclose.h"
#include <stack>
// For Qt translation support
#include <QCoreApplication>
using namespace ToolUtils;
//#define LINES L"Lines"
//#define AREAS L"Areas"
//#define ALL L"Lines & Areas"
#define NORMALFILL L"Normal"
#define RECTFILL L"Rectangular"
#define FREEHANDFILL L"Freehand"
#define POLYLINEFILL L"Polyline"
TEnv::IntVar MinFillDepth("InknpaintMinFillDepth", 0);
TEnv::IntVar MaxFillDepth("InknpaintMaxFillDepth", 10);
TEnv::StringVar FillType("InknpaintFillType", "Normal");
TEnv::StringVar FillColorType("InknpaintFillColorType", "Areas");
TEnv::IntVar FillSelective("InknpaintFillSelective", 0);
TEnv::IntVar FillOnion("InknpaintFillOnion", 0);
TEnv::IntVar FillSegment("InknpaintFillSegment", 0);
TEnv::IntVar FillRange("InknpaintFillRange", 0);
TEnv::IntVar FillOnlySavebox("InknpaintFillOnlySavebox", 0);
TEnv::StringVar RasterGapSetting("RasterGapSetting", "Ignore Gaps");
extern TEnv::DoubleVar AutocloseDistance;
extern TEnv::DoubleVar AutocloseAngle;
extern TEnv::IntVar AutocloseInk;
extern TEnv::IntVar AutocloseOpacity;
void checkSegments(std::vector<TAutocloser::Segment> &segments, TStroke *stroke,
const TRasterCM32P &ras, const TPoint &delta) {
TVectorImage vi;
TStroke *app = new TStroke();
*app = *stroke;
app->transform(TTranslation(convert(ras->getCenter())));
vi.addStroke(app);
vi.findRegions();
std::vector<TAutocloser::Segment>::iterator it = segments.begin();
for (; it < segments.end(); it++) {
if (it == segments.end()) break;
int i;
bool isContained = false;
for (i = 0; i < (int)vi.getRegionCount(); i++) {
TRegion *reg = vi.getRegion(i);
if (reg->contains(convert(it->first + delta)) &&
reg->contains(convert(it->second + delta))) {
isContained = true;
break;
}
}
if (!isContained) {
it = segments.erase(it);
if (it != segments.end() && it != segments.begin())
it--;
else if (it == segments.end())
break;
}
}
}
class AutocloseParameters {
public:
int m_closingDistance, m_inkIndex, m_opacity;
double m_spotAngle;
AutocloseParameters()
: m_closingDistance(0), m_inkIndex(0), m_spotAngle(0), m_opacity(1) {}
};
bool applyAutoclose(const TToonzImageP &ti, int distance, int angle,
int opacity, int newInkIndex, const TRectD &selRect,
TStroke *stroke = 0) {
if (!ti) return false;
TPoint delta;
TRasterCM32P ras, raux = ti->getRaster();
if (!stroke && raux && !selRect.isEmpty()) {
TRectD selArea = selRect;
if (selRect.x0 > selRect.x1) {
selArea.x1 = selRect.x0;
selArea.x0 = selRect.x1;
}
if (selRect.y0 > selRect.y1) {
selArea.y1 = selRect.y0;
selArea.y0 = selRect.y1;
}
TRect myRect = convert(selArea);
ras = raux->extract(myRect);
delta = myRect.getP00();
} else if (stroke) {
TRectD selArea = stroke->getBBox();
TRect myRect(ToonzImageUtils::convertWorldToRaster(selArea, ti));
ras = raux->extract(myRect);
delta = myRect.getP00();
} else
ras = raux;
if (!ras) return false;
TAutocloser ac(ras, distance, angle, newInkIndex, opacity);
std::vector<TAutocloser::Segment> segments;
ac.compute(segments);
if (stroke) checkSegments(segments, stroke, raux, delta);
std::vector<TAutocloser::Segment> segments2(segments);
/*-- segmentが取得できなければfalseを返す --*/
if (segments2.empty()) return false;
int i;
if (delta != TPoint(0, 0))
for (i = 0; i < (int)segments2.size(); i++) {
segments2[i].first += delta;
segments2[i].second += delta;
}
ac.draw(segments);
return true;
}
//-----------------------------------------------------------------------------
namespace {
inline int vectorFill(const TVectorImageP &img, const std::wstring &type,
const TPointD &point, int style, bool emptyOnly = false) {
if (type == ALL || type == LINES) {
int oldStyleId = img->fillStrokes(point, style);
if (oldStyleId != -1) return oldStyleId;
}
if (type == ALL || type == AREAS) return img->fill(point, style, emptyOnly);
return -1;
}
//=============================================================================
// VectorFillUndo
//-----------------------------------------------------------------------------
class VectorFillUndo final : public TToolUndo {
int m_oldColorStyle;
int m_newColorStyle;
TPointD m_point;
std::wstring m_type;
int m_row;
int m_column;
public:
VectorFillUndo(int newColorStyle, int oldColorStyle, std::wstring fillType,
TPointD clickPoint, TXshSimpleLevel *sl, const TFrameId &fid)
: TToolUndo(sl, fid)
, m_newColorStyle(newColorStyle)
, m_oldColorStyle(oldColorStyle)
, m_point(clickPoint)
, m_type(fillType) {
TTool::Application *app = TTool::getApplication();
if (app) {
m_row = app->getCurrentFrame()->getFrame();
m_column = app->getCurrentColumn()->getColumnIndex();
}
}
void undo() const override {
TTool::Application *app = TTool::getApplication();
if (!app) return;
app->getCurrentLevel()->setLevel(m_level.getPointer());
TVectorImageP img = m_level->getFrame(m_frameId, true);
if (app->getCurrentFrame()->isEditingScene()) {
app->getCurrentFrame()->setFrame(m_row);
app->getCurrentColumn()->setColumnIndex(m_column);
} else
app->getCurrentFrame()->setFid(m_frameId);
assert(img);
if (!img) return;
QMutexLocker lock(img->getMutex());
vectorFill(img, m_type, m_point, m_oldColorStyle);
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
void redo() const override {
TTool::Application *app = TTool::getApplication();
if (!app) return;
app->getCurrentLevel()->setLevel(m_level.getPointer());
TVectorImageP img = m_level->getFrame(m_frameId, true);
if (app->getCurrentFrame()->isEditingScene()) {
app->getCurrentFrame()->setFrame(m_row);
app->getCurrentColumn()->setColumnIndex(m_column);
} else
app->getCurrentFrame()->setFid(m_frameId);
assert(img);
if (!img) return;
QMutexLocker lock(img->getMutex());
vectorFill(img, m_type, m_point, m_newColorStyle);
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
void onAdd() override {}
int getSize() const override { return sizeof(*this); }
QString getToolName() override {
return QString("Fill Tool : %1").arg(QString::fromStdWString(m_type));
}
int getHistoryType() override { return HistoryType::FillTool; }
};
//=============================================================================
// VectorRectFillUndo
//-----------------------------------------------------------------------------
class VectorRectFillUndo final : public TToolUndo {
std::vector<TFilledRegionInf> *m_regionFillInformation;
std::vector<std::pair<int, int>> *m_strokeFillInformation;
TRectD m_selectionArea;
int m_styleId;
bool m_unpaintedOnly;
TStroke *m_stroke;
public:
~VectorRectFillUndo() {
if (m_regionFillInformation) delete m_regionFillInformation;
if (m_strokeFillInformation) delete m_strokeFillInformation;
if (m_stroke) delete m_stroke;
}
VectorRectFillUndo(std::vector<TFilledRegionInf> *regionFillInformation,
std::vector<std::pair<int, int>> *strokeFillInformation,
TRectD selectionArea, TStroke *stroke, int styleId,
bool unpaintedOnly, TXshSimpleLevel *sl,
const TFrameId &fid)
: TToolUndo(sl, fid)
, m_regionFillInformation(regionFillInformation)
, m_strokeFillInformation(strokeFillInformation)
, m_selectionArea(selectionArea)
, m_styleId(styleId)
, m_unpaintedOnly(unpaintedOnly)
, m_stroke(0) {
if (stroke) m_stroke = new TStroke(*stroke);
}
void undo() const override {
TTool::Application *app = TTool::getApplication();
if (!app) return;
TVectorImageP img = m_level->getFrame(m_frameId, true);
assert(!!img);
if (!img) return;
if (m_regionFillInformation) {
for (UINT i = 0; i < m_regionFillInformation->size(); i++) {
TRegion *reg = img->getRegion((*m_regionFillInformation)[i].m_regionId);
if (reg) reg->setStyle((*m_regionFillInformation)[i].m_styleId);
}
}
if (m_strokeFillInformation) {
for (UINT i = 0; i < m_strokeFillInformation->size(); i++) {
TStroke *s = img->getStroke((*m_strokeFillInformation)[i].first);
s->setStyle((*m_strokeFillInformation)[i].second);
}
}
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
void redo() const override {
TTool::Application *app = TTool::getApplication();
if (!app) return;
TVectorImageP img = m_level->getFrame(m_frameId, true);
assert(img);
if (!img) return;
img->selectFill(m_selectionArea, m_stroke, m_styleId, m_unpaintedOnly,
m_regionFillInformation != 0, m_strokeFillInformation != 0);
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
void onAdd() override {}
int getSize() const override {
int size1 = m_regionFillInformation
? m_regionFillInformation->capacity() *
sizeof(m_regionFillInformation)
: 0;
int size2 = m_strokeFillInformation
? m_strokeFillInformation->capacity() *
sizeof(m_strokeFillInformation)
: 0;
return sizeof(*this) + size1 + size2 + 500;
}
QString getToolName() override { return QString("Fill Tool : "); }
int getHistoryType() override { return HistoryType::FillTool; }
};
//=============================================================================
// VectorGapSizeChangeUndo
//-----------------------------------------------------------------------------
class VectorGapSizeChangeUndo final : public TToolUndo {
double m_oldGapSize;
double m_newGapSize;
int m_row;
int m_column;
TVectorImageP m_vi;
std::vector<TFilledRegionInf> m_oldFillInformation;
public:
VectorGapSizeChangeUndo(double oldGapSize, double newGapSize,
TXshSimpleLevel *sl, const TFrameId &fid,
TVectorImageP vi,
std::vector<TFilledRegionInf> oldFillInformation)
: TToolUndo(sl, fid)
, m_oldGapSize(oldGapSize)
, m_newGapSize(newGapSize)
, m_oldFillInformation(oldFillInformation)
, m_vi(vi) {
TTool::Application *app = TTool::getApplication();
if (app) {
m_row = app->getCurrentFrame()->getFrame();
m_column = app->getCurrentColumn()->getColumnIndex();
}
}
void undo() const override {
TTool::Application *app = TTool::getApplication();
if (!app || !m_level) return;
app->getCurrentLevel()->setLevel(m_level.getPointer());
if (app->getCurrentFrame()->isEditingScene()) {
app->getCurrentFrame()->setFrame(m_row);
app->getCurrentColumn()->setColumnIndex(m_column);
} else
app->getCurrentFrame()->setFid(m_frameId);
m_vi->setAutocloseTolerance(m_oldGapSize);
int count = m_vi->getStrokeCount();
std::vector<int> v(count);
int i;
for (i = 0; i < (int)count; i++) v[i] = i;
m_vi->notifyChangedStrokes(v, std::vector<TStroke *>(), false);
if (m_vi->isComputedRegionAlmostOnce()) m_vi->findRegions();
if (m_oldFillInformation.size()) {
for (UINT j = 0; j < m_oldFillInformation.size(); j++) {
TRegion *reg = m_vi->getRegion(m_oldFillInformation[j].m_regionId);
if (reg) reg->setStyle(m_oldFillInformation[j].m_styleId);
}
}
app->getCurrentXsheet()->notifyXsheetChanged();
app->getCurrentTool()->notifyToolChanged();
notifyImageChanged();
}
void redo() const override {
TTool::Application *app = TTool::getApplication();
if (!app || !m_level) return;
app->getCurrentLevel()->setLevel(m_level.getPointer());
TVectorImageP img = m_level->getFrame(m_frameId, true);
if (app->getCurrentFrame()->isEditingScene()) {
app->getCurrentFrame()->setFrame(m_row);
app->getCurrentColumn()->setColumnIndex(m_column);
} else
app->getCurrentFrame()->setFid(m_frameId);
m_vi->setAutocloseTolerance(m_newGapSize);
int count = m_vi->getStrokeCount();
std::vector<int> v(count);
int i;
for (i = 0; i < (int)count; i++) v[i] = i;
m_vi->notifyChangedStrokes(v, std::vector<TStroke *>(), false);
app->getCurrentXsheet()->notifyXsheetChanged();
app->getCurrentTool()->notifyToolChanged();
notifyImageChanged();
}
void onAdd() override {}
int getSize() const override { return sizeof(*this); }
QString getToolName() override {
return QString("Fill Tool: Set Gap Size ") + QString::number(m_newGapSize);
}
int getHistoryType() override { return HistoryType::FillTool; }
};
//=============================================================================
// RasterFillUndo
//-----------------------------------------------------------------------------
class RasterFillUndo final : public TRasterUndo {
FillParameters m_params;
bool m_saveboxOnly, m_closeGaps, m_fillGaps;
double m_autoCloseDistance;
int m_closeStyleIndex;
TRectD m_savebox;
public:
/*RasterFillUndo(TTileSetCM32 *tileSet, TPoint fillPoint,
int paintId, int
fillDepth,
std::wstring
fillType, bool isSegment,
bool selective, bool
isShiftFill,
TXshSimpleLevel* sl,
const TFrameId& fid)*/
RasterFillUndo(TTileSetCM32 *tileSet, const FillParameters ¶ms,
TXshSimpleLevel *sl, const TFrameId &fid, bool saveboxOnly,
bool fillGaps, bool closeGaps, int closeStyleIndex,
double autoCloseDistance, TRectD savebox)
: TRasterUndo(tileSet, sl, fid, false, false, 0)
, m_params(params)
, m_closeGaps(closeGaps)
, m_fillGaps(fillGaps)
, m_autoCloseDistance(autoCloseDistance)
, m_closeStyleIndex(closeStyleIndex)
, m_saveboxOnly(saveboxOnly)
, m_savebox(savebox) {}
void redo() const override {
TToonzImageP image = getImage();
if (!image) return;
bool recomputeSavebox = false;
TRasterCM32P r;
if (m_saveboxOnly) {
TRect ttemp = convert(m_savebox);
r = image->getRaster()->extract(ttemp);
} else
r = image->getRaster();
if (m_params.m_fillType == ALL || m_params.m_fillType == AREAS) {
if (m_params.m_shiftFill) {
FillParameters aux(m_params);
aux.m_styleId = (m_params.m_styleId == 0) ? 1 : 0;
recomputeSavebox = fill(r, aux, 0, m_fillGaps, m_closeGaps,
m_closeStyleIndex, m_autoCloseDistance);
}
recomputeSavebox = fill(r, m_params, 0, m_fillGaps, m_closeGaps,
m_closeStyleIndex, m_autoCloseDistance);
}
if (m_params.m_fillType == ALL || m_params.m_fillType == LINES) {
if (m_params.m_segment)
inkSegment(r, m_params.m_p, m_params.m_styleId, 2.51, true);
else
inkFill(r, m_params.m_p, m_params.m_styleId, 2);
}
if (recomputeSavebox) ToolUtils::updateSaveBox();
TTool::Application *app = TTool::getApplication();
if (app) {
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
}
int getSize() const override {
return sizeof(*this) + TRasterUndo::getSize();
}
QString getToolName() override {
return QString("Fill Tool : %1")
.arg(QString::fromStdWString(m_params.m_fillType));
}
int getHistoryType() override { return HistoryType::FillTool; }
};
//=============================================================================
// RasterRectFillUndo
//-----------------------------------------------------------------------------
class RasterRectFillUndo final : public TRasterUndo {
TRect m_fillArea;
int m_paintId;
std::wstring m_colorType;
TStroke *m_s;
bool m_onlyUnfilled;
TPalette *m_palette;
TXshSimpleLevel *m_level;
bool m_fillGaps, m_closeGaps;
double m_autoCloseDistance;
int m_closeStyleIndex;
public:
~RasterRectFillUndo() {
if (m_s) delete m_s;
}
RasterRectFillUndo(TTileSetCM32 *tileSet, TStroke *s, TRect fillArea,
int paintId, TXshSimpleLevel *level,
std::wstring colorType, bool onlyUnfilled,
const TFrameId &fid, TPalette *palette, bool fillGaps,
bool closeGaps, int closeStyleIndex,
double autoCloseDistance)
: TRasterUndo(tileSet, level, fid, false, false, 0)
, m_fillArea(fillArea)
, m_paintId(paintId)
, m_colorType(colorType)
, m_onlyUnfilled(onlyUnfilled)
, m_level(level)
, m_fillGaps(fillGaps)
, m_closeGaps(closeGaps)
, m_closeStyleIndex(closeStyleIndex)
, m_autoCloseDistance(autoCloseDistance)
, m_palette(palette) {
m_s = s ? new TStroke(*s) : 0;
}
void redo() const override {
TToonzImageP image = getImage();
if (!image) return;
TRasterCM32P ras = image->getRaster();
TRasterCM32P tempRaster;
int styleIndex = 4094;
if (m_fillGaps) {
TToonzImageP tempTi = image->clone();
tempRaster = tempTi->getRaster();
TRectD doubleFillArea = convert(m_fillArea);
applyAutoclose(tempTi, AutocloseDistance, AutocloseAngle,
AutocloseOpacity, 4094, doubleFillArea, m_s);
} else {
tempRaster = ras;
}
AreaFiller filler(tempRaster);
if (!m_s)
filler.rectFill(m_fillArea, m_paintId, m_onlyUnfilled,
m_colorType != LINES, m_colorType != AREAS);
else
filler.strokeFill(m_s, m_paintId, m_onlyUnfilled, m_colorType != LINES,
m_colorType != AREAS, m_fillArea);
if (m_fillGaps) {
TPixelCM32 *tempPix = tempRaster->pixels();
TPixelCM32 *keepPix = ras->pixels();
for (int tempY = 0; tempY < tempRaster->getLy(); tempY++) {
for (int tempX = 0; tempX < tempRaster->getLx();
tempX++, tempPix++, keepPix++) {
keepPix->setPaint(tempPix->getPaint());
if (tempPix->getInk() != styleIndex) {
if (m_colorType == AREAS && m_closeGaps &&
tempPix->getInk() == 4095) {
keepPix->setInk(m_closeStyleIndex);
keepPix->setTone(tempPix->getTone());
} else if (m_colorType != AREAS && tempPix->getInk() == 4095) {
keepPix->setInk(m_paintId);
keepPix->setTone(tempPix->getTone());
} else if (tempPix->getInk() != 4095) {
keepPix->setInk(tempPix->getInk());
}
}
}
}
}
if (m_palette) {
TRect rect = m_fillArea;
TRect bounds = ras->getBounds();
if (bounds.overlaps(rect)) {
rect *= bounds;
const TTileSetCM32::Tile *tile =
m_tiles->getTile(m_tiles->getTileCount() - 1);
TRasterCM32P rbefore;
tile->getRaster(rbefore);
fillautoInks(ras, rect, rbefore, m_palette);
}
}
TTool::Application *app = TTool::getApplication();
if (app) {
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
}
int getSize() const override {
int size =
m_s ? m_s->getControlPointCount() * sizeof(TThickPoint) + 100 : 0;
return sizeof(*this) + TRasterUndo::getSize() + size;
}
QString getToolName() override {
return QString("Fill Tool : %1").arg(QString::fromStdWString(m_colorType));
}
int getHistoryType() override { return HistoryType::FillTool; }
};
//=============================================================================
// RasterRectAutoFillUndo
//-----------------------------------------------------------------------------
class RasterRectAutoFillUndo final : public TRasterUndo {
TRect m_rectToFill;
TFrameId m_fidToLearn;
bool m_onlyUnfilled;
public:
~RasterRectAutoFillUndo() {}
RasterRectAutoFillUndo(TTileSetCM32 *tileSet, const TRect &rectToFill,
TXshSimpleLevel *level, bool onlyUnfilled,
const TFrameId ¤tFid, const TFrameId &fidToLearn)
: TRasterUndo(tileSet, level, currentFid, false, false, 0)
, m_rectToFill(rectToFill)
, m_onlyUnfilled(onlyUnfilled)
, m_fidToLearn(fidToLearn) {}
void redo() const override {
TToonzImageP image = getImage();
TToonzImageP imageToLearn = m_level->getFrame(m_fidToLearn, false);
if (!image || !imageToLearn) return;
rect_autofill_learn(imageToLearn, m_rectToFill.x0, m_rectToFill.y0,
m_rectToFill.x1, m_rectToFill.y1);
TTileSetCM32 tileSet(image->getRaster()->getSize());
bool recomputeBBox = rect_autofill_apply(
image, m_rectToFill.x0, m_rectToFill.y0, m_rectToFill.x1,
m_rectToFill.y1, m_onlyUnfilled, &tileSet);
if (recomputeBBox) ToolUtils::updateSaveBox();
TTool::Application *app = TTool::getApplication();
if (app) {
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
}
int getSize() const override {
return sizeof(*this) + TRasterUndo::getSize();
}
};
//=============================================================================
// RasterStrokeAutoFillUndo
//-----------------------------------------------------------------------------
class RasterStrokeAutoFillUndo final : public TRasterUndo {
TTileSetCM32 *m_tileSet;
public:
~RasterStrokeAutoFillUndo() {
if (m_tileSet) delete m_tileSet;
}
RasterStrokeAutoFillUndo(TTileSetCM32 *tileSet, TXshSimpleLevel *level,
const TFrameId ¤tFid)
: TRasterUndo(tileSet, level, currentFid, false, false, 0)
, m_tileSet(0) {}
void setTileSet(TTileSetCM32 *tileSet) { m_tileSet = tileSet; }
void redo() const override {
TToonzImageP image = getImage();
if (!image) return;
ToonzImageUtils::paste(image, m_tileSet);
ToolUtils::updateSaveBox(m_level, m_frameId);
TTool::Application *app = TTool::getApplication();
if (app) {
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
}
int getSize() const override {
return sizeof(*this) + TRasterUndo::getSize() + m_tileSet->getMemorySize();
}
};
//=============================================================================
// RasterRectAutoFillUndo
//-----------------------------------------------------------------------------
class VectorAutoFillUndo final : public TToolUndo {
std::vector<TFilledRegionInf> *m_regionFillInformation;
TRectD m_selectionArea;
TStroke *m_selectingStroke;
bool m_unpaintedOnly;
TFrameId m_onionFid;
int m_row;
int m_column;
public:
~VectorAutoFillUndo() {
if (m_regionFillInformation) delete m_regionFillInformation;
if (m_selectingStroke) delete m_selectingStroke;
}
VectorAutoFillUndo(std::vector<TFilledRegionInf> *regionFillInformation,
TRectD selectionArea, TStroke *selectingStroke,
bool unpaintedOnly, TXshSimpleLevel *sl,
const TFrameId &fid, const TFrameId &onionFid)
: TToolUndo(sl, fid)
, m_regionFillInformation(regionFillInformation)
, m_selectionArea(selectionArea)
, m_unpaintedOnly(unpaintedOnly)
, m_onionFid(onionFid) {
m_selectingStroke = selectingStroke ? new TStroke(*selectingStroke) : 0;
}
void undo() const override {
TTool::Application *app = TTool::getApplication();
if (!app) return;
TVectorImageP img = m_level->getFrame(m_frameId, true);
;
assert(!!img);
if (!img) return;
if (m_regionFillInformation) {
for (UINT i = 0; i < m_regionFillInformation->size(); i++) {
TRegion *reg = img->getRegion((*m_regionFillInformation)[i].m_regionId);
if (reg) reg->setStyle((*m_regionFillInformation)[i].m_styleId);
}
}
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
void redo() const override {
TTool::Application *app = TTool::getApplication();
if (!app) return;
TVectorImageP img = m_level->getFrame(m_frameId, true);
assert(img);
if (!img) return;
TVectorImageP onionImg = m_level->getFrame(m_onionFid, false);
if (!onionImg) return;
if (m_selectingStroke) {
stroke_autofill_learn(onionImg, m_selectingStroke);
stroke_autofill_apply(img, m_selectingStroke, m_unpaintedOnly);
} else {
rect_autofill_learn(onionImg, m_selectionArea);
rect_autofill_apply(img, m_selectionArea, m_unpaintedOnly);
}
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
int getSize() const override {
int size =
m_selectingStroke
? m_selectingStroke->getControlPointCount() * sizeof(TThickPoint) +
100
: 0;
return sizeof(*this) +
m_regionFillInformation->capacity() *
sizeof(m_regionFillInformation) +
500 + size;
}
};
//-----------------------------------------------------------------------------
void doRectAutofill(const TImageP &img, const TRectD selectingRect,
bool onlyUnfilled, const OnionSkinMask &osMask,
TXshSimpleLevel *sl, const TFrameId ¤tFid) {
TToonzImageP ti(img);
TVectorImageP vi(img);
if (!img || !sl) return;
std::vector<int> rows;
osMask.getAll(sl->guessIndex(currentFid), rows);
if (rows.empty()) return;
TFrameId onionFid;
int i;
for (i = 0; i < (int)rows.size(); i++) {
const TFrameId &app = sl->index2fid(rows[i]);
if (app > currentFid) break;
onionFid = app;
}
if (onionFid.isEmptyFrame()) onionFid = sl->index2fid(rows[0]);
if (onionFid.isEmptyFrame() || onionFid == currentFid || !sl->isFid(onionFid))
return;
if (ti) {
TRect rect = ToonzImageUtils::convertWorldToRaster(selectingRect, ti);
TToonzImageP onionImg(sl->getFrame(onionFid, false));
if (!onionImg) return;
TRect workRect = rect * ti->getRaster()->getBounds();
if (workRect.isEmpty()) return;
rect_autofill_learn(onionImg, workRect.x0, workRect.y0, workRect.x1,
workRect.y1);
TTileSetCM32 *tileSet = new TTileSetCM32(ti->getRaster()->getSize());
bool recomputeBBox =
rect_autofill_apply(ti, workRect.x0, workRect.y0, workRect.x1,
workRect.y1, onlyUnfilled, tileSet);
if (recomputeBBox) ToolUtils::updateSaveBox();
if (tileSet->getTileCount() > 0)
TUndoManager::manager()->add(new RasterRectAutoFillUndo(
tileSet, workRect, sl, onlyUnfilled, currentFid, onionFid));
} else if (vi) {
TVectorImageP onionImg(sl->getFrame(onionFid, false));
if (!onionImg) return;
std::vector<TFilledRegionInf> *regionFillInformation =
new std::vector<TFilledRegionInf>;
ImageUtils::getFillingInformationInArea(vi, *regionFillInformation,
selectingRect);
onionImg->findRegions();
vi->findRegions();
rect_autofill_learn(onionImg, selectingRect);
bool hasFilled = rect_autofill_apply(vi, selectingRect, onlyUnfilled);
if (hasFilled)
TUndoManager::manager()->add(
new VectorAutoFillUndo(regionFillInformation, selectingRect, 0,
onlyUnfilled, sl, currentFid, onionFid));
}
}
//-----------------------------------------------------------------------------
void doStrokeAutofill(const TImageP &img, TStroke *selectingStroke,
bool onlyUnfilled, const OnionSkinMask &osMask,
TXshSimpleLevel *sl, const TFrameId ¤tFid) {
TToonzImageP ti(img);
TVectorImageP vi(img);
if (!img || !sl) return;
std::vector<int> rows;
osMask.getAll(sl->guessIndex(currentFid), rows);
if (rows.empty()) return;
TFrameId onionFid;
int i;
for (i = 0; i < (int)rows.size(); i++) {
const TFrameId &app = sl->index2fid(rows[i]);
if (app > currentFid) break;
onionFid = app;
}
if (onionFid.isEmptyFrame()) onionFid = sl->index2fid(rows[0]);
if (onionFid.isEmptyFrame() || onionFid == currentFid || !sl->isFid(onionFid))
return;
if (ti) {
TToonzImageP onionImg(sl->getFrame(onionFid, false));
if (!onionImg) return;
TRasterCM32P ras = onionImg->getRaster();
TPointD center = ras->getCenterD();
TPoint pos;
TRaster32P image =
convertStrokeToImage(selectingStroke, ras->getBounds(), pos);
TRect bbox = (image->getBounds() + pos).enlarge(2);
pos = bbox.getP00();
TRasterCM32P onionAppRas = ras->extract(bbox)->clone();
TRasterCM32P tiAppRas = ti->getRaster()->extract(bbox)->clone();
TRect workRect = onionAppRas->getBounds().enlarge(-1);
TToonzImageP onionApp(onionAppRas, workRect);
TToonzImageP tiApp(tiAppRas, workRect);
ToonzImageUtils::eraseImage(onionApp, image, TPoint(2, 2), true, true, true,
false, 1);
ToonzImageUtils::eraseImage(tiApp, image, TPoint(2, 2), true, true, true,
false, 1);
rect_autofill_learn(onionApp, workRect.x0, workRect.y0, workRect.x1,
workRect.y1);
TTileSetCM32 *tileSet = new TTileSetCM32(ti->getRaster()->getSize());
bool recomputeBBox =
rect_autofill_apply(tiApp, workRect.x0, workRect.y0, workRect.x1,
workRect.y1, onlyUnfilled, tileSet);
delete tileSet;
tileSet = new TTileSetCM32(ti->getRaster()->getSize());
tileSet->add(ti->getRaster(), bbox);
RasterStrokeAutoFillUndo *undo =
new RasterStrokeAutoFillUndo(tileSet, sl, currentFid);
TRop::over(ti->getRaster(), tiAppRas, pos);
TTileSetCM32 *newTileSet = new TTileSetCM32(ti->getRaster()->getSize());
newTileSet->add(ti->getRaster(), bbox);
undo->setTileSet(newTileSet);
TUndoManager::manager()->add(undo);
} else if (vi) {
TVectorImageP onionImg(sl->getFrame(onionFid, false));
if (!onionImg) return;
std::vector<TFilledRegionInf> *regionFillInformation =
new std::vector<TFilledRegionInf>;
ImageUtils::getFillingInformationInArea(vi, *regionFillInformation,
selectingStroke->getBBox());
onionImg->findRegions();
vi->findRegions();
stroke_autofill_learn(onionImg, selectingStroke);
bool hasFilled = stroke_autofill_apply(vi, selectingStroke, onlyUnfilled);
if (hasFilled)
TUndoManager::manager()->add(new VectorAutoFillUndo(
regionFillInformation, TRectD(), selectingStroke, onlyUnfilled, sl,
currentFid, onionFid));
}
}
//=============================================================================
// fillRectWithUndo
//-----------------------------------------------------------------------------
bool inline hasAutoInks(const TPalette *plt) {
for (int i = 0; i < plt->getStyleCount(); i++)
if (plt->getStyle(i)->getFlags() != 0) return true;
return false;
}
//-----------------------------------------------------------------------------
void fillAreaWithUndo(const TImageP &img, const TRectD &area, TStroke *stroke,
bool onlyUnfilled, std::wstring colorType,
TXshSimpleLevel *sl, const TFrameId &fid, int cs,
bool autopaintLines, bool fillGaps, bool closeGaps,
int closeStyleIndex, bool fillOnlySavebox) {
TRectD selArea = stroke ? stroke->getBBox() : area;
if (TToonzImageP ti = img) {
// allargo di 1 la savebox, perche cosi' il rectfill di tutta l'immagine fa
// una sola fillata
TRect enlargedSavebox =
fillOnlySavebox
? ti->getSavebox().enlarge(1) * TRect(TPoint(0, 0), ti->getSize())
: TRect(TPoint(0, 0), ti->getSize());
TRect rasterFillArea =
ToonzImageUtils::convertWorldToRaster(selArea, ti) * enlargedSavebox;
if (rasterFillArea.isEmpty()) return;
TRasterCM32P ras = ti->getRaster();
/*-- tileSetでFill範囲のRectをUndoに格納しておく --*/
TTileSetCM32 *tileSet = new TTileSetCM32(ras->getSize());
tileSet->add(ras, rasterFillArea);
TRasterCM32P tempRaster;
int styleIndex = 4094;
if (fillGaps) {
TToonzImageP tempTi = ti->clone();
tempRaster = tempTi->getRaster();
applyAutoclose(tempTi, AutocloseDistance, AutocloseAngle,
AutocloseOpacity, 4094, convert(rasterFillArea), stroke);
} else {
tempRaster = ras;
}
AreaFiller filler(tempRaster);
if (!stroke) {
bool ret = filler.rectFill(rasterFillArea, cs, onlyUnfilled,
colorType != LINES, colorType != AREAS);
if (!ret) {
delete tileSet;
return;
}
} else
filler.strokeFill(stroke, cs, onlyUnfilled, colorType != LINES,
colorType != AREAS, rasterFillArea);
if (fillGaps) {
TPixelCM32 *tempPix = tempRaster->pixels();
TPixelCM32 *keepPix = ras->pixels();
for (int tempY = 0; tempY < tempRaster->getLy(); tempY++) {
for (int tempX = 0; tempX < tempRaster->getLx();
tempX++, tempPix++, keepPix++) {
keepPix->setPaint(tempPix->getPaint());
if (tempPix->getInk() != styleIndex) {
if (colorType == AREAS && closeGaps && tempPix->getInk() == 4095) {
keepPix->setInk(closeStyleIndex);
keepPix->setTone(tempPix->getTone());
} else if (colorType != AREAS && tempPix->getInk() == 4095) {
keepPix->setInk(cs);
keepPix->setTone(tempPix->getTone());
} else if (tempPix->getInk() != 4095) {
keepPix->setInk(tempPix->getInk());
}
}
}
}
}
TPalette *plt = ti->getPalette();
// !autopaintLines will temporary disable autopaint line feature
if ((plt && !hasAutoInks(plt)) || !autopaintLines) plt = 0;
if (plt) {
TRect rect = rasterFillArea;
TRect bounds = ras->getBounds();
if (bounds.overlaps(rect)) {
rect *= bounds;
const TTileSetCM32::Tile *tile =
tileSet->getTile(tileSet->getTileCount() - 1);
TRasterCM32P rbefore;
tile->getRaster(rbefore);
fillautoInks(ras, rect, rbefore, plt);
}
}
ToolUtils::updateSaveBox(sl, fid);
TUndoManager::manager()->add(new RasterRectFillUndo(
tileSet, stroke, rasterFillArea, cs, sl, colorType, onlyUnfilled, fid,
plt, fillGaps, closeGaps, closeStyleIndex, AutocloseDistance));
} else if (TVectorImageP vi = img) {
TPalette *palette = vi->getPalette();
assert(palette);
const TColorStyle *style = palette->getStyle(cs);
// if( !style->isRegionStyle() )
// return;
vi->findRegions();
std::vector<TFilledRegionInf> *regionFillInformation = 0;
std::vector<std::pair<int, int>> *strokeFillInformation = 0;
if (colorType != LINES) {
regionFillInformation = new std::vector<TFilledRegionInf>;
ImageUtils::getFillingInformationInArea(vi, *regionFillInformation,
selArea);
}
if (colorType != AREAS) {
strokeFillInformation = new std::vector<std::pair<int, int>>;
ImageUtils::getStrokeStyleInformationInArea(vi, *strokeFillInformation,
selArea);
}
VectorRectFillUndo *fUndo =
new VectorRectFillUndo(regionFillInformation, strokeFillInformation,
selArea, stroke, cs, onlyUnfilled, sl, fid);
QMutexLocker lock(vi->getMutex());
if (vi->selectFill(area, stroke, cs, onlyUnfilled, colorType != LINES,
colorType != AREAS))
TUndoManager::manager()->add(fUndo);
else
delete fUndo;
}
}
//=============================================================================
// doFill
//-----------------------------------------------------------------------------
void doFill(const TImageP &img, const TPointD &pos, FillParameters ¶ms,
bool isShiftFill, TXshSimpleLevel *sl, const TFrameId &fid,
bool autopaintLines, bool fillGaps = false, bool closeGaps = false,
int closeStyleIndex = -1) {
TTool::Application *app = TTool::getApplication();
if (!app) return;
if (TToonzImageP ti = TToonzImageP(img)) {
TPoint offs(0, 0);
TRasterCM32P ras = ti->getRaster();
TRectD bbox = ti->getBBox();
if (params.m_fillOnlySavebox) {
TRect ibbox = convert(bbox);
offs = ibbox.getP00();
ras = ti->getRaster()->extract(ibbox);
}
bool recomputeSavebox = false;
TPalette *plt = ti->getPalette();
if (!ras.getPointer() || ras->isEmpty()) return;
ras->lock();
TTileSetCM32 *tileSet = new TTileSetCM32(ras->getSize());
TTileSaverCM32 tileSaver(ras, tileSet);
TDimension imageSize = ti->getSize();
TPointD p(imageSize.lx % 2 ? 0.0 : 0.5, imageSize.ly % 2 ? 0.0 : 0.5);
TPointD tmp_p = pos - p;
params.m_p = TPoint((int)floor(tmp_p.x + 0.5), (int)floor(tmp_p.y + 0.5));
params.m_p += ti->getRaster()->getCenter();
params.m_p -= offs;
params.m_shiftFill = isShiftFill;
TRect rasRect(ras->getSize());
if (!rasRect.contains(params.m_p)) {
ras->unlock();
return;
}
// !autoPaintLines will temporary disable autopaint line feature
if (plt && hasAutoInks(plt) && autopaintLines) params.m_palette = plt;
if (params.m_fillType == ALL || params.m_fillType == AREAS) {
if (isShiftFill) {
FillParameters aux(params);
aux.m_styleId = (params.m_styleId == 0) ? 1 : 0;
recomputeSavebox =
fill(ras, aux, &tileSaver, fillGaps, closeGaps, closeStyleIndex);
}
recomputeSavebox =
fill(ras, params, &tileSaver, fillGaps, closeGaps, closeStyleIndex);
}
if (params.m_fillType == ALL || params.m_fillType == LINES) {
if (params.m_segment)
inkSegment(ras, params.m_p, params.m_styleId, 2.51, true, &tileSaver);
else if (!params.m_segment)
inkFill(ras, params.m_p, params.m_styleId, 2, &tileSaver);
}
if (tileSaver.getTileSet()->getTileCount() != 0) {
static int count = 0;
TSystem::outputDebug("FILL" + std::to_string(count++) + "\n");
if (offs != TPoint())
for (int i = 0; i < tileSet->getTileCount(); i++) {
TTileSet::Tile *t = tileSet->editTile(i);
t->m_rasterBounds = t->m_rasterBounds + offs;
}
TUndoManager::manager()->add(new RasterFillUndo(
tileSet, params, sl, fid, params.m_fillOnlySavebox, fillGaps,
closeGaps, closeStyleIndex, AutocloseDistance, bbox));
}
// instead of updateFrame :
TXshLevel *xl = app->getCurrentLevel()->getLevel();
if (!xl) return;
TXshSimpleLevel *sl = xl->getSimpleLevel();
sl->getProperties()->setDirtyFlag(true);
if (recomputeSavebox &&
Preferences::instance()->isMinimizeSaveboxAfterEditing())
ToolUtils::updateSaveBox(sl, fid);
ras->unlock();
} else if (TVectorImageP vi = TImageP(img)) {
int oldStyleId;
QMutexLocker lock(vi->getMutex());
/*if(params.m_fillType==ALL || params.m_fillType==AREAS)
vi->computeRegion(pos, params.m_styleId);*/
if ((oldStyleId = vectorFill(vi, params.m_fillType, pos, params.m_styleId,
params.m_emptyOnly)) != -1)
TUndoManager::manager()->add(new VectorFillUndo(
params.m_styleId, oldStyleId, params.m_fillType, pos, sl, fid));
}
TTool *t = app->getCurrentTool()->getTool();
if (t) t->notifyImageChanged();
}
//=============================================================================
// SequencePainter
// da spostare in toolutils?
//-----------------------------------------------------------------------------
class SequencePainter {
public:
virtual void process(TImageP img /*, TImageLocation &imgloc*/, double t,
TXshSimpleLevel *sl, const TFrameId &fid) = 0;
void processSequence(TXshSimpleLevel *sl, TFrameId firstFid,
TFrameId lastFid);
virtual ~SequencePainter() {}
};
//-----------------------------------------------------------------------------
void SequencePainter::processSequence(TXshSimpleLevel *sl, TFrameId firstFid,
TFrameId lastFid) {
if (!sl) return;
bool backward = false;
if (firstFid > lastFid) {
std::swap(firstFid, lastFid);
backward = true;
}
assert(firstFid <= lastFid);
std::vector<TFrameId> allFids;
sl->getFids(allFids);
std::vector<TFrameId>::iterator i0 = allFids.begin();
while (i0 != allFids.end() && *i0 < firstFid) i0++;
if (i0 == allFids.end()) return;
std::vector<TFrameId>::iterator i1 = i0;
while (i1 != allFids.end() && *i1 <= lastFid) i1++;
assert(i0 < i1);
std::vector<TFrameId> fids(i0, i1);
int m = fids.size();
assert(m > 0);
TUndoManager::manager()->beginBlock();
for (int i = 0; i < m; ++i) {
TFrameId fid = fids[i];
assert(firstFid <= fid && fid <= lastFid);
TImageP img = sl->getFrame(fid, true);
double t = m > 1 ? (double)i / (double)(m - 1) : 0.5;
process(img, backward ? 1 - t : t, sl, fid);
// Setto il fid come corrente per notificare il cambiamento dell'immagine
TTool::Application *app = TTool::getApplication();
if (app) {
if (app->getCurrentFrame()->isEditingScene())
app->getCurrentFrame()->setFrame(fid.getNumber());
else
app->getCurrentFrame()->setFid(fid);
TTool *tool = app->getCurrentTool()->getTool();
if (tool) tool->notifyImageChanged(fid);
}
}
TUndoManager::manager()->endBlock();
}
//=============================================================================
// MultiAreaFiller : SequencePainter
//-----------------------------------------------------------------------------
class MultiAreaFiller final : public SequencePainter {
TRectD m_firstRect, m_lastRect;
bool m_unfilledOnly;
std::wstring m_colorType;
TVectorImageP m_firstImage, m_lastImage;
int m_styleIndex;
bool m_autopaintLines;
bool m_fillGaps, m_closeGaps;
int m_closeStyleIndex;
bool m_fillOnlySavebox;
public:
MultiAreaFiller(const TRectD &firstRect, const TRectD &lastRect,
bool unfilledOnly, std::wstring colorType, int styleIndex,
bool autopaintLines, bool fillGaps, bool closeGaps,
int closeStyleIndex, bool fillOnlySavebox)
: m_firstRect(firstRect)
, m_lastRect(lastRect)
, m_unfilledOnly(unfilledOnly)
, m_colorType(colorType)
, m_firstImage()
, m_lastImage()
, m_styleIndex(styleIndex)
, m_fillGaps(fillGaps)
, m_closeGaps(closeGaps)
, m_closeStyleIndex(closeStyleIndex)
, m_autopaintLines(autopaintLines)
, m_fillOnlySavebox(fillOnlySavebox) {}
~MultiAreaFiller() {
if (m_firstImage) {
m_firstImage->removeStroke(0);
m_lastImage->removeStroke(0);
}
}
MultiAreaFiller(TStroke *&firstStroke, TStroke *&lastStroke,
bool unfilledOnly, std::wstring colorType, int styleIndex,
bool autopaintLines, bool fillGaps, bool closeGaps,
int closeStyleIndex, bool fillOnlySavebox)
: m_firstRect()
, m_lastRect()
, m_unfilledOnly(unfilledOnly)
, m_colorType(colorType)
, m_styleIndex(styleIndex)
, m_fillGaps(fillGaps)
, m_closeGaps(closeGaps)
, m_closeStyleIndex(closeStyleIndex)
, m_autopaintLines(autopaintLines)
, m_fillOnlySavebox(fillOnlySavebox) {
m_firstImage = new TVectorImage();
m_lastImage = new TVectorImage();
m_firstImage->addStroke(firstStroke);
m_lastImage->addStroke(lastStroke);
}
void process(TImageP img, double t, TXshSimpleLevel *sl,
const TFrameId &fid) override {
if (!m_firstImage) {
TPointD p0 = m_firstRect.getP00() * (1 - t) + m_lastRect.getP00() * t;
TPointD p1 = m_firstRect.getP11() * (1 - t) + m_lastRect.getP11() * t;
TRectD rect(p0.x, p0.y, p1.x, p1.y);
fillAreaWithUndo(img, rect, 0, m_unfilledOnly, m_colorType, sl, fid,
m_styleIndex, m_autopaintLines, m_fillGaps, m_closeGaps,
m_closeStyleIndex, m_fillOnlySavebox);
} else {
if (t == 0)
fillAreaWithUndo(img, TRectD(), m_firstImage->getStroke(0),
m_unfilledOnly, m_colorType, sl, fid, m_styleIndex,
m_autopaintLines, m_fillGaps, m_closeGaps,
m_closeStyleIndex, m_fillOnlySavebox);
else if (t == 1)
fillAreaWithUndo(img, TRectD(), m_lastImage->getStroke(0),
m_unfilledOnly, m_colorType, sl, fid, m_styleIndex,
m_autopaintLines, m_fillGaps, m_closeGaps,
m_closeStyleIndex, m_fillOnlySavebox);
else
// if(t>1)
{
assert(t > 0 && t < 1);
assert(m_firstImage->getStrokeCount() == 1);
assert(m_lastImage->getStrokeCount() == 1);
TVectorImageP vi = TInbetween(m_firstImage, m_lastImage).tween(t);
assert(vi->getStrokeCount() == 1);
fillAreaWithUndo(img, TRectD(), vi->getStroke(0) /*, imgloc*/,
m_unfilledOnly, m_colorType, sl, fid, m_styleIndex,
m_autopaintLines, m_fillGaps, m_closeGaps,
m_closeStyleIndex, m_fillOnlySavebox);
}
}
}
};
//=============================================================================
// MultiFiller : SequencePainter
//-----------------------------------------------------------------------------
class MultiFiller final : public SequencePainter {
TPointD m_firstPoint, m_lastPoint;
FillParameters m_params;
bool m_autopaintLines;
bool m_fillGaps, m_closeGaps;
int m_closeStyleIndex;
public:
MultiFiller(const TPointD &firstPoint, const TPointD &lastPoint,
const FillParameters ¶ms, bool autopaintLines, bool fillGaps,
bool closeGaps, int closeStyleIndex)
: m_firstPoint(firstPoint)
, m_lastPoint(lastPoint)
, m_params(params)
, m_autopaintLines(autopaintLines)
, m_fillGaps(fillGaps)
, m_closeStyleIndex(closeStyleIndex)
, m_closeGaps(closeGaps) {}
void process(TImageP img, double t, TXshSimpleLevel *sl,
const TFrameId &fid) override {
TPointD p = m_firstPoint * (1 - t) + m_lastPoint * t;
doFill(img, p, m_params, false, sl, fid, m_autopaintLines, m_fillGaps,
m_closeGaps, m_closeStyleIndex);
}
};
//=============================================================================
/*
if(e.isShiftPressed())
{
m_firstPoint = pos;
m_firstFrameId =
TApplication::instance()->getCurrentFrameId();
}
else
{
m_firstClick = false;
TApplication::instance()->setCurrentFrame(m_veryFirstFrameId);
}
TNotifier::instance()->notify(TLevelChange());
TNotifier::instance()->notify(TStageChange());
}
}
*/
//=============================================================================
// AreaFillTool
//-----------------------------------------------------------------------------
void drawPolyline(const std::vector<TPointD> &points) {
if (points.empty()) return;
tglDrawCircle(points[0], 2);
for (UINT i = 0; i < points.size() - 1; i++)
tglDrawSegment(points[i], points[i + 1]);
}
//-----------------------------------------------------------------------------
AreaFillTool::AreaFillTool(TTool *parent)
: m_frameRange(false)
, m_onlyUnfilled(false)
, m_selecting(false)
, m_selectingRect(TRectD())
, m_firstRect(TRectD())
, m_firstFrameSelected(false)
, m_level(0)
, m_parent(parent)
, m_colorType(AREAS)
, m_currCell(-1, -1)
, m_type(RECT)
, m_isPath(false)
, m_enabled(false)
, m_active(false)
, m_firstStroke(0)
, m_thick(0.5)
, m_mousePosition()
, m_onion(false)
, m_isLeftButtonPressed(false)
, m_autopaintLines(true)
, m_fillOnlySavebox(false) {}
void AreaFillTool::draw() {
m_thick = m_parent->getPixelSize() / 2.0;
TPixel color = TPixel32::Red;
if (m_type == RECT) {
if (m_frameRange && m_firstFrameSelected)
drawRect(m_firstRect, color, 0x3F33, true);
if (m_selecting || (m_frameRange && !m_firstFrameSelected))
drawRect(m_selectingRect, color, 0xFFFF, true);
} else if ((m_type == FREEHAND || m_type == POLYLINE) && m_frameRange) {
tglColor(color);
if (m_firstStroke) drawStrokeCenterline(*m_firstStroke, 1);
}
if (m_type == POLYLINE && !m_polyline.empty()) {
glPushMatrix();
tglColor(TPixel::Red);
tglDrawCircle(m_polyline[0], 2);
glBegin(GL_LINE_STRIP);
for (UINT i = 0; i < m_polyline.size(); i++) tglVertex(m_polyline[i]);
tglVertex(m_mousePosition);
glEnd();
glPopMatrix();
} else if (m_type == FREEHAND && !m_track.isEmpty()) {
tglColor(TPixel::Red);
glPushMatrix();
m_track.drawAllFragments();
glPopMatrix();
}
}
void AreaFillTool::resetMulti() {
m_firstFrameSelected = false;
m_firstRect.empty();
m_selectingRect.empty();
TTool::Application *app = TTool::getApplication();
TXshLevel *xl = app->getCurrentLevel()->getLevel();
m_level = xl ? xl->getSimpleLevel() : 0;
m_firstFrameId = m_veryFirstFrameId = m_parent->getCurrentFid();
if (m_firstStroke) {
delete m_firstStroke;
m_firstStroke = 0;
}
}
void AreaFillTool::leftButtonDown(const TPointD &pos, const TMouseEvent &,
TImage *img) {
TVectorImageP vi = TImageP(img);
TToonzImageP ti = TToonzImageP(img);
if (!vi && !ti) {
m_selecting = false;
return;
}
m_selecting = true;
if (m_type == RECT) {
m_selectingRect.x0 = pos.x;
m_selectingRect.y0 = pos.y;
m_selectingRect.x1 = pos.x + 1;
m_selectingRect.y1 = pos.y + 1;
} else if (m_type == FREEHAND || m_type == POLYLINE) {
int col = TTool::getApplication()->getCurrentColumn()->getColumnIndex();
m_isPath = TTool::getApplication()
->getCurrentObject()
->isSpline(); // getApplication()->isEditingSpline();
m_enabled = col >= 0 || m_isPath;
if (!m_enabled) return;
m_active = true;
m_track.clear();
m_firstPos = pos;
double pixelSize2 = m_parent->getPixelSize() * m_parent->getPixelSize();
m_track.add(TThickPoint(pos, m_thick), pixelSize2);
if (m_type == POLYLINE) {
if (m_polyline.empty() || m_polyline.back() != pos)
m_polyline.push_back(pos);
m_mousePosition = pos;
} else
m_track.add(TThickPoint(pos, m_thick), pixelSize2);
if (m_type == POLYLINE) {
if (m_polyline.empty() || m_polyline.back() != pos)
m_polyline.push_back(pos);
}
}
m_isLeftButtonPressed = true;
}
/*-- PolyLineFillを閉じる時に呼ばれる --*/
void AreaFillTool::leftButtonDoubleClick(const TPointD &pos,
const TMouseEvent &e, bool fillGaps,
bool closeGaps, int closeStyleIndex) {
TStroke *stroke;
TTool::Application *app = TTool::getApplication();
if (!app) return;
if (m_polyline.size() <= 1) {
resetMulti();
m_isLeftButtonPressed = false;
return;
}
if (m_polyline.back() != pos) m_polyline.push_back(pos);
if (m_polyline.back() != m_polyline.front())
m_polyline.push_back(m_polyline.front());
std::vector<TThickPoint> strokePoints;
for (UINT i = 0; i < m_polyline.size() - 1; i++) {
strokePoints.push_back(TThickPoint(m_polyline[i], 1));
strokePoints.push_back(
TThickPoint(0.5 * (m_polyline[i] + m_polyline[i + 1]), 1));
}
strokePoints.push_back(TThickPoint(m_polyline.back(), 1));
m_polyline.clear();
stroke = new TStroke(strokePoints);
assert(stroke->getPoint(0) == stroke->getPoint(1));
// if (m_type==POLYLINE)
// m_polyline.push_back(pos);
// drawPolyline(m_polyline);
int styleIndex = app->getCurrentLevelStyleIndex();
if (m_frameRange) // stroke multi
{
if (m_firstFrameSelected) {
MultiAreaFiller filler(m_firstStroke, stroke, m_onlyUnfilled, m_colorType,
styleIndex, m_autopaintLines, fillGaps, closeGaps,
closeStyleIndex, m_fillOnlySavebox);
filler.processSequence(m_level.getPointer(), m_firstFrameId,
m_parent->getCurrentFid());
m_parent->invalidate(m_selectingRect.enlarge(2));
if (e.isShiftPressed()) {
m_firstStroke = stroke;
m_firstFrameId = m_parent->getCurrentFid();
} else {
if (app->getCurrentFrame()->isEditingScene()) {
app->getCurrentColumn()->setColumnIndex(m_currCell.first);
app->getCurrentFrame()->setFrame(m_currCell.second);
} else
app->getCurrentFrame()->setFid(m_veryFirstFrameId);
resetMulti();
}
} else // primo frame
{
m_firstStroke = stroke;
// if (app->getCurrentFrame()->isEditingScene())
m_currCell =
std::pair<int, int>(app->getCurrentColumn()->getColumnIndex(),
app->getCurrentFrame()->getFrame());
}
} else {
if (m_onion) {
OnionSkinMask osMask = app->getCurrentOnionSkin()->getOnionSkinMask();
doStrokeAutofill(m_parent->getImage(true), stroke, m_onlyUnfilled, osMask,
m_level.getPointer(), m_parent->getCurrentFid());
} else
fillAreaWithUndo(m_parent->getImage(true), TRectD(), stroke,
m_onlyUnfilled, m_colorType, m_level.getPointer(),
m_parent->getCurrentFid(), styleIndex, m_autopaintLines,
fillGaps, closeGaps, closeStyleIndex, m_fillOnlySavebox);
TTool *t = app->getCurrentTool()->getTool();
if (t) t->notifyImageChanged();
}
}
void AreaFillTool::leftButtonDrag(const TPointD &pos, const TMouseEvent &e) {
if (!m_isLeftButtonPressed) return;
if (m_type == RECT) {
m_selectingRect.x1 = pos.x;
m_selectingRect.y1 = pos.y;
m_parent->invalidate();
} else if (m_type == FREEHAND) {
if (!m_enabled || !m_active) return;
double pixelSize2 = m_parent->getPixelSize() * m_parent->getPixelSize();
m_track.add(TThickPoint(pos, m_thick), pixelSize2);
m_parent->invalidate();
}
}
void AreaFillTool::mouseMove(const TPointD &pos, const TMouseEvent &e) {
if (m_type != POLYLINE || m_polyline.empty()) return;
if (!m_enabled || !m_active) return;
m_mousePosition = pos;
m_parent->invalidate();
}
void AreaFillTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e,
bool fillGaps, bool closeGaps,
int closeStyleIndex) {
if (!m_isLeftButtonPressed) return;
m_isLeftButtonPressed = false;
TTool::Application *app = TTool::getApplication();
if (!app) return;
TXshLevel *xl = app->getCurrentLevel()->getLevel();
m_level = xl ? xl->getSimpleLevel() : 0;
int styleIndex = app->getCurrentLevelStyleIndex();
m_selecting = false;
if (m_type == RECT) {
if (m_selectingRect.x0 > m_selectingRect.x1)
std::swap(m_selectingRect.x0, m_selectingRect.x1);
if (m_selectingRect.y0 > m_selectingRect.y1)
std::swap(m_selectingRect.y0, m_selectingRect.y1);
if (m_frameRange) {
if (m_firstFrameSelected) {
MultiAreaFiller filler(m_firstRect, m_selectingRect, m_onlyUnfilled,
m_colorType, styleIndex, m_autopaintLines,
fillGaps, closeGaps, closeStyleIndex,
m_fillOnlySavebox);
filler.processSequence(m_level.getPointer(), m_firstFrameId,
m_parent->getCurrentFid());
m_parent->invalidate(m_selectingRect.enlarge(2));
if (e.isShiftPressed()) {
m_firstRect = m_selectingRect;
m_firstFrameId = m_parent->getCurrentFid();
} else {
if (app->getCurrentFrame()->isEditingScene()) {
app->getCurrentColumn()->setColumnIndex(m_currCell.first);
app->getCurrentFrame()->setFrame(m_currCell.second);
} else
app->getCurrentFrame()->setFid(m_veryFirstFrameId);
resetMulti();
}
} else {
// if (app->getCurrentFrame()->isEditingScene())
m_currCell =
std::pair<int, int>(app->getCurrentColumn()->getColumnIndex(),
app->getCurrentFrame()->getFrame());
}
} else {
if (m_onion) {
OnionSkinMask osMask = app->getCurrentOnionSkin()->getOnionSkinMask();
doRectAutofill(m_parent->getImage(true), m_selectingRect,
m_onlyUnfilled, osMask, m_level.getPointer(),
m_parent->getCurrentFid());
} else
fillAreaWithUndo(m_parent->getImage(true), m_selectingRect, 0,
m_onlyUnfilled, m_colorType, m_level.getPointer(),
m_parent->getCurrentFid(), styleIndex,
m_autopaintLines, fillGaps, closeGaps, closeStyleIndex,
m_fillOnlySavebox);
m_parent->invalidate();
m_selectingRect.empty();
TTool *t = app->getCurrentTool()->getTool();
if (t) t->notifyImageChanged();
}
} else if (m_type == FREEHAND) {
#if defined(MACOSX)
// m_parent->m_viewer->enableRedraw(true);
#endif
bool isValid = m_enabled && m_active;
m_enabled = m_active = false;
if (!isValid || m_track.isEmpty()) return;
double pixelSize2 = m_parent->getPixelSize() * m_parent->getPixelSize();
m_track.add(TThickPoint(m_firstPos, m_thick), pixelSize2);
m_track.filterPoints();
double error = (m_isPath ? 20.0 : 30.0 / 11) * sqrt(pixelSize2);
TStroke *stroke = m_track.makeStroke(error);
stroke->setStyle(1);
m_track.clear();
if (m_frameRange) // stroke multi
{
if (m_firstFrameSelected) {
MultiAreaFiller filler(m_firstStroke, stroke, m_onlyUnfilled,
m_colorType, styleIndex, m_autopaintLines,
fillGaps, closeGaps, closeStyleIndex,
m_fillOnlySavebox);
filler.processSequence(m_level.getPointer(), m_firstFrameId,
m_parent->getCurrentFid());
m_parent->invalidate(m_selectingRect.enlarge(2));
if (e.isShiftPressed()) {
m_firstStroke = stroke;
m_firstFrameId = m_parent->getCurrentFid();
} else {
if (app->getCurrentFrame()->isEditingScene()) {
app->getCurrentColumn()->setColumnIndex(m_currCell.first);
app->getCurrentFrame()->setFrame(m_currCell.second);
} else
app->getCurrentFrame()->setFid(m_veryFirstFrameId);
resetMulti();
}
} else // primo frame
{
m_firstStroke = stroke;
// if (app->getCurrentFrame()->isEditingScene())
m_currCell =
std::pair<int, int>(app->getCurrentColumn()->getColumnIndex(),
app->getCurrentFrame()->getFrame());
}
} else // stroke non multi
{
if (!m_parent->getImage(true)) return;
if (m_onion) {
OnionSkinMask osMask = app->getCurrentOnionSkin()->getOnionSkinMask();
doStrokeAutofill(m_parent->getImage(true), stroke, m_onlyUnfilled,
osMask, m_level.getPointer(),
m_parent->getCurrentFid());
} else
fillAreaWithUndo(
m_parent->getImage(true), TRectD(), stroke /*, imageLocation*/,
m_onlyUnfilled, m_colorType, m_level.getPointer(),
m_parent->getCurrentFid(), styleIndex, m_autopaintLines, fillGaps,
closeGaps, closeStyleIndex, m_fillOnlySavebox);
delete stroke;
TTool *t = app->getCurrentTool()->getTool();
if (t) t->notifyImageChanged();
m_parent->invalidate();
}
}
}
void AreaFillTool::onImageChanged() {
if (!m_frameRange) return;
TTool::Application *app = TTool::getApplication();
if (!app) return;
TXshLevel *xshl = app->getCurrentLevel()->getLevel();
if (!xshl || m_level.getPointer() != xshl ||
(m_selectingRect.isEmpty() && !m_firstStroke))
resetMulti();
else if (m_firstFrameId == m_parent->getCurrentFid())
m_firstFrameSelected = false; // nel caso sono passato allo stato 1 e
// torno all'immagine iniziale, torno allo
// stato iniziale
else { // cambio stato.
m_firstFrameSelected = true;
if (m_type != FREEHAND && m_type != POLYLINE) {
assert(!m_selectingRect.isEmpty());
m_firstRect = m_selectingRect;
}
}
}
/*--Normal以外のTypeが選択された場合に呼ばれる--*/
bool AreaFillTool::onPropertyChanged(bool multi, bool onlyUnfilled, bool onion,
Type type, std::wstring colorType,
bool autopaintLines,
bool fillOnlySavebox) {
m_frameRange = multi;
m_onlyUnfilled = onlyUnfilled;
m_colorType = colorType;
m_type = type;
m_onion = onion;
m_autopaintLines = autopaintLines;
m_fillOnlySavebox = fillOnlySavebox;
if (m_frameRange) resetMulti();
/*--動作中にプロパティが変わったら、現在の動作を無効にする--*/
if (m_isLeftButtonPressed) m_isLeftButtonPressed = false;
if (m_type == POLYLINE && !m_polyline.empty()) m_polyline.clear();
return true;
}
void AreaFillTool::onActivate() {
// getApplication()->editImage();
if (m_frameRange) resetMulti();
if (TVectorImageP vi = TImageP(m_parent->getImage(false))) vi->findRegions();
}
void AreaFillTool::onEnter() {
// getApplication()->editImage();
}
bool descending(int i, int j) { return (i > j); }
} // namespace
//=============================================================================
/*! NormalLineFillTool
マウスドラッグで直線を延ばし、その直線がまたいだ点をFillLineするツール。
Raster - Normal - Line Fillツール(FrameRangeなし)のとき使用可能にする
*/
class NormalLineFillTool {
TTool *m_parent;
TPointD m_startPosition, m_mousePosition;
bool m_isEditing;
public:
NormalLineFillTool(TTool *parent)
: m_parent(parent), m_isEditing(false), m_mousePosition() {}
/*-- FillLineツールに戻ってきたときに前の位置情報をリセットする --*/
void init() {
m_startPosition = TPointD();
m_mousePosition = TPointD();
m_isEditing = false;
}
void leftButtonDown(const TPointD &pos, const TMouseEvent &e) {
m_startPosition = pos; /*-始点-*/
m_mousePosition = pos; /*-終点-*/
m_isEditing = true;
}
void leftButtonDrag(const TPointD &pos, const TMouseEvent &e) {
if (!m_isEditing) return;
m_mousePosition = pos;
m_parent->invalidate();
}
void leftButtonUp(const TPointD &pos, const TMouseEvent &e, TImage *img,
FillParameters ¶ms) {
if (!m_isEditing) return;
m_mousePosition = pos;
TTool::Application *app = TTool::getApplication();
if (!app) return;
TXshLevel *xl = app->getCurrentLevel()->getLevel();
TXshSimpleLevel *sl = xl ? xl->getSimpleLevel() : 0;
TToonzImageP ti = TImageP(m_parent->getImage(true));
if (!ti) return;
TRasterCM32P ras = ti->getRaster();
if (!ras) return;
int styleId = params.m_styleId;
/*--- Do a do Fill at all points on the line segment ---*/
double dx = m_mousePosition.x - m_startPosition.x;
double dy = m_mousePosition.y - m_startPosition.y;
if (std::abs(dx) >
std::abs(dy)) /*--For horizontally long line segments --*/
{
double k = dy / dx; /*-- Slope of a line --*/
/*--- In round, it does not connect well when the value is negative ---*/
int start = std::min((int)floor(m_startPosition.x + 0.5),
(int)floor(m_mousePosition.x + 0.5));
int end = std::max((int)floor(m_startPosition.x + 0.5),
(int)floor(m_mousePosition.x + 0.5));
double start_x = (m_startPosition.x < m_mousePosition.x)
? m_startPosition.x
: m_mousePosition.x;
double start_y = (m_startPosition.x < m_mousePosition.x)
? m_startPosition.y
: m_mousePosition.y;
for (int x = start; x <= end; x++) {
double ddx = (double)(x - start);
TPointD tmpPos(start_x + ddx, ddx * k + start_y);
TPoint ipos((int)(tmpPos.x + ras->getLx() / 2),
(int)(tmpPos.y + ras->getLy() / 2));
if (!ras->getBounds().contains(ipos)) continue;
TPixelCM32 pix = ras->pixels(ipos.y)[ipos.x];
if (pix.getInk() == styleId || pix.isPurePaint()) continue;
doFill(img, tmpPos, params, e.isShiftPressed(), sl,
m_parent->getCurrentFid(), true);
}
} else /*-- For vertically long line segments --*/
{
double k = dx / dy; /*-- Slope of a line --*/
/*--- In round, it does not connect well when the value is negative ---*/
int start = std::min((int)floor(m_startPosition.y + 0.5),
(int)floor(m_mousePosition.y + 0.5));
int end = std::max((int)floor(m_startPosition.y + 0.5),
(int)floor(m_mousePosition.y + 0.5));
double start_x = (m_startPosition.y < m_mousePosition.y)
? m_startPosition.x
: m_mousePosition.x;
double start_y = (m_startPosition.y < m_mousePosition.y)
? m_startPosition.y
: m_mousePosition.y;
for (int y = start; y <= end; y++) {
double ddy = (double)(y - start);
TPointD tmpPos(ddy * k + start_x, ddy + start_y);
TPoint ipos((int)(tmpPos.x + ras->getLx() / 2),
(int)(tmpPos.y + ras->getLy() / 2));
if (!ras->getBounds().contains(ipos)) continue;
TPixelCM32 pix = ras->pixels(ipos.y)[ipos.x];
if (pix.getInk() == styleId || pix.isPurePaint()) continue;
doFill(img, tmpPos, params, e.isShiftPressed(), sl,
m_parent->getCurrentFid(), true);
}
}
m_isEditing = false;
m_parent->invalidate();
}
void draw() {
if (m_isEditing) {
tglColor(TPixel32::Red);
glBegin(GL_LINE_STRIP);
tglVertex(m_startPosition);
tglVertex(m_mousePosition);
glEnd();
}
}
};
//=============================================================================
//=============================================================================
// Fill Tool
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
FillTool::FillTool(int targetType)
: TTool("T_Fill")
, m_frameRange("Frame Range", false) // W_ToolOptions_FrameRange
, m_fillType("Type:")
, m_selective("Selective", false)
, m_colorType("Mode:")
, m_onion("Onion Skin", false)
, m_fillDepth("Fill Depth", 0, 15, 0, 15)
, m_segment("Segment", false)
, m_onionStyleId(0)
, m_currCell(-1, -1)
, m_maxGapDistance("Maximum Gap", 0.01, 10.0, 1.15)
, m_closeStyleIndex("Style Index:", L"current") // W_ToolOptions_InkIndex
, m_rasterGapDistance("Distance:", 1, 100, 10)
, m_closeRasterGaps("Gaps:")
, m_firstTime(true)
, m_autopaintLines("Autopaint Lines", true)
, m_fillOnlySavebox("Savebox", false) {
m_rectFill = new AreaFillTool(this);
m_normalLineFillTool = new NormalLineFillTool(this);
bind(targetType);
m_prop.bind(m_fillType);
m_fillType.addValue(NORMALFILL);
m_fillType.addValue(RECTFILL);
m_fillType.addValue(FREEHANDFILL);
m_fillType.addValue(POLYLINEFILL);
m_prop.bind(m_colorType);
m_colorType.addValue(LINES);
m_colorType.addValue(AREAS);
m_colorType.addValue(ALL);
m_prop.bind(m_selective);
if (targetType == TTool::ToonzImage) {
m_prop.bind(m_fillDepth);
m_prop.bind(m_segment);
m_prop.bind(m_closeRasterGaps);
m_prop.bind(m_rasterGapDistance);
m_prop.bind(m_closeStyleIndex);
m_closeRasterGaps.setId("CloseGaps");
m_rasterGapDistance.setId("RasterGapDistance");
m_closeStyleIndex.setId("RasterGapInkIndex");
}
m_closeRasterGaps.addValue(IGNOREGAPS);
m_closeRasterGaps.addValue(FILLGAPS);
m_closeRasterGaps.addValue(CLOSEANDFILLGAPS);
m_prop.bind(m_onion);
m_prop.bind(m_frameRange);
if (targetType == TTool::VectorImage) {
m_prop.bind(m_maxGapDistance);
m_maxGapDistance.setId("MaxGapDistance");
}
if (targetType == TTool::ToonzImage) {
m_prop.bind(m_fillOnlySavebox);
m_prop.bind(m_autopaintLines);
}
m_selective.setId("Selective");
m_onion.setId("OnionSkin");
m_frameRange.setId("FrameRange");
m_segment.setId("SegmentInk");
m_fillType.setId("Type");
m_colorType.setId("Mode");
m_autopaintLines.setId("AutopaintLines");
m_fillOnlySavebox.setId("FillOnlySavebox");
}
//-----------------------------------------------------------------------------
int FillTool::getCursorId() const {
int ret;
if (m_colorType.getValue() == LINES)
ret = ToolCursor::FillCursorL;
else {
ret = ToolCursor::FillCursor;
if (m_colorType.getValue() == AREAS) ret = ret | ToolCursor::Ex_Area;
if (!m_autopaintLines.getValue())
ret = ret | ToolCursor::Ex_Fill_NoAutopaint;
}
if (m_fillType.getValue() == FREEHANDFILL)
ret = ret | ToolCursor::Ex_FreeHand;
else if (m_fillType.getValue() == POLYLINEFILL)
ret = ret | ToolCursor::Ex_PolyLine;
else if (m_fillType.getValue() == RECTFILL)
ret = ret | ToolCursor::Ex_Rectangle;
if (ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg)
ret = ret | ToolCursor::Ex_Negate;
return ret;
}
//-----------------------------------------------------------------------------
void FillTool::updateTranslation() {
m_frameRange.setQStringName(tr("Frame Range"));
m_fillType.setQStringName(tr("Type:"));
m_fillType.setItemUIName(NORMALFILL, tr("Normal"));
m_fillType.setItemUIName(RECTFILL, tr("Rectangular"));
m_fillType.setItemUIName(FREEHANDFILL, tr("Freehand"));
m_fillType.setItemUIName(POLYLINEFILL, tr("Polyline"));
m_selective.setQStringName(tr("Selective"));
m_colorType.setQStringName(tr("Mode:"));
m_colorType.setItemUIName(LINES, tr("Lines"));
m_colorType.setItemUIName(AREAS, tr("Areas"));
m_colorType.setItemUIName(ALL, tr("Lines & Areas"));
m_onion.setQStringName(tr("Onion Skin"));
m_fillDepth.setQStringName(tr("Fill Depth"));
m_segment.setQStringName(tr("Segment"));
m_maxGapDistance.setQStringName(tr("Maximum Gap"));
m_autopaintLines.setQStringName(tr("Autopaint Lines"));
m_fillOnlySavebox.setQStringName(tr("Savebox"));
m_rasterGapDistance.setQStringName(tr("Distance:"));
m_closeStyleIndex.setQStringName(tr("Style Index:"));
m_closeRasterGaps.setQStringName(tr("Gaps:"));
m_closeRasterGaps.setItemUIName(IGNOREGAPS, tr("Ingore Gaps"));
m_closeRasterGaps.setItemUIName(FILLGAPS, tr("Fill Gaps"));
m_closeRasterGaps.setItemUIName(CLOSEANDFILLGAPS, tr("Close and Fill"));
}
//-----------------------------------------------------------------------------
FillParameters FillTool::getFillParameters() const {
FillParameters params;
int styleId = TTool::getApplication()->getCurrentLevelStyleIndex();
params.m_styleId = styleId;
/*---紛らわしいことに、colorTypeをfillTypeに名前を変えて保存している。間違いではない。---*/
params.m_fillType = m_colorType.getValue();
params.m_emptyOnly = m_selective.getValue();
params.m_segment = m_segment.getValue();
params.m_minFillDepth = (int)m_fillDepth.getValue().first;
params.m_maxFillDepth = (int)m_fillDepth.getValue().second;
params.m_fillOnlySavebox = m_fillOnlySavebox.getValue();
return params;
}
//-----------------------------------------------------------------------------
void FillTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e) {
TTool::Application *app = TTool::getApplication();
if (!app) return;
int closeStyleIndex = m_closeStyleIndex.getStyleIndex();
if (closeStyleIndex == -1) {
closeStyleIndex = app->getCurrentPalette()->getStyleIndex();
}
m_clickPoint = pos;
if (m_fillType.getValue() != NORMALFILL) {
m_rectFill->leftButtonDown(pos, e, getImage(true));
return;
}
/*--以下、NormalFillの場合--*/
FillParameters params = getFillParameters();
if (m_onion.getValue()) {
m_onionStyleId = pickOnionColor(pos);
if (m_onionStyleId > 0) app->setCurrentLevelStyleIndex(m_onionStyleId);
} else if (m_frameRange.getValue()) {
if (!m_firstClick) {
// PRIMO CLICK
// if (app->getCurrentFrame()->isEditingScene())
m_currCell = std::pair<int, int>(getColumnIndex(), getFrame());
m_firstClick = true;
m_firstPoint = pos;
m_firstFrameId = m_veryFirstFrameId = getCurrentFid();
// gmt. NON BISOGNA DISEGNARE DENTRO LE CALLBACKS!!!!
// drawCross(m_firstPoint, 6);
invalidate();
} else {
// When using tablet on windows, the mouse press event may be called AFTER
// tablet release. It causes unwanted another "first click" just after
// frame-range-filling. Calling processEvents() here to make sure to
// consume the mouse press event in advance.
qApp->processEvents();
// SECONDO CLICK
TFrameId fid = getCurrentFid();
MultiFiller filler(m_firstPoint, pos, params, m_autopaintLines.getValue(),
m_closeRasterGaps.getIndex() > 0,
m_closeRasterGaps.getIndex() > 1, closeStyleIndex);
filler.processSequence(m_level.getPointer(), m_firstFrameId, fid);
if (e.isShiftPressed()) {
m_firstPoint = pos;
m_firstFrameId = getCurrentFid();
} else {
m_firstClick = false;
if (app->getCurrentFrame()->isEditingScene()) {
app->getCurrentColumn()->setColumnIndex(m_currCell.first);
app->getCurrentFrame()->setFrame(m_currCell.second);
} else
app->getCurrentFrame()->setFid(m_veryFirstFrameId);
}
TTool *t = app->getCurrentTool()->getTool();
if (t) t->notifyImageChanged();
}
} else {
if (params.m_fillType == LINES && m_targetType == TTool::ToonzImage)
m_normalLineFillTool->leftButtonDown(pos, e);
else {
TXshLevel *xl = app->getCurrentLevel()->getLevel();
m_level = xl ? xl->getSimpleLevel() : 0;
doFill(getImage(true), pos, params, e.isShiftPressed(),
m_level.getPointer(), getCurrentFid(), m_autopaintLines.getValue(),
m_closeRasterGaps.getIndex() > 0, m_closeRasterGaps.getIndex() > 1,
closeStyleIndex);
invalidate();
}
}
}
//-----------------------------------------------------------------------------
void FillTool::leftButtonDoubleClick(const TPointD &pos, const TMouseEvent &e) {
int closeStyleIndex = m_closeStyleIndex.getStyleIndex();
if (closeStyleIndex == -1) {
closeStyleIndex =
TTool::getApplication()->getCurrentPalette()->getStyleIndex();
}
if (m_fillType.getValue() != NORMALFILL) {
m_rectFill->leftButtonDoubleClick(pos, e, m_closeRasterGaps.getIndex() > 0,
m_closeRasterGaps.getIndex() > 1,
closeStyleIndex);
return;
}
}
//-----------------------------------------------------------------------------
void FillTool::leftButtonDrag(const TPointD &pos, const TMouseEvent &e) {
if ((m_fillType.getValue() != NORMALFILL && !m_onion.getValue()) ||
(m_colorType.getValue() == AREAS && m_onion.getValue()))
m_rectFill->leftButtonDrag(pos, e);
else if (!m_onion.getValue() && !m_frameRange.getValue()) {
FillParameters params = getFillParameters();
if (params.m_fillType == LINES && m_targetType == TTool::ToonzImage) {
m_normalLineFillTool->leftButtonDrag(pos, e);
return;
}
if (m_clickPoint == pos) return;
TImageP img = getImage(true);
int styleId = params.m_styleId;
if (TVectorImageP vi = img) {
TRegion *r = vi->getRegion(pos);
if (r && r->getStyle() == styleId) return;
} else if (TToonzImageP ti = img) {
TRasterCM32P ras = ti->getRaster();
if (!ras) return;
TPointD center = ras->getCenterD();
TPoint ipos = convert(pos + center);
if (!ras->getBounds().contains(ipos)) return;
TPixelCM32 pix = ras->pixels(ipos.y)[ipos.x];
if (pix.getPaint() == styleId) {
invalidate();
return;
}
TSystem::outputDebug("ok. pix=" + std::to_string(pix.getTone()) + "," +
std::to_string(pix.getPaint()) + "\n");
} else
return;
int closeStyleIndex = m_closeStyleIndex.getStyleIndex();
if (closeStyleIndex == -1) {
closeStyleIndex =
TTool::getApplication()->getCurrentPalette()->getStyleIndex();
}
doFill(img, pos, params, e.isShiftPressed(), m_level.getPointer(),
getCurrentFid(), m_autopaintLines.getValue(),
m_closeRasterGaps.getIndex() > 0, m_closeRasterGaps.getIndex() > 1,
closeStyleIndex);
invalidate();
}
}
//-----------------------------------------------------------------------------
void FillTool::leftButtonUp(const TPointD &pos, const TMouseEvent &e) {
int closeStyleIndex = m_closeStyleIndex.getStyleIndex();
if (closeStyleIndex == -1) {
closeStyleIndex =
TTool::getApplication()->getCurrentPalette()->getStyleIndex();
}
if (m_onion.getValue()) {
if (m_fillType.getValue() != NORMALFILL && m_colorType.getValue() == AREAS)
m_rectFill->leftButtonUp(pos, e, m_closeRasterGaps.getIndex() > 0,
m_closeRasterGaps.getIndex() > 1,
closeStyleIndex);
else if (m_onionStyleId > 0) {
FillParameters tmp = getFillParameters();
doFill(getImage(true), pos, tmp, e.isShiftPressed(), m_level.getPointer(),
getCurrentFid(), m_autopaintLines.getValue(),
m_closeRasterGaps.getIndex() > 0, m_closeRasterGaps.getIndex() > 1,
closeStyleIndex);
invalidate();
}
} else if (m_fillType.getValue() != NORMALFILL) {
m_rectFill->leftButtonUp(pos, e, m_closeRasterGaps.getIndex() > 0,
m_closeRasterGaps.getIndex() > 1, closeStyleIndex);
return;
}
if (!m_frameRange.getValue()) {
TFrameId fid = getCurrentFid();
// notifyImageChanged();
if (getFillParameters().m_fillType == LINES &&
m_targetType == TTool::ToonzImage) {
FillParameters params = getFillParameters();
m_normalLineFillTool->leftButtonUp(pos, e, getImage(true), params);
return;
}
}
}
//-----------------------------------------------------------------------------
void FillTool::resetMulti() {
m_firstClick = false;
m_firstFrameId = -1;
m_firstPoint = TPointD();
TXshLevel *xl = TTool::getApplication()->getCurrentLevel()->getLevel();
m_level = xl ? xl->getSimpleLevel() : 0;
}
//-----------------------------------------------------------------------------
bool FillTool::onPropertyChanged(std::string propertyName) {
/*--- m_rectFill->onPropertyChangedを呼ぶかどうかのフラグ
fillType, frameRange, selective,
colorTypeが変わったときに呼ぶ---*/
bool rectPropChangedflag = false;
// Areas, Lines etc.
if (propertyName == m_colorType.getName()) {
FillColorType = ::to_string(m_colorType.getValue());
rectPropChangedflag = true;
/*--- ColorModelのCursor更新のためにSIGNALを出す ---*/
TTool::getApplication()->getCurrentTool()->notifyToolChanged();
/*--- FillLineツールに戻ってきたときに前回の位置情報をリセットする ---*/
if (FillColorType.getValue() == "Lines") m_normalLineFillTool->init();
}
// Rect, Polyline etc.
else if (propertyName == m_fillType.getName()) {
if (m_fillType.getValue() != NORMALFILL) {
FillOnion = (int)(m_onion.getValue());
FillSegment = (int)(m_segment.getValue());
}
FillType = ::to_string(m_fillType.getValue());
rectPropChangedflag = true;
}
// Onion Skin
else if (propertyName == m_onion.getName()) {
if (m_onion.getValue()) FillType = ::to_string(m_fillType.getValue());
FillOnion = (int)(m_onion.getValue());
}
// Frame Range
else if (propertyName == m_frameRange.getName()) {
FillRange = (int)(m_frameRange.getValue());
resetMulti();
rectPropChangedflag = true;
}
// Selective
else if (propertyName == m_selective.getName()) {
rectPropChangedflag = true;
}
// Fill Depth
else if (propertyName == m_fillDepth.getName()) {
MinFillDepth = (int)m_fillDepth.getValue().first;
MaxFillDepth = (int)m_fillDepth.getValue().second;
}
// Segment
else if (propertyName == m_segment.getName()) {
if (m_segment.getValue()) FillType = ::to_string(m_fillType.getValue());
FillSegment = (int)(m_segment.getValue());
}
else if (propertyName == m_rasterGapDistance.getName()) {
AutocloseDistance = m_rasterGapDistance.getValue();
TTool::Application *app = TTool::getApplication();
// This is a hack to get the viewer to update with the distance.
app->getCurrentOnionSkin()->notifyOnionSkinMaskChanged();
}
else if (propertyName == m_closeStyleIndex.getName()) {
}
else if (propertyName == m_closeRasterGaps.getName()) {
RasterGapSetting = ::to_string(m_closeRasterGaps.getValue());
}
// Autopaint
else if (propertyName == m_autopaintLines.getName()) {
rectPropChangedflag = true;
}
else if (!m_frameSwitched &&
(propertyName == m_maxGapDistance.getName() ||
propertyName == m_maxGapDistance.getName() + "withUndo")) {
TXshLevel *xl = TTool::getApplication()->getCurrentLevel()->getLevel();
m_level = xl ? xl->getSimpleLevel() : 0;
if (TVectorImageP vi = getImage(true)) {
if (m_changedGapOriginalValue == -1.0) {
ImageUtils::getFillingInformationInArea(vi, m_oldFillInformation,
vi->getBBox());
m_changedGapOriginalValue = vi->getAutocloseTolerance();
}
TFrameId fid = getCurrentFid();
vi->setAutocloseTolerance(m_maxGapDistance.getValue());
int count = vi->getStrokeCount();
std::vector<int> v(count);
int i;
for (i = 0; i < (int)count; i++) v[i] = i;
vi->notifyChangedStrokes(v, std::vector<TStroke *>(), false);
if (m_level) {
m_level->setDirtyFlag(true);
TTool::getApplication()->getCurrentLevel()->notifyLevelChange();
if (propertyName == m_maxGapDistance.getName() + "withUndo" &&
m_changedGapOriginalValue != -1.0) {
TUndoManager::manager()->add(new VectorGapSizeChangeUndo(
m_changedGapOriginalValue, m_maxGapDistance.getValue(),
m_level.getPointer(), fid, vi, m_oldFillInformation));
m_changedGapOriginalValue = -1.0;
m_oldFillInformation.clear();
TTool::Application *app = TTool::getApplication();
app->getCurrentXsheet()->notifyXsheetChanged();
notifyImageChanged();
}
}
}
}
if (propertyName == m_fillOnlySavebox.getName()) {
FillOnlySavebox = (int)(m_fillOnlySavebox.getValue());
rectPropChangedflag = true;
}
/*--- fillType, frameRange, selective, colorTypeが変わったとき ---*/
if (rectPropChangedflag && m_fillType.getValue() != NORMALFILL) {
AreaFillTool::Type type;
if (m_fillType.getValue() == RECTFILL)
type = AreaFillTool::RECT;
else if (m_fillType.getValue() == FREEHANDFILL)
type = AreaFillTool::FREEHAND;
else if (m_fillType.getValue() == POLYLINEFILL)
type = AreaFillTool::POLYLINE;
else
assert(false);
m_rectFill->onPropertyChanged(
m_frameRange.getValue(), m_selective.getValue(), m_onion.getValue(),
type, m_colorType.getValue(), m_autopaintLines.getValue(),
m_fillOnlySavebox.getValue());
}
return true;
}
//-----------------------------------------------------------------------------
void FillTool::mouseMove(const TPointD &pos, const TMouseEvent &e) {
if (m_fillType.getValue() != NORMALFILL) m_rectFill->mouseMove(pos, e);
}
//-----------------------------------------------------------------------------
void FillTool::onImageChanged() {
if (m_fillType.getValue() != NORMALFILL) {
m_rectFill->onImageChanged();
return;
}
if (TVectorImageP vi = getImage(true)) {
m_frameSwitched = true;
if (m_maxGapDistance.getValue() != vi->getAutocloseTolerance()) {
m_maxGapDistance.setValue(vi->getAutocloseTolerance());
getApplication()->getCurrentTool()->notifyToolChanged();
}
m_frameSwitched = false;
}
if (!m_level) resetMulti();
}
//-----------------------------------------------------------------------------
void FillTool::onFrameSwitched() {
m_frameSwitched = true;
if (TVectorImageP vi = getImage(true)) {
if (m_maxGapDistance.getValue() != vi->getAutocloseTolerance()) {
m_maxGapDistance.setValue(vi->getAutocloseTolerance());
getApplication()->getCurrentTool()->notifyToolChanged();
}
}
m_frameSwitched = false;
m_changedGapOriginalValue = -1.0;
}
//-----------------------------------------------------------------------------
void FillTool::draw() {
if (m_fillOnlySavebox.getValue()) {
TToonzImageP ti = (TToonzImageP)getImage(false);
if (ti) {
TRectD bbox =
ToonzImageUtils::convertRasterToWorld(convert(ti->getBBox()), ti);
drawRect(bbox.enlarge(0.5) * ti->getSubsampling(),
TPixel32(210, 210, 210), 0xF0F0, true);
}
}
if (m_fillType.getValue() != NORMALFILL) {
m_rectFill->draw();
return;
}
if (m_frameRange.getValue() && m_firstClick) {
tglColor(TPixel::Red);
drawCross(m_firstPoint, 6);
} else if (!m_frameRange.getValue() &&
getFillParameters().m_fillType == LINES &&
m_targetType == TTool::ToonzImage)
m_normalLineFillTool->draw();
}
//-----------------------------------------------------------------------------
int FillTool::pick(const TImageP &image, const TPointD &pos, const int frame) {
TToonzImageP ti = image;
TVectorImageP vi = image;
if (!ti && !vi) return 0;
StylePicker picker(image);
double scale2 = 1.0;
if (vi) {
TAffine aff = getViewer()->getViewMatrix() * getCurrentColumnMatrix(frame);
scale2 = aff.det();
}
TPointD pickPos = pos;
// in case that the column is animated in scene-editing mode
if (frame > 0) {
TPointD dpiScale = getViewer()->getDpiScale();
pickPos.x *= dpiScale.x;
pickPos.y *= dpiScale.y;
TPointD worldPos = getCurrentColumnMatrix() * pickPos;
pickPos = getCurrentColumnMatrix(frame).inv() * worldPos;
pickPos.x /= dpiScale.x;
pickPos.y /= dpiScale.y;
}
// thin stroke can be picked with 10 pixel range
return picker.pickStyleId(pickPos, 10.0, scale2);
}
//-----------------------------------------------------------------------------
int FillTool::pickOnionColor(const TPointD &pos) {
TTool::Application *app = TTool::getApplication();
if (!app) return 0;
bool filmStripEditing = !app->getCurrentObject()->isSpline();
OnionSkinMask osMask = app->getCurrentOnionSkin()->getOnionSkinMask();
TFrameId fid = getCurrentFid();
TXshSimpleLevel *sl = m_level.getPointer();
if (!sl) return 0;
std::vector<int> rows;
// level editing case
if (app->getCurrentFrame()->isEditingLevel()) {
osMask.getAll(sl->guessIndex(fid), rows);
int i, j;
for (i = 0; i < (int)rows.size(); i++)
if (sl->index2fid(rows[i]) > fid) break;
int onionStyleId = 0;
for (j = i - 1; j >= 0; j--) {
TFrameId onionFid = sl->index2fid(rows[j]);
if (onionFid != fid &&
((onionStyleId =
pick(m_level->getFrame(onionFid, ImageManager::none, 1), pos)) >
0)) // subsampling must be 1, otherwise onionfill does not work
break;
}
if (onionStyleId == 0)
for (j = i; j < (int)rows.size(); j++) {
TFrameId onionFid = sl->index2fid(rows[j]);
if (onionFid != fid &&
((onionStyleId = pick(
m_level->getFrame(onionFid, ImageManager::none, 1), pos)) >
0)) // subsampling must be 1, otherwise onionfill does not work
break;
}
return onionStyleId;
} else { // scene editing case
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
int colId = app->getCurrentColumn()->getColumnIndex();
int row = app->getCurrentFrame()->getFrame();
osMask.getAll(row, rows);
std::vector<int>::iterator it = rows.begin();
while (it != rows.end() && *it < row) it++;
std::sort(rows.begin(), it, descending);
int onionStyleId = 0;
for (int i = 0; i < (int)rows.size(); i++) {
if (rows[i] == row) continue;
TXshCell cell = xsh->getCell(rows[i], colId);
TXshLevel *xl = cell.m_level.getPointer();
if (!xl || xl->getSimpleLevel() != sl) continue;
TFrameId onionFid = cell.getFrameId();
onionStyleId = pick(m_level->getFrame(onionFid, ImageManager::none, 1),
pos, rows[i]);
if (onionStyleId > 0) break;
}
return onionStyleId;
}
}
//-----------------------------------------------------------------------------
void FillTool::onEnter() {
// resetMulti();
// getApplication()->editImage();
}
//-----------------------------------------------------------------------------
void FillTool::onActivate() {
// OnionSkinMask osMask = getApplication()->getOnionSkinMask(false);
/*
for (int i=0; i<osMask.getMosCount(); i++)
boh = osMask.getMos(i);
for (i=0; i<osMask.getFosCount(); i++)
boh = osMask.getFos(i);
*/
if (m_firstTime) {
m_fillDepth.setValue(
TDoublePairProperty::Value(MinFillDepth, MaxFillDepth));
m_fillType.setValue(::to_wstring(FillType.getValue()));
m_colorType.setValue(::to_wstring(FillColorType.getValue()));
// m_onlyEmpty.setValue(FillSelective ? 1 :0);
m_onion.setValue(FillOnion ? 1 : 0);
m_segment.setValue(FillSegment ? 1 : 0);
m_frameRange.setValue(FillRange ? 1 : 0);
m_fillOnlySavebox.setValue(FillOnlySavebox ? 1 : 0);
m_firstTime = false;
if (m_fillType.getValue() != NORMALFILL) {
AreaFillTool::Type type;
if (m_fillType.getValue() == RECTFILL)
type = AreaFillTool::RECT;
else if (m_fillType.getValue() == FREEHANDFILL)
type = AreaFillTool::FREEHAND;
else if (m_fillType.getValue() == POLYLINEFILL)
type = AreaFillTool::POLYLINE;
else
assert(false);
m_rectFill->onPropertyChanged(
m_frameRange.getValue(), m_selective.getValue(), m_onion.getValue(),
type, m_colorType.getValue(), m_autopaintLines.getValue(),
m_fillOnlySavebox.getValue());
}
}
if (m_fillType.getValue() != NORMALFILL) {
m_rectFill->onActivate();
return;
}
if (FillColorType.getValue() == "Lines") m_normalLineFillTool->init();
resetMulti();
if (m_targetType == TTool::ToonzImage) {
m_closeRasterGaps.setValue(::to_wstring(RasterGapSetting.getValue()));
m_rasterGapDistance.setValue(AutocloseDistance);
}
// getApplication()->editImage();
TVectorImageP vi = TImageP(getImage(false));
if (!vi) return;
vi->findRegions();
if (m_targetType == TTool::VectorImage) {
if (m_level) {
TImageP img = getImage(true);
if (TVectorImageP vi = img) {
double tolerance = vi->getAutocloseTolerance();
if (tolerance < 9.9) tolerance += 0.000001;
m_maxGapDistance.setValue(tolerance);
}
}
}
bool ret = true;
ret = ret && connect(TTool::m_application->getCurrentFrame(),
SIGNAL(frameSwitched()), this, SLOT(onFrameSwitched()));
ret = ret && connect(TTool::m_application->getCurrentScene(),
SIGNAL(sceneSwitched()), this, SLOT(onFrameSwitched()));
ret = ret &&
connect(TTool::m_application->getCurrentColumn(),
SIGNAL(columnIndexSwitched()), this, SLOT(onFrameSwitched()));
assert(ret);
}
//-----------------------------------------------------------------------------
void FillTool::onDeactivate() {
disconnect(TTool::m_application->getCurrentFrame(), SIGNAL(frameSwitched()),
this, SLOT(onFrameSwitched()));
disconnect(TTool::m_application->getCurrentScene(), SIGNAL(sceneSwitched()),
this, SLOT(onFrameSwitched()));
disconnect(TTool::m_application->getCurrentColumn(),
SIGNAL(columnIndexSwitched()), this, SLOT(onFrameSwitched()));
}
//-----------------------------------------------------------------------------
FillTool FillVectorTool(TTool::VectorImage);
FillTool FiilRasterTool(TTool::ToonzImage);
|
//////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source
// License. See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by:
//
// File created by:
// Fionn D. Malone, malone14@llnl.gov
// Lawrence Livermore National Laboratory
////////////////////////////////////////////////////////////////////////////////
#include "catch.hpp"
#include "Configuration.h"
#undef APP_ABORT
#define APP_ABORT(x) {std::cout << x; exit(0);}
#include <vector>
#include "AFQMC/config.h"
#include "AFQMC/config.0.h"
#include "AFQMC/Numerics/ma_blas.hpp"
#include "AFQMC/Numerics/batched_operations.hpp"
#include "AFQMC/Matrix/tests/matrix_helpers.h"
#include "multi/array.hpp"
#include "multi/array_ref.hpp"
using boost::multi::array;
using boost::multi::array_ref;
using std::copy_n;
using boost::multi::iextensions;
namespace qmcplusplus
{
using namespace afqmc;
#if defined(ENABLE_CUDA) || defined(ENABLE_HIP)
template<typename T> using Alloc = device::device_allocator<T>;
#else
template<typename T> using Alloc = std::allocator<T>;
#endif
template<typename T> using pointer = typename Alloc<T>::pointer;
template<typename T> using Tensor1D = array<T,1,Alloc<T>>;
template<typename T> using Tensor2D = array<T,2,Alloc<T>>;
template<typename T> using Tensor3D = array<T,3,Alloc<T>>;
template<typename T> using Tensor4D = array<T,4,Alloc<T>>;
template<typename T> using Tensor5D = array<T,5,Alloc<T>>;
template<typename T> using Tensor2D_ref = array_ref<T,2,pointer<T>>;
template<typename T> using Tensor1D_ref = array_ref<T,1,pointer<T>>;
template <typename T>
void create_data(std::vector<T>& buffer, T scale)
{
T count = T(0);
for (int i=0; i<buffer.size(); i++) {
buffer[i] = count;
count += T(1) / scale;
}
}
// Test data for assertions was created from captured output.
TEST_CASE("Tab_to_Kl", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
// Tab_to_Kl tests, normally used for Coulomb energy evaluation via
// E_c[w] = \sum_{na} T[w,aa,n] T[w,aa,n]
// = \sum_{n} K[w,n] K[w,n]
int nwalk = 3;
int nel = 3;
int nchol = 7;
std::vector<ComplexType> buffer(nwalk*nel*nel*nchol);
create_data(buffer, ComplexType(1.0));
Tensor4D<ComplexType> Twban({nwalk, nel, nel, nchol}, alloc);
copy_n(buffer.data(), buffer.size(), Twban.origin());
Tensor2D<ComplexType> Kl({nwalk,nchol}, 0.0, alloc);
using ma::Tab_to_Kl;
Tab_to_Kl(nwalk, nel, nchol, Twban.origin(), Kl.origin());
array_ref<ComplexType,1,pointer<ComplexType>> Kl_(Kl.origin(), iextensions<1u>{nwalk*nchol});
array<ComplexType,1,Alloc<ComplexType>> ref = {84.0, 87.0, 90.0, 93.0, 96.0, 99.0, 102.0, 273.0, 276.0,
279.0, 282.0, 285.0, 288.0, 291.0, 462.0, 465.0, 468.0, 471.0,
474.0, 477.0, 480.0};
verify_approx(Kl_, ref);
}
TEST_CASE("batched_Tab_to_Klr", "[batched_operations]")
{
Alloc<ComplexType> alloc{};
int nwalk = 3;
int nel = 3;
int nchol = 11;
int nbatch = 4;
int nchol_max = 3;
int ncholQ = 2;
int ncholQ0 = 2;
std::vector<int> kdiag = {0,1,2,3};
Tensor1D<int> dev_kdiag(iextensions<1u>{nbatch}, alloc);
copy_n(kdiag.data(), kdiag.size(), dev_kdiag.origin());
std::vector<ComplexType> buffer(2*nbatch*nwalk*nel*nel*nchol_max);
create_data(buffer, ComplexType(1.0));
Tensor5D<ComplexType> Tab({2*nbatch, nwalk, nel, nel, nchol_max}, alloc);
copy_n(buffer.data(), buffer.size(), Tab.origin());
Tensor2D<ComplexType> Kl({nwalk,2*nchol}, 0.0, alloc);
Tensor2D<ComplexType> Kr({nwalk,2*nchol}, 0.0, alloc);
using ma::batched_Tab_to_Klr;
batched_Tab_to_Klr(nbatch, nwalk, nel, nchol_max, nchol, ncholQ, ncholQ0,
dev_kdiag.origin(), Tab.origin(), Kl.origin(), Kr.origin());
copy_n(Kr.origin(), Kr.num_elements(), buffer.data());
//std::cout << std::setprecision(16) << Kl[2][3] << " " << Kl[1][4] << " " << Kr[1][3] << " " << Kr[0][1] << std::endl;
REQUIRE(real(buffer[2*nchol+3]) == Approx(2262));
}
TEST_CASE("Tanb_to_Kl", "[batched_operations]")
{
Alloc<ComplexType> alloc{};
// Tab_to_Kl tests, normally used for Coulomb energy evaluation via
// E_c[w] = \sum_{na} T[w,aa,n] T[w,aa,n]
// = \sum_{n} K[w,n] K[w,n]
int nwalk = 3;
int nel = 3;
int nchol = 7;
std::vector<ComplexType> buffer(nwalk*nel*nel*nchol);
create_data(buffer, ComplexType(1.0));
Tensor4D<ComplexType> Twanb({nwalk, nel, nchol, nel}, alloc);
copy_n(buffer.data(), buffer.size(), Twanb.origin());
Tensor2D<ComplexType> Kl({nwalk,nchol}, 0.0, alloc);
using ma::Tanb_to_Kl;
Tanb_to_Kl(nwalk, nel, nchol, nchol, Twanb.origin(), Kl.origin());
array_ref<ComplexType,1,pointer<ComplexType>> Kl_(Kl.origin(), iextensions<1u>{nwalk*nchol});
//std::cout << "{";
//for (auto i : Kl_)
//std::cout << "ComplexType(" << real(i) << ")," << std::endl;
//std::cout << "};" << std::endl;;
array<ComplexType,1,Alloc<ComplexType>> ref = {ComplexType(66), ComplexType(75),
ComplexType(84), ComplexType(93), ComplexType(102), ComplexType(111),
ComplexType(120), ComplexType(255), ComplexType(264), ComplexType(273),
ComplexType(282), ComplexType(291), ComplexType(300), ComplexType(309),
ComplexType(444), ComplexType(453), ComplexType(462), ComplexType(471),
ComplexType(480), ComplexType(489), ComplexType(498)};
verify_approx(Kl_, ref);
}
TEST_CASE("batched_dot_wabn_wban", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
int nbatch = 4;
int nwalk = 3;
int nocc = 7;
int nchol = 13;
// 2*nbatch as routine expects left and right tensors to contract.
std::vector<ComplexType> buffer(2*nbatch*nwalk*nocc*nocc*nchol);
create_data(buffer, ComplexType(1e4));
Tensor5D<ComplexType> Twabn({2*nbatch, nwalk, nocc, nocc, nchol}, alloc);
Tensor1D<ComplexType> scal({nbatch}, 1.0, alloc);
copy_n(buffer.data(), buffer.size(), Twabn.origin());
std::vector<pointer<ComplexType>> Aarray;
array<ComplexType,1,Alloc<ComplexType>> out(iextensions<1u>{nwalk}, alloc);
array<ComplexType,1,Alloc<ComplexType>> ref = {ComplexType(1693.073254599684),
ComplexType(1930.853888599637),
ComplexType(2189.312510839587)};
using ma::batched_dot_wabn_wban;
batched_dot_wabn_wban(nbatch, nwalk, nocc, nchol, scal.origin(),
Twabn.origin(), to_address(out.data()), 1);
//std::cout << std::setprecision(16) << "this: " << out[0] << " " << out[1] << " " << out[2] << std::endl;
verify_approx(ref,out);
}
// Not used.
TEST_CASE("batched_dot_wanb_wbna", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
int nbatch = 4;
int nwalk = 3;
int nocc = 7;
int nchol = 13;
// 2*nbatch as routine expects left and right tensors to contract.
std::vector<ComplexType> buffer(2*nbatch*nwalk*nocc*nocc*nchol);
create_data(buffer, ComplexType(1e4));
Tensor5D<ComplexType> Twabn({2*nbatch, nwalk, nocc, nchol, nocc}, alloc);
Tensor1D<ComplexType> scal({nbatch}, 1.0, alloc);
copy_n(buffer.data(), buffer.size(), Twabn.origin());
std::vector<pointer<ComplexType>> Aarray;
array<ComplexType,1,Alloc<ComplexType>> out(iextensions<1u>{nwalk}, alloc);
array<ComplexType,1,Alloc<ComplexType>> ref = {ComplexType(1692.867783879684),
ComplexType(1930.648417879638),
ComplexType(2189.107040119586)};
using ma::batched_dot_wanb_wbna;
batched_dot_wanb_wbna(nbatch, nwalk, nocc, nchol, scal.origin(),
Twabn.origin(), to_address(out.data()), 1);
//std::cout << std::setprecision(16) << "this: " << out[0] << " " << out[1] << " " << out[2] << std::endl;
verify_approx(ref,out);
}
TEST_CASE("dot_wabn", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
int nwalk = 3;
int nocc = 7;
int nchol = 13;
std::vector<ComplexType> buffer(nwalk*nocc*nocc*nchol);
create_data(buffer, ComplexType(100));
Tensor4D<ComplexType> Twabn({nwalk, nocc, nocc, nchol}, alloc);
copy_n(buffer.data(), buffer.size(), Twabn.origin());
array<ComplexType,1,Alloc<ComplexType>> out(iextensions<1u>{nwalk}, alloc);
using ma::dot_wabn;
dot_wabn(nwalk, nocc, nchol, ComplexType(1.0), Twabn.origin(), to_address(out.origin()), 1);
array<ComplexType,1,Alloc<ComplexType>> ref = {ComplexType(7045.35), ComplexType(58699.7), ComplexType(162049.0)};
verify_approx(out, ref);
}
TEST_CASE("dot_wanb", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
int nwalk = 3;
int nocc = 7;
int nchol = 13;
std::vector<ComplexType> buffer(nwalk*nocc*nocc*nchol);
// T = numpy.arange(nw*nocc*nocc*nchol).reshape(nw,nocc,nchol,nocc) / 100.0
create_data(buffer, ComplexType(100));
Tensor4D<ComplexType> Twanb({nwalk, nocc, nchol, nocc}, alloc);
copy_n(buffer.data(), buffer.size(), Twanb.origin());
array<ComplexType,1,Alloc<ComplexType>> out(iextensions<1u>{nwalk}, 0.0, alloc);
using ma::dot_wanb;
// out = numpy.einsum('wanb,wbna->w', Twanb, Twanb)
dot_wanb(nwalk, nocc, nchol, ComplexType(1.0), Twanb.origin(), to_address(out.origin()), 1);
array<ComplexType,1,Alloc<ComplexType>> ref = {ComplexType(6531.67), ComplexType(58186.1), ComplexType(161535)};
verify_approx(out, ref);
}
TEST_CASE("Auwn_Bun_Cuw", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
int nu = 3;
int nw = 2;
int nn = 4;
Tensor3D<ComplexType> A({nu, nw, nn}, 1.0, alloc);
Tensor2D<ComplexType> B({nu, nn}, 2.0, alloc);
Tensor2D<ComplexType> C({nu, nw}, 0.0, alloc);
ComplexType alpha = 0.5;
// C = alpha * numpy.einsum('uwn,un->uw', A, B)
using ma::Auwn_Bun_Cuw;
Auwn_Bun_Cuw(nu, nw, nn, alpha, A.origin(), B.origin(), C.origin());
Tensor2D<ComplexType> ref({nu, nw}, 4.0, alloc);
verify_approx(C, ref);
}
TEST_CASE("Awiu_Biu_Cuw", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
int nu = 3;
int nw = 2;
int nn = 4;
Tensor3D<ComplexType> A({nw, nn, nu}, 1.0, alloc);
Tensor2D<ComplexType> B({nn, nu}, 2, alloc);
B[0][1] = 0.0;
Tensor2D<ComplexType> C({nu, nw}, 0.0, alloc);
ComplexType alpha = 0.5;
// C = alpha * numpy.einsum('wnu,nu->uw', A, B)
using ma::Awiu_Biu_Cuw;
Awiu_Biu_Cuw(nu, nw, nn, alpha, A.origin(), B.origin(), B.size(1), C.origin(), C.size(1));
Tensor2D<ComplexType> ref({nu, nw}, 4.0, alloc);
ref[1][0] = 3.0;
ref[1][1] = 3.0;
verify_approx(C, ref);
}
TEST_CASE("Aijk_Bkj_Cik", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
int ni = 3;
int nj = 2;
int nk = 4;
Tensor3D<ComplexType> A({ni, nj, nk}, 1.0, alloc);
Tensor2D<ComplexType> B({nk, nj}, 2, alloc);
B[0][1] = 0.0;
Tensor2D<ComplexType> C({ni, nk}, 0.0, alloc);
// C = alpha * numpy.einsum('wnu,nu->uw', A, B)
using ma::Aijk_Bkj_Cik;
Aijk_Bkj_Cik(ni, nj, nk, A.origin(), A.size(1), A.stride(0),
B.origin(), B.stride(0), C.origin(), C.stride(0));
Tensor2D<ComplexType> ref({ni, nk}, 4.0, alloc);
ref[0][0] = 2.0;
ref[1][0] = 2.0;
ref[2][0] = 2.0;
verify_approx(C, ref);
}
TEST_CASE("viwj_vwij", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
int ni = 3;
int nj = 2;
int nw = 4;
Tensor3D<ComplexType> A({nw, ni, nj}, 0.0, alloc);
Tensor3D<ComplexType> B({ni, nw, nj}, 0.0, alloc);
std::vector<ComplexType> buffer(ni*nj*nw);
create_data(buffer, ComplexType(1.0));
copy_n(buffer.data(), buffer.size(), B.origin());
using ma::viwj_vwij;
//viwj_vwij(nw, ni, 0, nj, B.data(), A.data());
//std::cout << A[0][1][1] << " " << A[1][2][1] << std::endl;
}
TEST_CASE("element_wise_Aij_Bjk_Ckij", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
int ni = 3;
int nj = 2;
int nk = 2;
using ma::element_wise_Aij_Bjk_Ckij;
{
Tensor2D<ComplexType> A({ni, nj}, 3.0, alloc);
Tensor2D<ComplexType> B({nj, nk}, 2.0, alloc);
Tensor3D<ComplexType> C({nk, ni, nj}, 0.0, alloc);
element_wise_Aij_Bjk_Ckij('N', ni, nj, nk,
A.origin(), A.stride(0),
B.origin(), B.stride(0),
C.origin(), C.size(1), C.size(2));
Tensor3D<ComplexType> ref({nk, ni, nj}, 6.0, alloc);
verify_approx(C, ref);
}
{
Tensor2D<ComplexType> A({ni, nj}, ComplexType(0.0,-3.0), alloc);
Tensor2D<ComplexType> B({nj, nk}, ComplexType(1.0,2.0), alloc);
Tensor3D<ComplexType> C({nk, ni, nj}, 0.0, alloc);
element_wise_Aij_Bjk_Ckij('C', ni, nj, nk,
A.origin(), A.stride(0),
B.origin(), B.stride(0),
C.origin(), C.size(1), C.size(2));
Tensor3D<ComplexType> ref({nk, ni, nj}, ComplexType(-6.0,3.0), alloc);
verify_approx(C, ref);
}
}
template <typename T1, typename T2>
void test_Aij_Bjk_Ckji()
{
Alloc<T1> alloc_a{};
Alloc<T2> alloc_b{};
int ni = 3;
int nj = 2;
int nk = 2;
using ma::element_wise_Aij_Bjk_Ckji;
Tensor2D<T1> A({ni, nj}, -3.0, alloc_a);
Tensor2D<T2> B({nj, nk}, T2(1.0,2.0), alloc_b);
Tensor3D<T2> C({nk, nj, ni}, 0.0, alloc_b);
element_wise_Aij_Bjk_Ckji(ni, nj, nk,
A.origin(), A.stride(0),
B.origin(), B.stride(0),
C.origin(), C.size(2), C.stride(0));
Tensor3D<T2> ref({nk, nj, ni}, T2(-3.0, -6.0), alloc_b);
verify_approx(C, ref);
}
TEST_CASE("element_wise_Aij_Bjk_Ckji", "[Numerics][batched_operations]")
{
test_Aij_Bjk_Ckji<double,std::complex<double>>();
test_Aij_Bjk_Ckji<float,std::complex<float>>();
test_Aij_Bjk_Ckji<std::complex<double>,std::complex<double>>();
test_Aij_Bjk_Ckji<std::complex<float>,std::complex<float>>();
}
TEST_CASE("inplace_product", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
Alloc<double> dalloc{};
int nb = 4;
int ni = 3;
int nj = 2;
Tensor3D<ComplexType> A({nb, ni, nj}, ComplexType(1.0,-3.0), alloc);
Tensor2D<double> B({ni, nj}, 2.0, dalloc);
using ma::inplace_product;
inplace_product(nb, ni, nj, B.origin(), B.size(1), A.origin(), A.size(2));
Tensor3D<ComplexType> ref({nb, ni, nj}, ComplexType(2.0,-6.0), alloc);
verify_approx(A, ref);
}
// Not clear.
//TEST_CASE("batched_ab_ba", "[Numerics][batched_operations]")
//{
//Alloc<ComplexType> alloc{};
//int nbatch = 4;
//int nrows = 7;
//int ncols = 7;
//std::vector<int> packed_dims = {7,7,7,7,7,7,7,7};
//Tensor1D<ComplexType> Buff;
//Buff = std::move(Tensor1D<ComplexType>(iextensions<1u>{2*nrows*ncols+nbatch}, alloc));
//Tensor2D_ref<ComplexType> A(make_device_ptr(Buff.origin()), {nrows,ncols});
//Tensor2D_ref<ComplexType> B(make_device_ptr(Buff.origin()+nrows*ncols), {nrows,ncols});
//Tensor1D_ref<ComplexType> C(make_device_ptr(Buff.origin()+2*nrows*ncols), iextensions<1u>{nbatch});
////Tensor2D<ComplexType> A({nrows, ncols}, alloc);
////Tensor2D<ComplexType> B({ncols, nrows}, alloc);
//std::vector<pointer<ComplexType>> Aarray(nbatch);
//std::vector<pointer<ComplexType>> Barray(nbatch);
////std::vector<pointer<ComplexType>> y(nbatch);
//std::vector<ComplexType> buffer(nrows*ncols);
//create_data(buffer, ComplexType(1.0));
//copy_n(buffer.data(), buffer.size(), A.origin());
//copy_n(buffer.data(), buffer.size(), B.origin());
//for (int i=0; i < nbatch; i++) {
//Aarray.emplace_back(ma::pointer_dispatch(A.origin()));
//Barray.emplace_back(ma::pointer_dispatch(B.origin()));
//}
//using ma::batched_ab_ba;
//batched_ab_ba(packed_dims.data(), A.data(), ncols, B.data(), nrows,
//ComplexType(1.0), C.data(), nbatch);
//}
TEST_CASE("vbias_from_v1", "[Numerics][batched_operations]")
{
Alloc<ComplexType> alloc{};
int nkpts = 4;
int nwalk = 4;
int nchol_max = 87;
int nchol_tot = 339;
Tensor1D<int> qmap = {1, 2, 3, 4};
Tensor1D<int> kminus = {0, 1, 2, 3};
Tensor1D<int> nchol_pq = {87, 84, 84, 84};
Tensor1D<int> q2vbias = {0, 174, 342, 510};
Tensor3D<ComplexType> v1({2*nkpts, nchol_max, nwalk}, ComplexType(1.0,-0.007), alloc);
Tensor2D<ComplexType> vbias({2*nchol_tot, nwalk}, 0.0, alloc);
using ma::vbias_from_v1;
vbias_from_v1(nwalk, nkpts, nchol_max, qmap.origin(), kminus.origin(),
nchol_pq.origin(), q2vbias.origin(), ComplexType(0.05),
v1.origin(), to_address(vbias.origin()));
array<ComplexType,2> vbias_host({2*nchol_tot, nwalk}, 0.0);
copy_n(vbias.origin(), vbias.num_elements(), vbias_host.origin());
// Captured from stdout
REQUIRE(real(vbias_host[0][0]) == Approx(0.1));
REQUIRE(imag(vbias_host[10][0]) == Approx(-0.0007));
REQUIRE(imag(vbias_host[100][2]) == Approx(0));
}
}
|
/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** PeerConnectionManager.cpp
**
** -------------------------------------------------------------------------*/
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include "api/video_codecs/builtin_video_decoder_factory.h"
#include "api/video_codecs/builtin_video_encoder_factory.h"
#include "api/audio_codecs/builtin_audio_encoder_factory.h"
#include "api/audio_codecs/builtin_audio_decoder_factory.h"
#include "api/rtc_event_log/rtc_event_log_factory.h"
#include "api/task_queue/default_task_queue_factory.h"
#include "media/engine/webrtc_media_engine.h"
#include "modules/audio_device/include/fake_audio_device.h"
#include "PeerConnectionManager.h"
#include "V4l2AlsaMap.h"
#include "CapturerFactory.h"
#include "VideoScaler.h"
#include "VideoFilter.h"
#include "NullEncoder.h"
#include "NullDecoder.h"
// Names used for a IceCandidate JSON object.
const char kCandidateSdpMidName[] = "sdpMid";
const char kCandidateSdpMlineIndexName[] = "sdpMLineIndex";
const char kCandidateSdpName[] = "candidate";
// Names used for a SessionDescription JSON object.
const char kSessionDescriptionTypeName[] = "type";
const char kSessionDescriptionSdpName[] = "sdp";
// character to remove from url to make webrtc label
bool ignoreInLabel(char c)
{
return c == ' ' || c == ':' || c == '.' || c == '/' || c == '&';
}
/* ---------------------------------------------------------------------------
** helpers that should be moved somewhere else
** -------------------------------------------------------------------------*/
#ifdef WIN32
std::string getServerIpFromClientIp(int clientip)
{
return "127.0.0.1";
}
#else
#include <net/if.h>
#include <ifaddrs.h>
std::string getServerIpFromClientIp(int clientip)
{
std::string serverAddress;
char host[NI_MAXHOST];
struct ifaddrs *ifaddr = NULL;
if (getifaddrs(&ifaddr) == 0)
{
for (struct ifaddrs *ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{
if ((ifa->ifa_netmask != NULL) && (ifa->ifa_netmask->sa_family == AF_INET) && (ifa->ifa_addr != NULL) && (ifa->ifa_addr->sa_family == AF_INET))
{
struct sockaddr_in *addr = (struct sockaddr_in *)ifa->ifa_addr;
struct sockaddr_in *mask = (struct sockaddr_in *)ifa->ifa_netmask;
if ((addr->sin_addr.s_addr & mask->sin_addr.s_addr) == (clientip & mask->sin_addr.s_addr))
{
if (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, sizeof(host), NULL, 0, NI_NUMERICHOST) == 0)
{
serverAddress = host;
break;
}
}
}
}
}
freeifaddrs(ifaddr);
return serverAddress;
}
#endif
struct IceServer
{
std::string url;
std::string user;
std::string pass;
};
IceServer getIceServerFromUrl(const std::string &url, const std::string &clientIp = "")
{
IceServer srv;
srv.url = url;
std::size_t pos = url.find_first_of(':');
if (pos != std::string::npos)
{
std::string protocol = url.substr(0, pos);
std::string uri = url.substr(pos + 1);
std::string credentials;
std::size_t pos = uri.rfind('@');
if (pos != std::string::npos)
{
credentials = uri.substr(0, pos);
uri = uri.substr(pos + 1);
}
if ((uri.find("0.0.0.0:") == 0) && (clientIp.empty() == false))
{
// answer with ip that is on same network as client
std::string clienturl = getServerIpFromClientIp(inet_addr(clientIp.c_str()));
clienturl += uri.substr(uri.find_first_of(':'));
uri = clienturl;
}
srv.url = protocol + ":" + uri;
if (!credentials.empty())
{
pos = credentials.find(':');
if (pos == std::string::npos)
{
srv.user = credentials;
}
else
{
srv.user = credentials.substr(0, pos);
srv.pass = credentials.substr(pos + 1);
}
}
}
return srv;
}
std::unique_ptr<webrtc::VideoEncoderFactory> CreateEncoderFactory(bool nullCodec) {
std::unique_ptr<webrtc::VideoEncoderFactory> factory;
if (nullCodec) {
factory = std::make_unique<VideoEncoderFactory>();
} else {
factory = webrtc::CreateBuiltinVideoEncoderFactory();
}
return factory;
}
std::unique_ptr<webrtc::VideoDecoderFactory> CreateDecoderFactory(bool nullCodec) {
std::unique_ptr<webrtc::VideoDecoderFactory> factory;
if (nullCodec) {
factory = std::make_unique<VideoDecoderFactory>();
} else {
factory = webrtc::CreateBuiltinVideoDecoderFactory();
}
return factory;
}
webrtc::PeerConnectionFactoryDependencies CreatePeerConnectionFactoryDependencies(rtc::Thread* signalingThread, rtc::Thread* workerThread, rtc::scoped_refptr<webrtc::AudioDeviceModule> audioDeviceModule, rtc::scoped_refptr<webrtc::AudioDecoderFactory> audioDecoderfactory, bool useNullCodec)
{
webrtc::PeerConnectionFactoryDependencies dependencies;
dependencies.network_thread = NULL;
dependencies.worker_thread = workerThread;
dependencies.signaling_thread = signalingThread;
dependencies.call_factory = webrtc::CreateCallFactory();
dependencies.task_queue_factory = webrtc::CreateDefaultTaskQueueFactory();
dependencies.event_log_factory = absl::make_unique<webrtc::RtcEventLogFactory>(dependencies.task_queue_factory.get());
cricket::MediaEngineDependencies mediaDependencies;
mediaDependencies.task_queue_factory = dependencies.task_queue_factory.get();
mediaDependencies.adm = std::move(audioDeviceModule);
mediaDependencies.audio_encoder_factory = webrtc::CreateBuiltinAudioEncoderFactory();
mediaDependencies.audio_decoder_factory = std::move(audioDecoderfactory);
mediaDependencies.audio_processing = webrtc::AudioProcessingBuilder().Create();
mediaDependencies.video_encoder_factory = CreateEncoderFactory(useNullCodec);
mediaDependencies.video_decoder_factory = CreateDecoderFactory(useNullCodec);
dependencies.media_engine = cricket::CreateMediaEngine(std::move(mediaDependencies));
return dependencies;
}
/* ---------------------------------------------------------------------------
** Constructor
** -------------------------------------------------------------------------*/
PeerConnectionManager::PeerConnectionManager(const std::list<std::string> &iceServerList, const Json::Value & config, const webrtc::AudioDeviceModule::AudioLayer audioLayer, const std::string &publishFilter, const std::string & webrtcUdpPortRange, bool useNullCodec, bool usePlanB)
: m_signalingThread(rtc::Thread::Create()),
m_workerThread(rtc::Thread::Create()),
m_audioDecoderfactory(webrtc::CreateBuiltinAudioDecoderFactory()),
m_task_queue_factory(webrtc::CreateDefaultTaskQueueFactory()),
m_video_decoder_factory(CreateDecoderFactory(useNullCodec)),
m_iceServerList(iceServerList),
m_config(config),
m_publishFilter(publishFilter),
m_webrtcPortRange(webrtcUdpPortRange),
m_useNullCodec(useNullCodec),
m_usePlanB(usePlanB)
{
m_workerThread->SetName("worker", NULL);
m_workerThread->Start();
m_workerThread->Invoke<void>(RTC_FROM_HERE, [this, audioLayer] {
this->createAudioModule(audioLayer);
});
m_signalingThread->SetName("signaling", NULL);
m_signalingThread->Start();
m_peer_connection_factory = webrtc::CreateModularPeerConnectionFactory(CreatePeerConnectionFactoryDependencies(m_signalingThread.get(), m_workerThread.get(), m_audioDeviceModule, m_audioDecoderfactory, useNullCodec));
// build video audio map
m_videoaudiomap = getV4l2AlsaMap();
// register api in http server
m_func["/api/getMediaList"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
return this->getMediaList();
};
m_func["/api/getVideoDeviceList"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
return this->getVideoDeviceList();
};
m_func["/api/getAudioDeviceList"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
return this->getAudioDeviceList();
};
m_func["/api/getIceServers"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
return this->getIceServers(req_info->remote_addr);
};
m_func["/api/call"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
std::string peerid;
std::string url;
std::string audiourl;
std::string options;
if (req_info->query_string)
{
CivetServer::getParam(req_info->query_string, "peerid", peerid);
CivetServer::getParam(req_info->query_string, "url", url);
CivetServer::getParam(req_info->query_string, "audiourl", audiourl);
CivetServer::getParam(req_info->query_string, "options", options);
}
return this->call(peerid, url, audiourl, options, in);
};
m_func["/api/hangup"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
std::string peerid;
if (req_info->query_string)
{
CivetServer::getParam(req_info->query_string, "peerid", peerid);
}
return this->hangUp(peerid);
};
m_func["/api/createOffer"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
std::string peerid;
std::string url;
std::string audiourl;
std::string options;
if (req_info->query_string)
{
CivetServer::getParam(req_info->query_string, "peerid", peerid);
CivetServer::getParam(req_info->query_string, "url", url);
CivetServer::getParam(req_info->query_string, "audiourl", audiourl);
CivetServer::getParam(req_info->query_string, "options", options);
}
return this->createOffer(peerid, url, audiourl, options);
};
m_func["/api/setAnswer"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
std::string peerid;
if (req_info->query_string)
{
CivetServer::getParam(req_info->query_string, "peerid", peerid);
}
return this->setAnswer(peerid, in);
};
m_func["/api/getIceCandidate"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
std::string peerid;
if (req_info->query_string)
{
CivetServer::getParam(req_info->query_string, "peerid", peerid);
}
return this->getIceCandidateList(peerid);
};
m_func["/api/addIceCandidate"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
std::string peerid;
if (req_info->query_string)
{
CivetServer::getParam(req_info->query_string, "peerid", peerid);
}
return this->addIceCandidate(peerid, in);
};
m_func["/api/getPeerConnectionList"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
return this->getPeerConnectionList();
};
m_func["/api/getStreamList"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
return this->getStreamList();
};
m_func["/api/version"] = [](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
Json::Value answer(VERSION);
return answer;
};
m_func["/api/log"] = [](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
std::string loglevel;
if (req_info->query_string)
{
CivetServer::getParam(req_info->query_string, "level", loglevel);
if (!loglevel.empty())
{
rtc::LogMessage::LogToDebug((rtc::LoggingSeverity)atoi(loglevel.c_str()));
}
}
Json::Value answer(rtc::LogMessage::GetLogToDebug());
return answer;
};
m_func["/api/help"] = [this](const struct mg_request_info *req_info, const Json::Value &in) -> Json::Value {
Json::Value answer;
for (auto it : m_func)
{
answer.append(it.first);
}
return answer;
};
}
/* ---------------------------------------------------------------------------
** Destructor
** -------------------------------------------------------------------------*/
PeerConnectionManager::~PeerConnectionManager()
{
}
void PeerConnectionManager::createAudioModule(webrtc::AudioDeviceModule::AudioLayer audioLayer) {
#ifdef HAVE_SOUND
m_audioDeviceModule = webrtc::AudioDeviceModule::Create(audioLayer, m_task_queue_factory.get());
if (m_audioDeviceModule->Init() != 0) {
RTC_LOG(LS_WARNING) << "audio init fails -> disable audio capture";
m_audioDeviceModule = new webrtc::FakeAudioDeviceModule();
}
#else
m_audioDeviceModule = new webrtc::FakeAudioDeviceModule();
#endif
}
/* ---------------------------------------------------------------------------
** return deviceList as JSON vector
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getMediaList()
{
Json::Value value(Json::arrayValue);
const std::list<std::string> videoCaptureDevice = CapturerFactory::GetVideoCaptureDeviceList(m_publishFilter, m_useNullCodec);
for (auto videoDevice : videoCaptureDevice)
{
Json::Value media;
media["video"] = videoDevice;
std::map<std::string, std::string>::iterator it = m_videoaudiomap.find(videoDevice);
if (it != m_videoaudiomap.end())
{
media["audio"] = it->second;
}
value.append(media);
}
const std::list<std::string> videoList = CapturerFactory::GetVideoSourceList(m_publishFilter, m_useNullCodec);
for (auto videoSource : videoList)
{
Json::Value media;
media["video"] = videoSource;
value.append(media);
}
for( auto it = m_config.begin() ; it != m_config.end() ; it++ ) {
std::string name = it.key().asString();
Json::Value media(*it);
if (media.isMember("video")) {
media["video"]=name;
}
if (media.isMember("audio")) {
media["audio"]=name;
}
value.append(media);
}
return value;
}
/* ---------------------------------------------------------------------------
** return video device List as JSON vector
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getVideoDeviceList()
{
Json::Value value(Json::arrayValue);
const std::list<std::string> videoCaptureDevice = CapturerFactory::GetVideoCaptureDeviceList(m_publishFilter, m_useNullCodec);
for (auto videoDevice : videoCaptureDevice)
{
value.append(videoDevice);
}
return value;
}
/* ---------------------------------------------------------------------------
** return audio device List as JSON vector
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getAudioDeviceList()
{
Json::Value value(Json::arrayValue);
const std::list<std::string> audioCaptureDevice = CapturerFactory::GetAudioCaptureDeviceList(m_publishFilter, m_audioDeviceModule);
for (auto audioDevice : audioCaptureDevice)
{
value.append(audioDevice);
}
return value;
}
/* ---------------------------------------------------------------------------
** return iceServers as JSON vector
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getIceServers(const std::string &clientIp)
{
Json::Value urls(Json::arrayValue);
for (auto iceServer : m_iceServerList)
{
Json::Value server;
Json::Value urlList(Json::arrayValue);
IceServer srv = getIceServerFromUrl(iceServer, clientIp);
RTC_LOG(LS_INFO) << "ICE URL:" << srv.url;
urlList.append(srv.url);
server["urls"] = urlList;
if (srv.user.length() > 0)
server["username"] = srv.user;
if (srv.pass.length() > 0)
server["credential"] = srv.pass;
urls.append(server);
}
Json::Value iceServers;
iceServers["iceServers"] = urls;
return iceServers;
}
/* ---------------------------------------------------------------------------
** get PeerConnection associated with peerid
** -------------------------------------------------------------------------*/
rtc::scoped_refptr<webrtc::PeerConnectionInterface> PeerConnectionManager::getPeerConnection(const std::string &peerid)
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection;
std::map<std::string, PeerConnectionObserver *>::iterator it = m_peer_connectionobs_map.find(peerid);
if (it != m_peer_connectionobs_map.end())
{
peerConnection = it->second->getPeerConnection();
}
return peerConnection;
}
/* ---------------------------------------------------------------------------
** add ICE candidate to a PeerConnection
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::addIceCandidate(const std::string &peerid, const Json::Value &jmessage)
{
bool result = false;
std::string sdp_mid;
int sdp_mlineindex = 0;
std::string sdp;
if (!rtc::GetStringFromJsonObject(jmessage, kCandidateSdpMidName, &sdp_mid) || !rtc::GetIntFromJsonObject(jmessage, kCandidateSdpMlineIndexName, &sdp_mlineindex) || !rtc::GetStringFromJsonObject(jmessage, kCandidateSdpName, &sdp))
{
RTC_LOG(LS_WARNING) << "Can't parse received message:" << jmessage;
}
else
{
std::unique_ptr<webrtc::IceCandidateInterface> candidate(webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp, NULL));
if (!candidate.get())
{
RTC_LOG(LS_WARNING) << "Can't parse received candidate message.";
}
else
{
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = this->getPeerConnection(peerid);
if (peerConnection)
{
if (!peerConnection->AddIceCandidate(candidate.get()))
{
RTC_LOG(LS_WARNING) << "Failed to apply the received candidate";
}
else
{
result = true;
}
}
}
}
Json::Value answer;
if (result)
{
answer = result;
}
return answer;
}
/* ---------------------------------------------------------------------------
** create an offer for a call
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::createOffer(const std::string &peerid, const std::string &videourl, const std::string &audiourl, const std::string &options)
{
RTC_LOG(LS_INFO) << __FUNCTION__ << " video:" << videourl << " audio:" << audiourl << " options:" << options;
Json::Value offer;
PeerConnectionObserver *peerConnectionObserver = this->CreatePeerConnection(peerid);
if (!peerConnectionObserver)
{
RTC_LOG(LS_ERROR) << "Failed to initialize PeerConnection";
}
else
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = peerConnectionObserver->getPeerConnection();
if (!this->AddStreams(peerConnection, videourl, audiourl, options))
{
RTC_LOG(LS_WARNING) << "Can't add stream";
}
// register peerid
{
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
m_peer_connectionobs_map.insert(std::pair<std::string, PeerConnectionObserver *>(peerid, peerConnectionObserver));
}
// ask to create offer
webrtc::PeerConnectionInterface::RTCOfferAnswerOptions rtcoptions;
rtcoptions.offer_to_receive_video = 0;
rtcoptions.offer_to_receive_audio = 0;
std::promise<const webrtc::SessionDescriptionInterface *> localpromise;
rtc::scoped_refptr<CreateSessionDescriptionObserver> localSessionObserver(CreateSessionDescriptionObserver::Create(peerConnection, localpromise));
peerConnection->CreateOffer(localSessionObserver, rtcoptions);
// waiting for offer
std::future<const webrtc::SessionDescriptionInterface *> future = localpromise.get_future();
if (future.wait_for(std::chrono::milliseconds(5000)) == std::future_status::ready)
{
// answer with the created offer
const webrtc::SessionDescriptionInterface *desc = future.get();
if (desc)
{
std::string sdp;
desc->ToString(&sdp);
offer[kSessionDescriptionTypeName] = desc->type();
offer[kSessionDescriptionSdpName] = sdp;
}
else
{
RTC_LOG(LS_ERROR) << "Failed to create offer - no session";
}
}
else
{
localSessionObserver->cancel();
RTC_LOG(LS_ERROR) << "Failed to create offer - timeout";
}
}
return offer;
}
/* ---------------------------------------------------------------------------
** set answer to a call initiated by createOffer
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::setAnswer(const std::string &peerid, const Json::Value &jmessage)
{
RTC_LOG(LS_INFO) << jmessage;
Json::Value answer;
std::string type;
std::string sdp;
if (!rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionTypeName, &type) || !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionSdpName, &sdp))
{
RTC_LOG(LS_WARNING) << "Can't parse received message.";
answer["error"] = "Can't parse received message.";
}
else
{
webrtc::SessionDescriptionInterface *session_description(webrtc::CreateSessionDescription(type, sdp, NULL));
if (!session_description)
{
RTC_LOG(LS_WARNING) << "Can't parse received session description message.";
answer["error"] = "Can't parse received session description message.";
}
else
{
RTC_LOG(LS_ERROR) << "From peerid:" << peerid << " received session description :" << session_description->type();
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = this->getPeerConnection(peerid);
if (peerConnection)
{
std::promise<const webrtc::SessionDescriptionInterface *> remotepromise;
rtc::scoped_refptr<SetSessionDescriptionObserver> remoteSessionObserver(SetSessionDescriptionObserver::Create(peerConnection, remotepromise));
peerConnection->SetRemoteDescription(remoteSessionObserver, session_description);
// waiting for remote description
std::future<const webrtc::SessionDescriptionInterface *> remotefuture = remotepromise.get_future();
if (remotefuture.wait_for(std::chrono::milliseconds(5000)) == std::future_status::ready)
{
RTC_LOG(LS_INFO) << "remote_description is ready";
const webrtc::SessionDescriptionInterface *desc = remotefuture.get();
if (desc)
{
std::string sdp;
desc->ToString(&sdp);
answer[kSessionDescriptionTypeName] = desc->type();
answer[kSessionDescriptionSdpName] = sdp;
} else {
answer["error"] = "Can't get remote description.";
}
}
else
{
remoteSessionObserver->cancel();
RTC_LOG(LS_WARNING) << "Can't get remote description.";
answer["error"] = "Can't get remote description.";
}
}
}
}
return answer;
}
/* ---------------------------------------------------------------------------
** auto-answer to a call
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::call(const std::string &peerid, const std::string &videourl, const std::string &audiourl, const std::string &options, const Json::Value &jmessage)
{
RTC_LOG(LS_INFO) << __FUNCTION__ << " video:" << videourl << " audio:" << audiourl << " options:" << options;
Json::Value answer;
std::string type;
std::string sdp;
if (!rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionTypeName, &type) || !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionSdpName, &sdp))
{
RTC_LOG(LS_WARNING) << "Can't parse received message.";
}
else
{
PeerConnectionObserver *peerConnectionObserver = this->CreatePeerConnection(peerid);
if (!peerConnectionObserver)
{
RTC_LOG(LS_ERROR) << "Failed to initialize PeerConnectionObserver";
}
else if (!peerConnectionObserver->getPeerConnection().get())
{
RTC_LOG(LS_ERROR) << "Failed to initialize PeerConnection";
delete peerConnectionObserver;
}
else
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = peerConnectionObserver->getPeerConnection();
RTC_LOG(LS_INFO) << "nbStreams local:" << peerConnection->GetSenders().size() << " remote:" << peerConnection->GetReceivers().size() << " localDescription:" << peerConnection->local_description();
// register peerid
{
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
m_peer_connectionobs_map.insert(std::pair<std::string, PeerConnectionObserver *>(peerid, peerConnectionObserver));
}
// set remote offer
webrtc::SessionDescriptionInterface *session_description(webrtc::CreateSessionDescription(type, sdp, NULL));
if (!session_description)
{
RTC_LOG(LS_WARNING) << "Can't parse received session description message.";
}
else
{
std::promise<const webrtc::SessionDescriptionInterface *> remotepromise;
rtc::scoped_refptr<SetSessionDescriptionObserver> remoteSessionObserver(SetSessionDescriptionObserver::Create(peerConnection, remotepromise));
peerConnection->SetRemoteDescription(remoteSessionObserver, session_description);
// waiting for remote description
std::future<const webrtc::SessionDescriptionInterface *> remotefuture = remotepromise.get_future();
if (remotefuture.wait_for(std::chrono::milliseconds(5000)) == std::future_status::ready)
{
RTC_LOG(LS_INFO) << "remote_description is ready";
}
else
{
remoteSessionObserver->cancel();
RTC_LOG(LS_WARNING) << "remote_description is NULL";
}
}
// add local stream
if (!this->AddStreams(peerConnection, videourl, audiourl, options))
{
RTC_LOG(LS_WARNING) << "Can't add stream";
}
// create answer
webrtc::PeerConnectionInterface::RTCOfferAnswerOptions rtcoptions;
std::promise<const webrtc::SessionDescriptionInterface *> localpromise;
rtc::scoped_refptr<CreateSessionDescriptionObserver> localSessionObserver(CreateSessionDescriptionObserver::Create(peerConnection, localpromise));
peerConnection->CreateAnswer(localSessionObserver, rtcoptions);
// waiting for answer
std::future<const webrtc::SessionDescriptionInterface *> localfuture = localpromise.get_future();
if (localfuture.wait_for(std::chrono::milliseconds(5000)) == std::future_status::ready)
{
// answer with the created answer
const webrtc::SessionDescriptionInterface *desc = localfuture.get();
if (desc)
{
std::string sdp;
desc->ToString(&sdp);
answer[kSessionDescriptionTypeName] = desc->type();
answer[kSessionDescriptionSdpName] = sdp;
}
else
{
RTC_LOG(LS_ERROR) << "Failed to create answer - no SDP";
}
}
else
{
RTC_LOG(LS_ERROR) << "Failed to create answer - timeout";
localSessionObserver->cancel();
}
}
}
return answer;
}
bool PeerConnectionManager::streamStillUsed(const std::string &streamLabel)
{
bool stillUsed = false;
for (auto it : m_peer_connectionobs_map)
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = it.second->getPeerConnection();
std::vector<rtc::scoped_refptr<webrtc::RtpSenderInterface>> localstreams = peerConnection->GetSenders();
for (auto stream : localstreams)
{
std::vector<std::string> streamVector = stream->stream_ids();
if (streamVector.size() > 0) {
if (streamVector[0] == streamLabel)
{
stillUsed = true;
break;
}
}
}
}
return stillUsed;
}
/* ---------------------------------------------------------------------------
** hangup a call
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::hangUp(const std::string &peerid)
{
bool result = false;
RTC_LOG(LS_INFO) << __FUNCTION__ << " " << peerid;
PeerConnectionObserver *pcObserver = NULL;
{
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
std::map<std::string, PeerConnectionObserver *>::iterator it = m_peer_connectionobs_map.find(peerid);
if (it != m_peer_connectionobs_map.end())
{
pcObserver = it->second;
RTC_LOG(LS_ERROR) << "Remove PeerConnection peerid:" << peerid;
m_peer_connectionobs_map.erase(it);
}
if (pcObserver)
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = pcObserver->getPeerConnection();
std::vector<rtc::scoped_refptr<webrtc::RtpSenderInterface>> localstreams = peerConnection->GetSenders();
for (auto stream : localstreams)
{
std::vector<std::string> streamVector = stream->stream_ids();
if (streamVector.size() > 0) {
std::string streamLabel = streamVector[0];
bool stillUsed = this->streamStillUsed(streamLabel);
if (!stillUsed)
{
RTC_LOG(LS_ERROR) << "hangUp stream is no more used " << streamLabel;
std::lock_guard<std::mutex> mlock(m_streamMapMutex);
std::map<std::string, std::pair<rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>, rtc::scoped_refptr<webrtc::AudioSourceInterface>>>::iterator it = m_stream_map.find(streamLabel);
if (it != m_stream_map.end())
{
m_stream_map.erase(it);
}
RTC_LOG(LS_ERROR) << "hangUp stream closed " << streamLabel;
}
peerConnection->RemoveTrackOrError(stream);
}
}
delete pcObserver;
result = true;
}
}
Json::Value answer;
if (result)
{
answer = result;
}
RTC_LOG(LS_INFO) << __FUNCTION__ << " " << peerid << " result:" << result;
return answer;
}
/* ---------------------------------------------------------------------------
** get list ICE candidate associayed with a PeerConnection
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getIceCandidateList(const std::string &peerid)
{
RTC_LOG(LS_INFO) << __FUNCTION__;
Json::Value value;
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
std::map<std::string, PeerConnectionObserver *>::iterator it = m_peer_connectionobs_map.find(peerid);
if (it != m_peer_connectionobs_map.end())
{
PeerConnectionObserver *obs = it->second;
if (obs)
{
value = obs->getIceCandidateList();
}
else
{
RTC_LOG(LS_ERROR) << "No observer for peer:" << peerid;
}
}
return value;
}
/* ---------------------------------------------------------------------------
** get PeerConnection list
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getPeerConnectionList()
{
Json::Value value(Json::arrayValue);
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
for (auto it : m_peer_connectionobs_map)
{
Json::Value content;
// get local SDP
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = it.second->getPeerConnection();
if ((peerConnection) && (peerConnection->local_description()))
{
content["pc_state"] = (int)(peerConnection->peer_connection_state());
content["signaling_state"] = (int)(peerConnection->signaling_state());
content["ice_state"] = (int)(peerConnection->ice_connection_state());
std::string sdp;
peerConnection->local_description()->ToString(&sdp);
content["sdp"] = sdp;
Json::Value streams;
std::vector<rtc::scoped_refptr<webrtc::RtpSenderInterface>> localstreams = peerConnection->GetSenders();
for (auto localStream : localstreams)
{
if (localStream != NULL)
{
rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> mediaTrack = localStream->track();
if (mediaTrack) {
Json::Value track;
track["kind"] = mediaTrack->kind();
if (track["kind"] == "video") {
webrtc::VideoTrackInterface* videoTrack = (webrtc::VideoTrackInterface*)mediaTrack.get();
webrtc::VideoTrackSourceInterface::Stats stats;
if (videoTrack->GetSource())
{
track["state"] = videoTrack->GetSource()->state();
if (videoTrack->GetSource()->GetStats(&stats))
{
track["width"] = stats.input_width;
track["height"] = stats.input_height;
}
}
} else if (track["kind"] == "audio") {
webrtc::AudioTrackInterface* audioTrack = (webrtc::AudioTrackInterface*)mediaTrack.get();
if (audioTrack->GetSource())
{
track["state"] = audioTrack->GetSource()->state();
}
int level = 0;
if (audioTrack->GetSignalLevel(&level)) {
track["level"] = level;
}
}
Json::Value tracks;
tracks[mediaTrack->id()] = track;
std::string streamLabel = localStream->stream_ids()[0];
streams[streamLabel] = tracks;
}
}
}
content["streams"] = streams;
}
// get Stats
// content["stats"] = it.second->getStats();
Json::Value pc;
pc[it.first] = content;
value.append(pc);
}
return value;
}
/* ---------------------------------------------------------------------------
** get StreamList list
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getStreamList()
{
std::lock_guard<std::mutex> mlock(m_streamMapMutex);
Json::Value value(Json::arrayValue);
for (auto it : m_stream_map)
{
value.append(it.first);
}
return value;
}
/* ---------------------------------------------------------------------------
** check if factory is initialized
** -------------------------------------------------------------------------*/
bool PeerConnectionManager::InitializePeerConnection()
{
return (m_peer_connection_factory.get() != NULL);
}
/* ---------------------------------------------------------------------------
** create a new PeerConnection
** -------------------------------------------------------------------------*/
PeerConnectionManager::PeerConnectionObserver *PeerConnectionManager::CreatePeerConnection(const std::string &peerid)
{
webrtc::PeerConnectionInterface::RTCConfiguration config;
if (m_usePlanB) {
config.sdp_semantics = webrtc::SdpSemantics::kPlanB;
} else {
config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan;
}
for (auto iceServer : m_iceServerList)
{
webrtc::PeerConnectionInterface::IceServer server;
IceServer srv = getIceServerFromUrl(iceServer);
server.uri = srv.url;
server.username = srv.user;
server.password = srv.pass;
config.servers.push_back(server);
}
// Use example From https://soru.site/questions/51578447/api-c-webrtcyi-kullanarak-peerconnection-ve-ucretsiz-baglant-noktasn-serbest-nasl
int minPort = 0;
int maxPort = 65535;
std::istringstream is(m_webrtcPortRange);
std::string port;
if (std::getline(is, port, ':')) {
minPort = std::stoi(port);
if (std::getline(is, port, ':')) {
maxPort = std::stoi(port);
}
}
RTC_LOG(LS_INFO) << __FUNCTION__ << "CreatePeerConnection webrtcPortRange:" << minPort << ":" << maxPort;
RTC_LOG(LS_INFO) << __FUNCTION__ << "CreatePeerConnection peerid:" << peerid;
PeerConnectionObserver *obs = new PeerConnectionObserver(this, peerid, config, minPort, maxPort);
if (!obs)
{
RTC_LOG(LS_ERROR) << __FUNCTION__ << "CreatePeerConnection failed";
}
return obs;
}
/* ---------------------------------------------------------------------------
** get the capturer from its URL
** -------------------------------------------------------------------------*/
rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> PeerConnectionManager::CreateVideoSource(const std::string &videourl, const std::map<std::string, std::string> &opts)
{
RTC_LOG(LS_INFO) << "videourl:" << videourl;
std::string video = videourl;
if (m_config.isMember(video)) {
video = m_config[video]["video"].asString();
}
return CapturerFactory::CreateVideoSource(video, opts, m_publishFilter, m_peer_connection_factory, m_video_decoder_factory);
}
rtc::scoped_refptr<webrtc::AudioSourceInterface> PeerConnectionManager::CreateAudioSource(const std::string &audiourl, const std::map<std::string, std::string> &opts)
{
RTC_LOG(LS_INFO) << "audiourl:" << audiourl;
std::string audio = audiourl;
if (m_config.isMember(audio)) {
audio = m_config[audio]["audio"].asString();
}
std::map<std::string, std::string>::iterator it = m_videoaudiomap.find(audio);
if (it != m_videoaudiomap.end())
{
audio = it->second;
}
return m_workerThread->Invoke<rtc::scoped_refptr<webrtc::AudioSourceInterface>>(RTC_FROM_HERE, [this, audio, opts] {
return CapturerFactory::CreateAudioSource(audio, opts, m_publishFilter, m_peer_connection_factory, m_audioDecoderfactory, m_audioDeviceModule);
});
}
const std::string PeerConnectionManager::sanitizeLabel(const std::string &label)
{
std::string out(label);
// conceal labels that contain rtsp URL to prevent sensitive data leaks.
if (label.find("rtsp:") != std::string::npos)
{
std::hash<std::string> hash_fn;
size_t hash = hash_fn(out);
return std::to_string(hash);
}
out.erase(std::remove_if(out.begin(), out.end(), ignoreInLabel), out.end());
return out;
}
/* ---------------------------------------------------------------------------
** Add a stream to a PeerConnection
** -------------------------------------------------------------------------*/
bool PeerConnectionManager::AddStreams(webrtc::PeerConnectionInterface *peer_connection, const std::string &videourl, const std::string &audiourl, const std::string &options)
{
bool ret = false;
// compute options
std::string optstring = options;
if (m_config.isMember(videourl)) {
std::string urlopts = m_config[videourl]["options"].asString();
if (options.empty()) {
optstring = urlopts;
} else if (options.find_first_of("&")==0) {
optstring = urlopts + options;
} else {
optstring = options;
}
}
// convert options string into map
std::istringstream is(optstring);
std::map<std::string, std::string> opts;
std::string key, value;
while (std::getline(std::getline(is, key, '='), value, '&'))
{
opts[key] = value;
}
std::string video = videourl;
if (m_config.isMember(video)) {
video = m_config[video]["video"].asString();
}
// compute audiourl if not set
std::string audio(audiourl);
if (audio.empty())
{
audio = videourl;
}
// set bandwidth
if (opts.find("bitrate") != opts.end())
{
int bitrate = std::stoi(opts.at("bitrate"));
webrtc::BitrateSettings bitrateParam;
bitrateParam.min_bitrate_bps = absl::optional<int>(bitrate / 2);
bitrateParam.start_bitrate_bps = absl::optional<int>(bitrate);
bitrateParam.max_bitrate_bps = absl::optional<int>(bitrate * 2);
peer_connection->SetBitrate(bitrateParam);
RTC_LOG(LS_WARNING) << "set bitrate:" << bitrate;
}
// keep capturer options (to improve!!!)
std::string optcapturer;
if ((video.find("rtsp://") == 0) || (audio.find("rtsp://") == 0))
{
if (opts.find("rtptransport") != opts.end())
{
optcapturer += opts["rtptransport"];
}
if (opts.find("timeout") != opts.end())
{
optcapturer += opts["timeout"];
}
}
// compute stream label removing space because SDP use label
std::string streamLabel = this->sanitizeLabel(videourl + "|" + audiourl + "|" + optcapturer);
bool existingStream = false;
{
std::lock_guard<std::mutex> mlock(m_streamMapMutex);
existingStream = (m_stream_map.find(streamLabel) != m_stream_map.end());
}
if (!existingStream)
{
// need to create the stream
rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> videoSource(this->CreateVideoSource(video, opts));
rtc::scoped_refptr<webrtc::AudioSourceInterface> audioSource(this->CreateAudioSource(audio, opts));
RTC_LOG(LS_INFO) << "Adding Stream to map";
std::lock_guard<std::mutex> mlock(m_streamMapMutex);
m_stream_map[streamLabel] = std::make_pair(videoSource, audioSource);
}
// create a new webrtc stream
{
std::lock_guard<std::mutex> mlock(m_streamMapMutex);
std::map<std::string, std::pair<rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>, rtc::scoped_refptr<webrtc::AudioSourceInterface>>>::iterator it = m_stream_map.find(streamLabel);
if (it != m_stream_map.end())
{
std::pair<rtc::scoped_refptr<webrtc::VideoTrackSourceInterface>, rtc::scoped_refptr<webrtc::AudioSourceInterface>> pair = it->second;
rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> videoSource(pair.first);
if (!videoSource)
{
RTC_LOG(LS_ERROR) << "Cannot create capturer video:" << videourl;
}
else
{
rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> videoScaled = VideoFilter<VideoScaler>::Create(videoSource, opts);
rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track = m_peer_connection_factory->CreateVideoTrack(streamLabel + "_video", videoScaled);
if ((video_track) && (!peer_connection->AddTrack(video_track, {streamLabel}).ok()))
{
RTC_LOG(LS_ERROR) << "Adding VideoTrack to MediaStream failed";
}
else
{
RTC_LOG(LS_INFO) << "VideoTrack added to PeerConnection";
ret = true;
}
}
rtc::scoped_refptr<webrtc::AudioSourceInterface> audioSource(pair.second);
if (!audioSource)
{
RTC_LOG(LS_ERROR) << "Cannot create capturer audio:" << audio;
}
else
{
rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track = m_peer_connection_factory->CreateAudioTrack(streamLabel + "_audio", audioSource);
if ((audio_track) && (!peer_connection->AddTrack(audio_track, {streamLabel}).ok()))
{
RTC_LOG(LS_ERROR) << "Adding AudioTrack to MediaStream failed";
}
else
{
RTC_LOG(LS_INFO) << "AudioTrack added to PeerConnection";
ret = true;
}
}
}
else
{
RTC_LOG(LS_ERROR) << "Cannot find stream";
}
}
return ret;
}
/* ---------------------------------------------------------------------------
** ICE callback
** -------------------------------------------------------------------------*/
void PeerConnectionManager::PeerConnectionObserver::OnIceCandidate(const webrtc::IceCandidateInterface *candidate)
{
RTC_LOG(LS_INFO) << __FUNCTION__ << " " << candidate->sdp_mline_index();
std::string sdp;
if (!candidate->ToString(&sdp))
{
RTC_LOG(LS_ERROR) << "Failed to serialize candidate";
}
else
{
RTC_LOG(LS_INFO) << sdp;
Json::Value jmessage;
jmessage[kCandidateSdpMidName] = candidate->sdp_mid();
jmessage[kCandidateSdpMlineIndexName] = candidate->sdp_mline_index();
jmessage[kCandidateSdpName] = sdp;
m_iceCandidateList.append(jmessage);
}
}
|
/*=============================================================================
Copyright (c) 2011-2015 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_ALGORITHM_SEARCHING_HPP
#define SPROUT_ALGORITHM_SEARCHING_HPP
#include <sprout/config.hpp>
#include <sprout/algorithm/searching/default_searcher.hpp>
#endif // #ifndef SPROUT_ALGORITHM_SEARCHING_HPP
|
// Copyright 2018 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/process/process_memory_win.h"
#include <windows.h>
#include <algorithm>
#include <limits>
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "base/process/process_metrics.h"
#include "base/strings/stringprintf.h"
namespace crashpad {
ProcessMemoryWin::ProcessMemoryWin()
: ProcessMemory(), handle_(), process_info_(), initialized_() {}
ProcessMemoryWin::~ProcessMemoryWin() {}
bool ProcessMemoryWin::Initialize(HANDLE handle) {
INITIALIZATION_STATE_SET_INITIALIZING(initialized_);
handle_ = handle;
if (!process_info_.Initialize(handle)) {
LOG(ERROR) << "Failed to initialize ProcessInfo.";
return false;
}
INITIALIZATION_STATE_SET_VALID(initialized_);
return true;
}
ssize_t ProcessMemoryWin::ReadUpTo(VMAddress address,
size_t size,
void* buffer) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
DCHECK_LE(size, (size_t)std::numeric_limits<ssize_t>::max());
SIZE_T size_out = 0;
BOOL success = ReadProcessMemory(
handle_, reinterpret_cast<void*>(address), buffer, size, &size_out);
if (success)
return base::checked_cast<ssize_t>(size_out);
if (GetLastError() == ERROR_PARTIAL_COPY) {
// If we can not read the entire section, perform a short read of the first
// page instead. This is necessary to support ReadCString().
size_t short_read =
base::GetPageSize() - (address & (base::GetPageSize() - 1));
success = ReadProcessMemory(handle_,
reinterpret_cast<void*>(address),
buffer,
short_read,
&size_out);
if (success)
return base::checked_cast<ssize_t>(size_out);
}
PLOG(ERROR) << "ReadMemory at 0x" << std::hex << address << std::dec << " of "
<< size << " bytes failed";
return -1;
}
size_t ProcessMemoryWin::ReadAvailableMemory(VMAddress address,
size_t size,
void* buffer) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
DCHECK_LE(size, (size_t)std::numeric_limits<ssize_t>::max());
if (size == 0)
return 0;
auto ranges = process_info_.GetReadableRanges(
CheckedRange<WinVMAddress, WinVMSize>(address, size));
// We only read up until the first unavailable byte, so we only read from the
// first range. If we have no ranges, then no bytes were accessible anywhere
// in the range.
if (ranges.empty()) {
LOG(ERROR) << base::StringPrintf(
"range at 0x%llx, size 0x%zx completely inaccessible", address, size);
return 0;
}
// If the start address was adjusted, we couldn't read even the first
// requested byte.
if (ranges.front().base() != address) {
LOG(ERROR) << base::StringPrintf(
"start of range at 0x%llx, size 0x%zx inaccessible", address, size);
return 0;
}
DCHECK_LE(ranges.front().size(), size);
ssize_t result = ReadUpTo(ranges.front().base(),
base::checked_cast<size_t>(ranges.front().size()),
buffer);
if (result < 0)
return 0;
return base::checked_cast<size_t>(result);
}
} // namespace crashpad
|
#include <iostream>
#include <vector>
using namespace std;
pair<int, int> minmax(vector<int> arr)
{
int maxima = INT_MIN;
int minima = INT_MAX;
int n = arr.size();
int i = 0;
int j = n - 1;
while (i < n && j >= 0)
{
maxima = max(maxima, arr[i]);
minima = min(minima, arr[j]);
i++;
j--;
}
return {maxima, minima};
}
int main()
{
vector<int> arr = {4, 2, 7, 9, 6, 0, 5, 1, 12};
auto p = minmax(arr);
cout << "[Max,Min] -> [" << p.first << "," << p.second << "]" << endl;
return 0;
}
|
/*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Engine.
**
** Centreon Engine is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Engine is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Engine. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <exception>
#include "com/centreon/engine/exceptions/error.hh"
#include "com/centreon/engine/globals.hh"
#include "com/centreon/engine/modules/external_commands/commands.hh"
#include "com/centreon/logging/engine.hh"
#include "test/unittest.hh"
using namespace com::centreon::engine;
/**
* Run change_custom_host_var test.
*/
static int check_change_custom_host_var(int argc, char** argv) {
(void)argc;
(void)argv;
host* hst =
add_host("name", NULL, NULL, "localhost", NULL, 0, 0.0, 0.0, 42, 0, 0, 0,
0, 0, 0.0, 0.0, NULL, 0, NULL, 0, 0, NULL, 0, 0, 0.0, 0.0, 0, 0,
0, 0, 0, 0, 0, 0, NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, 0, 0, 0, 0.0, 0.0, 0.0, 0, 0, 0, 0, 0);
if (!hst)
throw(engine_error() << "create host failed.");
customvariablesmember* member =
add_custom_variable_to_host(hst, "_VAR", "TEST");
if (!member)
throw(engine_error() << "create customvariablesmember failed.");
char const* cmd("[1317196300] CHANGE_CUSTOM_HOST_VAR;name;_VAR;VALUE");
process_external_command(cmd);
if (strcmp(member->variable_value, "VALUE"))
throw(engine_error() << "change_custom_host_var failed.");
return (0);
}
/**
* Init unit test.
*/
int main(int argc, char** argv) {
unittest utest(argc, argv, &check_change_custom_host_var);
return (utest.run());
}
|
// Copyright (C) 2005 Arkadiy Vertleyb
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_TYPEOF_INTEGRAL_TEMPLATE_PARAM_HPP_INCLUDED
#define BOOST_TYPEOF_INTEGRAL_TEMPLATE_PARAM_HPP_INCLUDED
#define BOOST_TYPEOF_unsigned (unsigned)
#define BOOST_TYPEOF_signed (signed)
#define char_BOOST_TYPEOF (char)
#define short_BOOST_TYPEOF (short)
#define int_BOOST_TYPEOF (int)
#define long_BOOST_TYPEOF (long)
#define BOOST_TYPEOF_char_BOOST_TYPEOF (char)
#define BOOST_TYPEOF_short_BOOST_TYPEOF (short)
#define BOOST_TYPEOF_int_BOOST_TYPEOF (int)
#define BOOST_TYPEOF_long_BOOST_TYPEOF (long)
#define BOOST_TYPEOF_bool_BOOST_TYPEOF (bool)
#define BOOST_TYPEOF_unsigned_BOOST_TYPEOF (unsigned)
#define BOOST_TYPEOF_size_t_BOOST_TYPEOF (size_t)
#define BOOST_TYPEOF_MAKE_OBJ_char BOOST_TYPEOF_INTEGRAL_PARAM(char)
#define BOOST_TYPEOF_MAKE_OBJ_short BOOST_TYPEOF_INTEGRAL_PARAM(short)
#define BOOST_TYPEOF_MAKE_OBJ_int BOOST_TYPEOF_INTEGRAL_PARAM(int)
#define BOOST_TYPEOF_MAKE_OBJ_long BOOST_TYPEOF_INTEGRAL_PARAM(long)
#define BOOST_TYPEOF_MAKE_OBJ_bool BOOST_TYPEOF_INTEGRAL_PARAM(bool)
#define BOOST_TYPEOF_MAKE_OBJ_unsigned BOOST_TYPEOF_INTEGRAL_PARAM(unsigned)
#define BOOST_TYPEOF_MAKE_OBJ_size_t BOOST_TYPEOF_INTEGRAL_PARAM(size_t)
#define BOOST_TYPEOF_MAKE_OBJ_unsignedchar BOOST_TYPEOF_INTEGRAL_PARAM(unsigned char)
#define BOOST_TYPEOF_MAKE_OBJ_unsignedshort BOOST_TYPEOF_INTEGRAL_PARAM(unsigned short)
#define BOOST_TYPEOF_MAKE_OBJ_unsignedint BOOST_TYPEOF_INTEGRAL_PARAM(unsigned int)
#define BOOST_TYPEOF_MAKE_OBJ_unsignedlong BOOST_TYPEOF_INTEGRAL_PARAM(unsigned long)
#define BOOST_TYPEOF_MAKE_OBJ_signedchar BOOST_TYPEOF_INTEGRAL_PARAM(signed char)
#define BOOST_TYPEOF_MAKE_OBJ_signedshort BOOST_TYPEOF_INTEGRAL_PARAM(signed short)
#define BOOST_TYPEOF_MAKE_OBJ_signedint BOOST_TYPEOF_INTEGRAL_PARAM(signed int)
#define BOOST_TYPEOF_MAKE_OBJ_signedlong BOOST_TYPEOF_INTEGRAL_PARAM(signed long)
#define BOOST_TYPEOF_MAKE_OBJ_integral(x) BOOST_TYPEOF_INTEGRAL_PARAM(x)
#define BOOST_TYPEOF_INTEGRAL(X) integral(X) BOOST_TYPEOF_EAT
#define BOOST_TYPEOF_EAT_BOOST_TYPEOF
#define BOOST_TYPEOF_integral(X) (integral(X))
#define BOOST_TYPEOF_INTEGRAL_PARAM(Type)\
(INTEGRAL_PARAM)\
(Type)
#define BOOST_TYPEOF_INTEGRAL_PARAM_GETTYPE(Param)\
BOOST_PP_SEQ_ELEM(1, Param)
#define BOOST_TYPEOF_INTEGRAL_PARAM_EXPANDTYPE(Param)\
BOOST_TYPEOF_INTEGRAL_PARAM_GETTYPE(Param)
// INTEGRAL_PARAM "virtual functions" implementation
#define BOOST_TYPEOF_INTEGRAL_PARAM_ENCODE(This, n)\
typedef typename mars_boost::type_of::encode_integral<\
BOOST_PP_CAT(V, n),\
BOOST_TYPEOF_INTEGRAL_PARAM_GETTYPE(This),\
BOOST_PP_CAT(P, n)\
>::type BOOST_PP_CAT(V, BOOST_PP_INC(n));
#define BOOST_TYPEOF_INTEGRAL_PARAM_DECODE(This, n)\
typedef mars_boost::type_of::decode_integral<BOOST_TYPEOF_INTEGRAL_PARAM_GETTYPE(This), BOOST_PP_CAT(iter, n)> BOOST_PP_CAT(d, n);\
static const BOOST_TYPEOF_INTEGRAL_PARAM_GETTYPE(This) BOOST_PP_CAT(P, n) = BOOST_PP_CAT(d, n)::value;\
typedef typename BOOST_PP_CAT(d, n)::iter BOOST_PP_CAT(iter, BOOST_PP_INC(n));
#define BOOST_TYPEOF_INTEGRAL_PARAM_PLACEHOLDER(Param)\
(BOOST_TYPEOF_INTEGRAL_PARAM_GETTYPE(Param))0
#define BOOST_TYPEOF_INTEGRAL_PARAM_DECLARATION_TYPE(Param)\
BOOST_TYPEOF_INTEGRAL_PARAM_GETTYPE(Param)
#define BOOST_TYPEOF_INTEGRAL_PARAM_PLACEHOLDER_TYPES(Param, n)\
BOOST_PP_CAT(T,n)
#define BOOST_TYPEOF_INTEGRAL_PARAM_ISTEMPLATE 0
#endif//BOOST_TYPEOF_INTEGRAL_TEMPLATE_PARAM_HPP_INCLUDED
|
// Copyright(c) 2016 Jounayd Id Salah
// Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT).
#include "container/pch.h"
#include "container/string/coChar_f.h"
#define _coCC(_category_) _coCharCategory_##_category_
//-------------------------------------------------------
const coUint16 _coCharCategoryTable[256] =
{
// 0 NUL 1 SOH 2 STX 3 ETX
// 4 EOT 5 ENQ 6 ACK 7 BEL
0, 0, 0, 0,
0, 0, 0, 0,
// 8 BS 9 HT 10 NL 11 VT
//12 NP 13 CR 14 SO 15 SI
0, _coCC(horzws), _coCC(vertws), _coCC(horzws),
_coCC(horzws), _coCC(vertws), 0, 0,
//16 DLE 17 DC1 18 DC2 19 DC3
//20 DC4 21 NAK 22 SYN 23 ETB
0, 0, 0, 0,
0, 0, 0, 0,
//24 CAN 25 EM 26 SUB 27 ESC
//28 FS 29 GS 30 RS 31 US
0, 0, 0, 0,
0, 0, 0, 0,
//32 SP 33 ! 34 " 35 #
//36 $ 37 % 38 & 39 '
_coCC(space), _coCC(rawdel), _coCC(rawdel), _coCC(rawdel),
_coCC(punct), _coCC(rawdel), _coCC(rawdel), _coCC(rawdel),
//40 ( 41 ) 42 * 43 +
//44 , 45 - 46 . 47 /
_coCC(punct), _coCC(punct), _coCC(rawdel), _coCC(sign),
_coCC(rawdel), _coCC(sign), _coCC(period), _coCC(rawdel),
//48 0 49 1 50 2 51 3
//52 4 53 5 54 6 55 7
_coCC(digit), _coCC(digit), _coCC(digit), _coCC(digit),
_coCC(digit), _coCC(digit), _coCC(digit), _coCC(digit),
//56 8 57 9 58 : 59 ;
//60 < 61 = 62 > 63 ?
_coCC(digit), _coCC(digit), _coCC(rawdel), _coCC(rawdel),
_coCC(rawdel), _coCC(rawdel), _coCC(rawdel), _coCC(rawdel),
//64 @ 65 A 66 B 67 C
//68 D 69 E 70 F 71 G
_coCC(punct), _coCC(xupper), _coCC(xupper), _coCC(xupper),
_coCC(xupper), _coCC(xupper), _coCC(xupper), _coCC(upper),
//72 H 73 I 74 J 75 K
//76 L 77 M 78 N 79 O
_coCC(upper), _coCC(upper), _coCC(upper), _coCC(upper),
_coCC(upper), _coCC(upper), _coCC(upper), _coCC(upper),
//80 P 81 Q 82 R 83 S
//84 T 85 U 86 V 87 W
_coCC(upper), _coCC(upper), _coCC(upper), _coCC(upper),
_coCC(upper), _coCC(upper), _coCC(upper), _coCC(upper),
//88 X 89 Y 90 Z 91 [
//92 \ 93 ] 94 ^ 95 _
_coCC(upper), _coCC(upper), _coCC(upper), _coCC(rawdel),
_coCC(punct), _coCC(rawdel), _coCC(rawdel), _coCC(under),
//96 ` 97 a 98 b 99 c
//100 d 101 e 102 f 103 g
_coCC(punct), _coCC(xlower), _coCC(xlower), _coCC(xlower),
_coCC(xlower), _coCC(xlower), _coCC(xlower), _coCC(lower),
//104 h 105 i 106 j 107 k
//108 l 109 m 110 n 111 o
_coCC(lower), _coCC(lower), _coCC(lower), _coCC(lower),
_coCC(lower), _coCC(lower), _coCC(lower), _coCC(lower),
//112 p 113 q 114 r 115 s
//116 t 117 u 118 v 119 w
_coCC(lower), _coCC(lower), _coCC(lower), _coCC(lower),
_coCC(lower), _coCC(lower), _coCC(lower), _coCC(lower),
//120 x 121 y 122 z 123 {
//124 | 125 } 126 ~ 127 DEL
_coCC(lower), _coCC(lower), _coCC(lower), _coCC(rawdel),
_coCC(rawdel), _coCC(rawdel), _coCC(rawdel), 0
};
|
/******************************************************************************\
Copyright (c) 2005-2020, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This sample was distributed or derived from the Intel's Media Samples package.
The original version of this sample may be obtained from https://software.intel.com/en-us/intel-media-server-studio
or https://software.intel.com/en-us/media-client-solutions-support.
\**********************************************************************************/
#include "mfx_samples_config.h"
#include "plugin_utils.h"
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#include <psapi.h>
#include <d3d9.h>
#include "d3d_allocator.h"
#include "d3d11_allocator.h"
#else
#include <stdarg.h>
#include "vaapi_allocator.h"
#endif
#include "sysmem_allocator.h"
#include "transcode_utils.h"
#include "version.h"
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <cctype>
#include <iterator>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace TranscodingSample;
// parsing defines
#define IS_SEPARATOR(ch) ((ch) <= ' ' || (ch) == '=')
#define VAL_CHECK(val, argIdx, argName) \
{ \
if (val) \
{ \
PrintError(MSDK_STRING("Input argument number %d \"%s\" require more parameters"), argIdx, argName); \
return MFX_ERR_UNSUPPORTED;\
} \
}
#define SIZE_CHECK(cond) \
{ \
if (cond) \
{ \
PrintError(MSDK_STRING("Buffer is too small")); \
return MFX_ERR_UNSUPPORTED; \
} \
}
#ifndef MFX_VERSION
#error MFX_VERSION not defined
#endif
msdk_tick TranscodingSample::GetTick()
{
return msdk_time_get_tick();
}
mfxF64 TranscodingSample::GetTime(msdk_tick start)
{
static msdk_tick frequency = msdk_time_get_frequency();
return MSDK_GET_TIME(msdk_time_get_tick(), start, frequency);
}
void TranscodingSample::PrintError(const msdk_char *strErrorMessage, ...)
{
if (strErrorMessage)
{
msdk_printf(MSDK_STRING("ERROR: "));
va_list args;
va_start(args, strErrorMessage);
msdk_vprintf(strErrorMessage, args);
va_end(args);
msdk_printf(MSDK_STRING("\nUsage: sample_multi_transcode [options] [--] pipeline-description\n"));
msdk_printf(MSDK_STRING(" or: sample_multi_transcode [options] -par ParFile\n"));
msdk_printf(MSDK_STRING("\n"));
msdk_printf(MSDK_STRING("Run application with -? option to get full help text.\n\n"));
}
}
void TranscodingSample::PrintHelp()
{
msdk_printf(MSDK_STRING("Multi Transcoding Sample Version %s\n\n"), GetMSDKSampleVersion().c_str());
msdk_printf(MSDK_STRING("Command line parameters\n"));
msdk_printf(MSDK_STRING("Usage: sample_multi_transcode [options] [--] pipeline-description\n"));
msdk_printf(MSDK_STRING(" or: sample_multi_transcode [options] -par ParFile\n"));
msdk_printf(MSDK_STRING("\n"));
msdk_printf(MSDK_STRING(" -stat <N>\n"));
msdk_printf(MSDK_STRING(" Output statistic every N transcoding cycles\n"));
msdk_printf(MSDK_STRING(" -stat-log <name>\n"));
msdk_printf(MSDK_STRING(" Output statistic to the specified file (opened in append mode)\n"));
msdk_printf(MSDK_STRING(" -stat-per-frame <name>\n"));
msdk_printf(MSDK_STRING(" Output per-frame latency values to a file (opened in append mode). The file name will be for an input sesssion: <name>_input_ID_<N>.log\n"));
msdk_printf(MSDK_STRING(" or, for output session: <name>_output_ID_<N>.log; <N> - a number of a session.\n"));
msdk_printf(MSDK_STRING("Options:\n"));
// (" ............xx
msdk_printf(MSDK_STRING(" -? Print this help and exit\n"));
msdk_printf(MSDK_STRING(" -p <file-name>\n"));
msdk_printf(MSDK_STRING(" Collect performance statistics in specified file\n"));
msdk_printf(MSDK_STRING(" -dump <file-name>\n"));
msdk_printf(MSDK_STRING(" Dump MSDK components configuration in specified text file\n"));
msdk_printf(MSDK_STRING(" -timeout <seconds>\n"));
msdk_printf(MSDK_STRING(" Set time to run transcoding in seconds\n"));
msdk_printf(MSDK_STRING(" -greedy \n"));
msdk_printf(MSDK_STRING(" Use greedy formula to calculate number of surfaces\n"));
msdk_printf(MSDK_STRING("\n"));
msdk_printf(MSDK_STRING("Pipeline description (general options):\n"));
msdk_printf(MSDK_STRING(" -i::h265|h264|mpeg2|vc1|mvc|jpeg|vp9|av1 <file-name>\n"));
msdk_printf(MSDK_STRING(" Set input file and decoder type\n"));
msdk_printf(MSDK_STRING(" -i::i420|nv12 <file-name>\n"));
msdk_printf(MSDK_STRING(" Set raw input file and color format\n"));
msdk_printf(MSDK_STRING(" -i::rgb4_frame Set input rgb4 file for compositon. File should contain just one single frame (-vpp_comp_src_h and -vpp_comp_src_w should be specified as well).\n"));
msdk_printf(MSDK_STRING(" -o::h265|h264|mpeg2|mvc|jpeg|vp9|raw <file-name>\n"));
msdk_printf(MSDK_STRING(" Set output file and encoder type\n"));
msdk_printf(MSDK_STRING(" -sw|-hw|-hw_d3d11|-hw_d3d9\n"));
msdk_printf(MSDK_STRING(" SDK implementation to use: \n"));
msdk_printf(MSDK_STRING(" -hw - platform-specific on default display adapter (default)\n"));
msdk_printf(MSDK_STRING(" -hw_d3d11 - platform-specific via d3d11 (d3d11 is default for win)\n"));
msdk_printf(MSDK_STRING(" -hw_d3d9 - platform-specific via d3d9\n"));
msdk_printf(MSDK_STRING(" -sw - software\n"));
#if defined(LINUX32) || defined(LINUX64)
msdk_printf(MSDK_STRING(" -device /path/to/device - set graphics device for processing\n"));
msdk_printf(MSDK_STRING(" For example: '-device /dev/dri/card0'\n"));
msdk_printf(MSDK_STRING(" '-device /dev/dri/renderD128'\n"));
msdk_printf(MSDK_STRING(" If not specified, defaults to the first Intel device found on the system\n"));
#endif
#if (defined(_WIN64) || defined(_WIN32)) && (MFX_VERSION >= 1031)
msdk_printf(MSDK_STRING(" [-dGfx] - preffer processing on dGfx (by default system decides)\n"));
msdk_printf(MSDK_STRING(" [-iGfx] - preffer processing on iGfx (by default system decides)\n"));
#endif
#if (MFX_VERSION >= 1025)
msdk_printf(MSDK_STRING(" -mfe_frames <N> maximum number of frames to be combined in multi-frame encode pipeline"));
msdk_printf(MSDK_STRING(" 0 - default for platform will be used\n"));
msdk_printf(MSDK_STRING(" -mfe_mode 0|1|2|3 multi-frame encode operation mode - should be the same for all sessions\n"));
msdk_printf(MSDK_STRING(" 0, MFE operates as DEFAULT mode, decided by SDK if MFE enabled\n"));
msdk_printf(MSDK_STRING(" 1, MFE is disabled\n"));
msdk_printf(MSDK_STRING(" 2, MFE operates as AUTO mode\n"));
msdk_printf(MSDK_STRING(" 3, MFE operates as MANUAL mode\n"));
msdk_printf(MSDK_STRING(" -mfe_timeout <N> multi-frame encode timeout in milliseconds - set per sessions control\n"));
#endif
#ifdef ENABLE_MCTF
#if !defined ENABLE_MCTF_EXT
msdk_printf(MSDK_STRING(" -mctf [Strength]\n"));
msdk_printf(MSDK_STRING(" Strength is an optional value; it is in range [0...20]\n"));
msdk_printf(MSDK_STRING(" value 0 makes MCTF operates in auto mode;\n"));
msdk_printf(MSDK_STRING(" Strength: integer, [0...20]. Default value is 0.Might be a CSV filename (upto 15 symbols); if a string is convertable to an integer, integer has a priority over filename\n"));
msdk_printf(MSDK_STRING(" In fixed-strength mode, MCTF strength can be adjusted at framelevel;\n"));
msdk_printf(MSDK_STRING(" If no Strength is given, MCTF operates in auto mode.\n"));
#else
msdk_printf(MSDK_STRING(" -mctf MctfMode:BitsPerPixel:Strength:ME:Overlap:DB\n"));
msdk_printf(MSDK_STRING(" every parameter may be missed; in this case default value is used.\n"));
msdk_printf(MSDK_STRING(" MctfMode: 0 - spatial filter\n"));
msdk_printf(MSDK_STRING(" MctfMode: 1- temporal filtering, 1 backward reference\n"));
msdk_printf(MSDK_STRING(" MctfMode: 2- temporal filtering, 1 backward & 1 forward reference\n"));
msdk_printf(MSDK_STRING(" MctfMode: 3- temporal filtering, 2 backward & 2 forward references\n"));
msdk_printf(MSDK_STRING(" MctfMode: other values: force default mode to be used\n"));
msdk_printf(MSDK_STRING(" BitsPerPixel: float, valid range [0...12.0]; if exists, is used for automatic filter strength adaptation. Default is 0.0\n"));
msdk_printf(MSDK_STRING(" Strength: integer, [0...20]. Default value is 0.Might be a CSV filename (upto 15 symbols); if a string is convertable to an integer, integer has a priority over filename\n"));
msdk_printf(MSDK_STRING(" ME: Motion Estimation precision; 0 - integer ME (default); 1 - quater-pel ME\n"));
msdk_printf(MSDK_STRING(" Overlap: 0 - do not apply overlap ME (default); 1 - to apply overlap ME\n"));
msdk_printf(MSDK_STRING(" DB: 0 - do not apply deblock Filter (default); 1 - to apply Deblock Filter\n"));
#endif //ENABLE_MCTF_EXT
#endif //ENABLE_MCTF
msdk_printf(MSDK_STRING(" -robust Recover from gpu hang errors as they come (by resetting components)\n"));
msdk_printf(MSDK_STRING(" -robust:soft Recover from gpu hang errors by inserting an IDR\n"));
msdk_printf(MSDK_STRING(" -async Depth of asynchronous pipeline. default value 1\n"));
msdk_printf(MSDK_STRING(" -join Join session with other session(s), by default sessions are not joined\n"));
msdk_printf(MSDK_STRING(" -priority Use priority for join sessions. 0 - Low, 1 - Normal, 2 - High. Normal by default\n"));
msdk_printf(MSDK_STRING(" -threads num Number of session internal threads to create\n"));
msdk_printf(MSDK_STRING(" -n Number of frames to transcode\n") \
MSDK_STRING(" (session ends after this number of frames is reached). \n") \
MSDK_STRING(" In decoding sessions (-o::sink) this parameter limits number\n") \
MSDK_STRING(" of frames acquired from decoder.\n") \
MSDK_STRING(" In encoding sessions (-o::source) and transcoding sessions \n") \
MSDK_STRING(" this parameter limits number of frames sent to encoder.\n"));
msdk_printf(MSDK_STRING(" -MemType::video Force usage of external video allocator (default)\n"));
msdk_printf(MSDK_STRING(" -MemType::system Force usage of external system allocator\n"));
msdk_printf(MSDK_STRING(" -MemType::opaque Force usage of internal allocator\n"));
msdk_printf(MSDK_STRING(" -dec::sys Set dec output to system memory\n"));
msdk_printf(MSDK_STRING(" -vpp::sys Set vpp output to system memory\n"));
msdk_printf(MSDK_STRING(" -vpp::vid Set vpp output to video memory\n"));
msdk_printf(MSDK_STRING(" -fps <frames per second>\n"));
msdk_printf(MSDK_STRING(" Transcoding frame rate limit\n"));
msdk_printf(MSDK_STRING(" -pe Set encoding plugin for this particular session.\n"));
msdk_printf(MSDK_STRING(" This setting overrides plugin settings defined by SET clause.\n"));
msdk_printf(MSDK_STRING(" -pd Set decoding plugin for this particular session.\n"));
msdk_printf(MSDK_STRING(" This setting overrides plugin settings defined by SET clause.\n"));
msdk_printf(MSDK_STRING(" Supported values: hevcd_sw, hevcd_hw, hevce_sw, hevce_gacc, hevce_hw, vp8d_hw, vp8e_hw, vp9d_hw, vp9e_hw, camera_hw, capture_hw, h264_la_hw, ptir_hw, hevce_fei_hw\n"));
msdk_printf(MSDK_STRING(" Direct GUID number can be used as well\n"));
msdk_printf(MSDK_STRING("\n"));
msdk_printf(MSDK_STRING("Pipeline description (encoding options):\n"));
msdk_printf(MSDK_STRING(" -b <Kbits per second>\n"));
msdk_printf(MSDK_STRING(" Encoded bit rate, valid for H.264, MPEG2 and MVC encoders\n"));
msdk_printf(MSDK_STRING(" -bm Bitrate multiplier. Use it when required bitrate isn't fit into 16-bit\n"));
msdk_printf(MSDK_STRING(" Affects following parameters: InitialDelayInKB, BufferSizeInKB, TargetKbps, MaxKbps\n"));
msdk_printf(MSDK_STRING(" -f <frames per second>\n"));
msdk_printf(MSDK_STRING(" Video frame rate for the FRC and deinterlace options\n"));
msdk_printf(MSDK_STRING(" -fe <frames per second>\n"));
msdk_printf(MSDK_STRING(" Video frame rate for the FRC and deinterlace options (deprecated, will be removed in next versions).\n"));
msdk_printf(MSDK_STRING(" -override_decoder_framerate <framerate> \n"));
msdk_printf(MSDK_STRING(" Forces decoder output framerate to be set to provided value (overwriting actual framerate from decoder)\n"));
msdk_printf(MSDK_STRING(" -override_encoder_framerate <framerate> \n"));
msdk_printf(MSDK_STRING(" Overwrites framerate of stream going into encoder input with provided value (this option does not enable FRC, it just ovewrites framerate value)\n"));
msdk_printf(MSDK_STRING(" -override_encoder_picstruct <picstruct> \n"));
msdk_printf(MSDK_STRING(" Overwrites encoder picstruct with specific value"));
msdk_printf(MSDK_STRING(" -u <usage> Target usage. Valid for H.265, H.264, MPEG2 and MVC encoders. Expected values:\n"));
msdk_printf(MSDK_STRING(" veryslow(quality), slower, slow, medium(balanced), fast, faster, veryfast(speed)\n"));
msdk_printf(MSDK_STRING(" -q <quality> Quality parameter for JPEG encoder; in range [1,100], 100 is the best quality\n"));
msdk_printf(MSDK_STRING(" -l numSlices Number of slices for encoder; default value 0 \n"));
msdk_printf(MSDK_STRING(" -mss maxSliceSize \n"));
msdk_printf(MSDK_STRING(" Maximum slice size in bytes. Supported only with -hw and h264 codec. This option is not compatible with -l option.\n"));
msdk_printf(MSDK_STRING(" -BitrateLimit:<on,off>\n"));
msdk_printf(MSDK_STRING(" Turn this flag ON to set bitrate limitations imposed by the SDK encoder. Off by default.\n"));
msdk_printf(MSDK_STRING(" -la Use the look ahead bitrate control algorithm (LA BRC) for H.264 encoder. Supported only with -hw option on 4th Generation Intel Core processors. \n"));
msdk_printf(MSDK_STRING(" -lad depth Depth parameter for the LA BRC, the number of frames to be analyzed before encoding. In range [0,100] (0 - default: auto-select by mediasdk library). \n"));
msdk_printf(MSDK_STRING(" May be 1 in the case when -mss option is specified \n"));
msdk_printf(MSDK_STRING(" -la_ext Use external LA plugin (compatible with h264 & hevc encoders)\n"));
msdk_printf(MSDK_STRING(" -vbr Variable bitrate control\n"));
msdk_printf(MSDK_STRING(" -avbr Average variable bitrate control\n"));
msdk_printf(MSDK_STRING(" -convergence <number>\n"));
msdk_printf(MSDK_STRING(" Bitrate convergence period for AVBR, in the unit of 100 frames\n"));
msdk_printf(MSDK_STRING(" -accuracy <number>\n"));
msdk_printf(MSDK_STRING(" Bitrate accuracy for AVBR. Value is specified in the unit of tenth of percent\n"));
msdk_printf(MSDK_STRING(" -qvbr <quality>\n"));
msdk_printf(MSDK_STRING(" Quality-defined variable bitrate control, quality is a value in range [1..51], where 1 corresponds to the best quality\n"));
msdk_printf(MSDK_STRING(" -icq <quality>\n"));
msdk_printf(MSDK_STRING(" Intelligent constant quality bitrate control, quality is a value in range [1..51], where 1 corresponds to the best quality\n"));
msdk_printf(MSDK_STRING(" -cbr Constant bitrate control\n"));
msdk_printf(MSDK_STRING(" -vcm Video Conferencing Mode (VCM) bitrate control\n"));
msdk_printf(MSDK_STRING(" -hrd <KBytes> Maximum possible size of any compressed frames \n"));
msdk_printf(MSDK_STRING(" -wb <Kbits per second>\n"));
msdk_printf(MSDK_STRING(" Maximum bitrate for sliding window\n"));
msdk_printf(MSDK_STRING(" -ws Sliding window size in frames\n"));
msdk_printf(MSDK_STRING(" -gop_size Size of GOP structure in frames \n"));
msdk_printf(MSDK_STRING(" -dist Distance between I- or P- key frames \n"));
msdk_printf(MSDK_STRING(" -num_ref Number of reference frames\n"));
msdk_printf(MSDK_STRING(" -bref Arrange B frames in B pyramid reference structure\n"));
msdk_printf(MSDK_STRING(" -nobref Do not use B-pyramid (by default the decision is made by library)\n"));
msdk_printf(MSDK_STRING(" -bpyr Enable B pyramid\n"));
msdk_printf(MSDK_STRING(" -gpb:<on,off> - Enable or disable Generalized P/B frames\n"));
#if (MFX_VERSION >= 1026)
msdk_printf(MSDK_STRING(" -TransformSkip:<on,off>- Enable or disable TransformSkip\n"));
#endif
msdk_printf(MSDK_STRING(" -trows <rows> - Number of rows for tiled encoding\n"));
msdk_printf(MSDK_STRING(" -tcols <cols> - Number of columns for tiled encoding\n"));
msdk_printf(MSDK_STRING(" -CodecProfile - Specifies codec profile\n"));
msdk_printf(MSDK_STRING(" -CodecLevel - Specifies codec level\n"));
msdk_printf(MSDK_STRING(" -GopOptFlag:closed - Closed gop\n"));
msdk_printf(MSDK_STRING(" -GopOptFlag:strict - Strict gop\n"));
msdk_printf(MSDK_STRING(" -AdaptiveI:<on,off> - Turn Adaptive I frames on/off\n"));
msdk_printf(MSDK_STRING(" -AdaptiveB:<on,off> - Turn Adaptive B frames on/off\n"));
msdk_printf(MSDK_STRING(" -InitialDelayInKB - The decoder starts decoding after the buffer reaches the initial size InitialDelayInKB, \n\
which is equivalent to reaching an initial delay of InitialDelayInKB*8000/TargetKbps ms\n"));
msdk_printf(MSDK_STRING(" -MaxKbps - For variable bitrate control, specifies the maximum bitrate at which \n\
the encoded data enters the Video Buffering Verifier buffer\n"));
msdk_printf(MSDK_STRING(" -gpucopy::<on,off> Enable or disable GPU copy mode\n"));
msdk_printf(MSDK_STRING(" -repartitioncheck::<on,off> Enable or disable RepartitionCheckEnable mode\n"));
msdk_printf(MSDK_STRING(" -cqp Constant quantization parameter (CQP BRC) bitrate control method\n"));
msdk_printf(MSDK_STRING(" (by default constant bitrate control method is used), should be used along with -qpi, -qpp, -qpb.\n"));
#if (MFX_VERSION >= 1022)
msdk_printf(MSDK_STRING(" -qpi Constant quantizer for I frames (if bitrace control method is CQP). In range [1,51]. 0 by default, i.e.no limitations on QP.\n"));
msdk_printf(MSDK_STRING(" -qpp Constant quantizer for P frames (if bitrace control method is CQP). In range [1,51]. 0 by default, i.e.no limitations on QP.\n"));
msdk_printf(MSDK_STRING(" -qpb Constant quantizer for B frames (if bitrace control method is CQP). In range [1,51]. 0 by default, i.e.no limitations on QP.\n"));
#endif
msdk_printf(MSDK_STRING(" -DisableQPOffset Disable QP adjustment for GOP pyramid-level frames\n"));
msdk_printf(MSDK_STRING(" -lowpower:<on,off> Turn this option ON to enable QuickSync Fixed Function (low-power HW) encoding mode\n"));
#if (MFX_VERSION >= 1027)
msdk_printf(MSDK_STRING(" [-TargetBitDepthLuma] - Encoding target bit depth for luma samples, by default same as source one.\n"));
msdk_printf(MSDK_STRING(" [-TargetBitDepthChroma] - Encoding target bit depth for chroma samples, by default same as source one.\n"));
#endif
#if MFX_VERSION >= 1022
msdk_printf(MSDK_STRING(" -roi_file <roi-file-name>\n"));
msdk_printf(MSDK_STRING(" Set Regions of Interest for each frame from <roi-file-name>\n"));
msdk_printf(MSDK_STRING(" -roi_qpmap Use QP map to emulate ROI for CQP mode\n"));
msdk_printf(MSDK_STRING(" -extmbqp Use external MBQP map\n"));
#endif //MFX_VERSION >= 1022
msdk_printf(MSDK_STRING(" -AvcTemporalLayers [array:Layer.Scale] Configures the temporal layers hierarchy\n"));
msdk_printf(MSDK_STRING(" -BaseLayerPID <pid> Sets priority ID for the base layer\n"));
msdk_printf(MSDK_STRING(" -SPSId <pid> Sets sequence parameter set ID\n"));
msdk_printf(MSDK_STRING(" -PPSId <pid> Sets picture parameter set ID\n"));
msdk_printf(MSDK_STRING(" -PicTimingSEI:<on,off> Enables or disables picture timing SEI\n"));
msdk_printf(MSDK_STRING(" -NalHrdConformance:<on,off> Enables or disables picture HRD conformance\n"));
msdk_printf(MSDK_STRING(" -VuiNalHrdParameters:<on,off> Enables or disables NAL HRD parameters in VUI header\n"));
msdk_printf(MSDK_STRING("\n"));
msdk_printf(MSDK_STRING("Pipeline description (vpp options):\n"));
msdk_printf(MSDK_STRING(" -deinterlace Forces VPP to deinterlace input stream\n"));
msdk_printf(MSDK_STRING(" -deinterlace::ADI Forces VPP to deinterlace input stream using ADI algorithm\n"));
msdk_printf(MSDK_STRING(" -deinterlace::ADI_SCD Forces VPP to deinterlace input stream using ADI_SCD algorithm\n"));
msdk_printf(MSDK_STRING(" -deinterlace::ADI_NO_REF Forces VPP to deinterlace input stream using ADI no ref algorithm\n"));
msdk_printf(MSDK_STRING(" -deinterlace::BOB Forces VPP to deinterlace input stream using BOB algorithm\n"));
msdk_printf(MSDK_STRING(" -detail <level> Enables detail (edge enhancement) filter with provided level(0..100)\n"));
msdk_printf(MSDK_STRING(" -denoise <level> Enables denoise filter with provided level (0..100)\n"));
msdk_printf(MSDK_STRING(" -FRC::PT Enables FRC filter with Preserve Timestamp algorithm\n"));
msdk_printf(MSDK_STRING(" -FRC::DT Enables FRC filter with Distributed Timestamp algorithm\n"));
msdk_printf(MSDK_STRING(" -FRC::INTERP Enables FRC filter with Frame Interpolation algorithm\n"));
msdk_printf(MSDK_STRING(" -scaling_mode <mode> Specifies scaling mode (lowpower/quality)\n"));
msdk_printf(MSDK_STRING(" -ec::nv12|rgb4|yuy2|nv16|p010|p210|y210|y410|p016|y216|y416 Forces encoder input to use provided chroma mode\n"));
msdk_printf(MSDK_STRING(" -dc::nv12|rgb4|yuy2|p010|y210|y410|p016|y216 Forces decoder output to use provided chroma mode\n"));
msdk_printf(MSDK_STRING(" NOTE: chroma transform VPP may be automatically enabled if -ec/-dc parameters are provided\n"));
msdk_printf(MSDK_STRING(" -angle 180 Enables 180 degrees picture rotation user module before encoding\n"));
msdk_printf(MSDK_STRING(" -opencl Uses implementation of rotation plugin (enabled with -angle option) through Intel(R) OpenCL\n"));
msdk_printf(MSDK_STRING(" -w Destination picture width, invokes VPP resize or decoder fixed function resize engine (if -dec_postproc specified)\n"));
msdk_printf(MSDK_STRING(" -h Destination picture height, invokes VPP resize or decoder fixed function resize engine (if -dec_postproc specified)\n"));
msdk_printf(MSDK_STRING(" -field_processing t2t|t2b|b2t|b2b|fr2fr - Field Copy feature\n"));
msdk_printf(MSDK_STRING(" -WeightedPred::default|implicit Enambles weighted prediction usage\n"));
msdk_printf(MSDK_STRING(" -WeightedBiPred::default|implicit Enambles weighted bi-prediction usage\n"));
msdk_printf(MSDK_STRING(" -ir_type - Intra refresh type. 0 - no refresh, 1 - vertical refresh, 2 - horisontal refresh, 3 - slice refresh\n"));
msdk_printf(MSDK_STRING(" -ir_cycle_size - Number of pictures within refresh cycle starting from 2\n"));
msdk_printf(MSDK_STRING(" -ir_qp_delta - QP difference for inserted intra MBs. This is signed value in [-51, 51] range\n"));
msdk_printf(MSDK_STRING(" -ir_cycle_dist - Distance between the beginnings of the intra-refresh cycles in frames\n"));
msdk_printf(MSDK_STRING(" -LowDelayBRC - strictly obey average frame size set by MaxKbps\n"));
msdk_printf(MSDK_STRING(" -amfs:<on,off> - adaptive max frame size. If set on, P or B frame size can exceed MaxFrameSize when the scene change is detected.\
It can benefit the video quality \n"));
msdk_printf(MSDK_STRING(" -mfs - maximum frame size in bytes. Supported only with h264 and hevc codec for VBR mode.\n"));
#if (MFX_VERSION >= 1024)
msdk_printf(MSDK_STRING(" -extbrc::<on,off,implicit> Enables external BRC for AVC and HEVC encoders\n"));
#endif
#if (MFX_VERSION >= 1026)
msdk_printf(MSDK_STRING(" -ExtBrcAdaptiveLTR:<on,off> Set AdaptiveLTR for implicit extbrc"));
#endif
msdk_printf(MSDK_STRING(" -vpp_comp <sourcesNum> Enables composition from several decoding sessions. Result is written to the file\n"));
msdk_printf(MSDK_STRING(" -vpp_comp_only <sourcesNum> Enables composition from several decoding sessions. Result is shown on screen\n"));
msdk_printf(MSDK_STRING(" -vpp_comp_num_tiles <Num> Quantity of tiles for composition. if equal to 0 tiles processing ignored\n"));
msdk_printf(MSDK_STRING(" -vpp_comp_dst_x X position of this stream in composed stream (should be used in decoder session)\n"));
msdk_printf(MSDK_STRING(" -vpp_comp_dst_y Y position of this stream in composed stream (should be used in decoder session)\n"));
msdk_printf(MSDK_STRING(" -vpp_comp_dst_h Height of this stream in composed stream (should be used in decoder session)\n"));
msdk_printf(MSDK_STRING(" -vpp_comp_dst_w Width of this stream in composed stream (should be used in decoder session)\n"));
msdk_printf(MSDK_STRING(" -vpp_comp_src_h Width of this stream in composed stream (should be used in decoder session)\n"));
msdk_printf(MSDK_STRING(" -vpp_comp_src_w Width of this stream in composed stream (should be used in decoder session)\n"));
#if MFX_VERSION >= 1023
msdk_printf(MSDK_STRING(" -vpp_comp_tile_id Tile_id for current channel of composition (should be used in decoder session)\n"));
#endif
msdk_printf(MSDK_STRING(" -vpp_comp_dump <file-name> Dump of VPP Composition's output into file. Valid if with -vpp_comp* options\n"));
msdk_printf(MSDK_STRING(" -vpp_comp_dump null_render Disabling rendering after VPP Composition. This is for performance measurements\n"));
#if MFX_VERSION >= 1022
msdk_printf(MSDK_STRING(" -dec_postproc Resize after decoder using direct pipe (should be used in decoder session)\n"));
msdk_printf(MSDK_STRING(" -single_texture_d3d11 single texture mode for d3d11 allocator \n"));
#endif //MFX_VERSION >= 1022
msdk_printf(MSDK_STRING(" -preset <default,dss,conference,gaming> Use particular preset for encoding parameters\n"));
msdk_printf(MSDK_STRING(" -pp Print preset parameters\n"));
msdk_printf(MSDK_STRING("\n"));
msdk_printf(MSDK_STRING("ParFile format:\n"));
msdk_printf(MSDK_STRING(" ParFile is extension of what can be achieved by setting pipeline in the command\n"));
msdk_printf(MSDK_STRING("line. For more information on ParFile format see readme-multi-transcode.pdf\n"));
msdk_printf(MSDK_STRING("\n"));
msdk_printf(MSDK_STRING("Examples:\n"));
msdk_printf(MSDK_STRING(" sample_multi_transcode -i::mpeg2 in.mpeg2 -o::h264 out.h264\n"));
msdk_printf(MSDK_STRING(" sample_multi_transcode -i::mvc in.mvc -o::mvc out.mvc -w 320 -h 240\n"));
msdk_printf(MSDK_STRING("\n"));
msdk_printf(MSDK_STRING("For more information on HOWTO usage of sample_multi_transcode, refer to readme document available at https://github.com/Intel-Media-SDK/MediaSDK/blob/master/doc/samples/readme-multi-transcode_linux.md\n"));
}
void TranscodingSample::PrintInfo(mfxU32 session_number, sInputParams* pParams, mfxVersion *pVer)
{
msdk_char buf[2048];
MSDK_CHECK_POINTER_NO_RET(pVer);
if ((MFX_IMPL_AUTO <= pParams->libType) && (MFX_IMPL_HARDWARE4 >= pParams->libType))
{
msdk_printf(MSDK_STRING("MFX %s Session %d API ver %d.%d parameters: \n"),
(MFX_IMPL_SOFTWARE == pParams->libType)? MSDK_STRING("SOFTWARE") : MSDK_STRING("HARDWARE"),
session_number,
pVer->Major,
pVer->Minor);
}
if (0 == pParams->DecodeId)
msdk_printf(MSDK_STRING("Input video: From parent session\n"));
else
msdk_printf(MSDK_STRING("Input video: %s\n"), CodecIdToStr(pParams->DecodeId).c_str());
// means that source is parent session
if (0 == pParams->EncodeId)
msdk_printf(MSDK_STRING("Output video: To child session\n"));
else
msdk_printf(MSDK_STRING("Output video: %s\n"), CodecIdToStr(pParams->EncodeId).c_str());
if (PrintDllInfo(buf, MSDK_ARRAY_LEN(buf), pParams))
msdk_printf(MSDK_STRING("MFX dll: %s\n"),buf);
msdk_printf(MSDK_STRING("\n"));
}
bool TranscodingSample::PrintDllInfo(msdk_char* buf, mfxU32 buf_size, sInputParams* pParams)
{
#if defined(_WIN32) || defined(_WIN64)
HANDLE hCurrent = GetCurrentProcess();
HMODULE *pModules;
DWORD cbNeeded;
int nModules;
if (NULL == EnumProcessModules(hCurrent, NULL, 0, &cbNeeded))
return false;
nModules = cbNeeded / sizeof(HMODULE);
pModules = new HMODULE[nModules];
if (NULL == pModules)
{
return false;
}
if (NULL == EnumProcessModules(hCurrent, pModules, cbNeeded, &cbNeeded))
{
delete []pModules;
return false;
}
for (int i = 0; i < nModules; i++)
{
GetModuleFileName(pModules[i], buf, buf_size);
if (_tcsstr(buf, MSDK_STRING("libmfxhw")) && (MFX_IMPL_SOFTWARE != pParams->libType))
{
delete []pModules;
return true;
}
else if (_tcsstr(buf, MSDK_STRING("libmfxsw")) && (MFX_IMPL_SOFTWARE == pParams->libType))
{
delete []pModules;
return true;
}
}
delete []pModules;
return false;
#else
return false;
#endif
}
CmdProcessor::CmdProcessor()
{
m_SessionParamId = 0;
m_SessionArray.clear();
m_decoderPlugins.clear();
m_encoderPlugins.clear();
m_PerfFILE = NULL;
m_parName = NULL;
m_nTimeout = 0;
statisticsWindowSize = 0;
statisticsLogFile = NULL;
DumpLogFileName.clear();
shouldUseGreedyFormula=false;
bRobustFlag = false;
bSoftRobustFlag = false;
} //CmdProcessor::CmdProcessor()
CmdProcessor::~CmdProcessor()
{
m_SessionArray.clear();
m_decoderPlugins.clear();
m_encoderPlugins.clear();
if (m_PerfFILE)
fclose(m_PerfFILE);
if (statisticsLogFile)
fclose(statisticsLogFile);
} //CmdProcessor::~CmdProcessor()
void CmdProcessor::PrintParFileName()
{
if (m_parName && m_PerfFILE)
{
msdk_fprintf(m_PerfFILE, MSDK_STRING("Input par file: %s\n\n"), m_parName);
}
}
msdk_string CmdProcessor::GetLine(mfxU32 n)
{
if (m_lines.size() > n)
return m_lines[n];
return msdk_string();
}
mfxStatus CmdProcessor::ParseCmdLine(int argc, msdk_char *argv[])
{
FILE *parFile = NULL;
mfxStatus sts = MFX_ERR_UNSUPPORTED;
if (1 == argc)
{
PrintError(MSDK_STRING("Too few parameters"), NULL);
return MFX_ERR_UNSUPPORTED;
}
--argc;
++argv;
while (argv[0])
{
if (0 == msdk_strcmp(argv[0], MSDK_STRING("-par")))
{
--argc;
++argv;
if (!argv[0]) {
msdk_printf(MSDK_STRING("error: no argument given for '-par' option\n"));
}
m_parName = argv[0];
}
else if (0 == msdk_strcmp(argv[0], MSDK_STRING("-timeout")))
{
--argc;
++argv;
if (!argv[0]) {
msdk_printf(MSDK_STRING("error: no argument given for '-timeout' option\n"));
}
if (MFX_ERR_NONE != msdk_opt_read(argv[0], m_nTimeout))
{
msdk_printf(MSDK_STRING("error: -timeout \"%s\" is invalid"), argv[0]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[0], MSDK_STRING("-robust")))
{
bRobustFlag = true;
}
else if (0 == msdk_strcmp(argv[0], MSDK_STRING("-robust:soft")))
{
bSoftRobustFlag = true;
}
else if (0 == msdk_strcmp(argv[0], MSDK_STRING("-?")) )
{
PrintHelp();
return MFX_WRN_OUT_OF_RANGE;
}
else if (0 == msdk_strcmp(argv[0], MSDK_STRING("-greedy")))
{
shouldUseGreedyFormula=true;
}
else if (0 == msdk_strcmp(argv[0], MSDK_STRING("-p")))
{
if (m_PerfFILE)
{
msdk_printf(MSDK_STRING("error: only one performance file is supported"));
return MFX_ERR_UNSUPPORTED;
}
--argc;
++argv;
if (!argv[0]) {
msdk_printf(MSDK_STRING("error: no argument given for '-p' option\n"));
}
MSDK_FOPEN(m_PerfFILE, argv[0], MSDK_STRING("w"));
if (NULL == m_PerfFILE)
{
msdk_printf(MSDK_STRING("error: performance file \"%s\" not found"), argv[0]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[0], MSDK_STRING("--")))
{
// just skip separator "--" which delimits cmd options and pipeline settings
break;
}
else if (0 == msdk_strcmp(argv[0], MSDK_STRING("-stat")))
{
--argc;
++argv;
if (!argv[0]) {
msdk_printf(MSDK_STRING("error: no argument given for 'stat' option\n"));
}
if (MFX_ERR_NONE != msdk_opt_read(argv[0], statisticsWindowSize))
{
msdk_printf(MSDK_STRING("error: stat \"%s\" is invalid"), argv[0]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[0], MSDK_STRING("-stat-log")))
{
if (statisticsLogFile)
{
msdk_printf(MSDK_STRING("error: only one statistics file is supported"));
return MFX_ERR_UNSUPPORTED;
}
--argc;
++argv;
if (!argv[0]) {
msdk_printf(MSDK_STRING("error: no argument given for 'stat-log' option\n"));
}
MSDK_FOPEN(statisticsLogFile, argv[0], MSDK_STRING("w"));
if (NULL == statisticsLogFile)
{
msdk_printf(MSDK_STRING("error: statistics file \"%s\" not found"), argv[0]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[0], MSDK_STRING("-stat-per-frame")))
{
if (!DumpLogFileName.empty()){
msdk_printf(MSDK_STRING("error: only one dump file is supported"));
return MFX_ERR_UNSUPPORTED;
}
--argc;
++argv;
if (!argv[0])
{
msdk_printf(MSDK_STRING("error: no argument given for 'stat-dump' option\n"));
}
DumpLogFileName = argv[0];
}
else
{
break;
}
--argc;
++argv;
}
msdk_printf(MSDK_STRING("Multi Transcoding Sample Version %s\n\n"), GetMSDKSampleVersion().c_str());
//Read pipeline from par file
if (m_parName && !argv[0])
{
MSDK_FOPEN(parFile, m_parName, MSDK_STRING("r"));
if (NULL == parFile)
{
msdk_printf(MSDK_STRING("error: ParFile \"%s\" not found\n"), m_parName);
return MFX_ERR_UNSUPPORTED;
}
if (NULL != m_parName) msdk_printf(MSDK_STRING("Par file is: %s\n\n"), m_parName);
sts = ParseParFile(parFile);
if (MFX_ERR_NONE != sts)
{
fclose(parFile);
return sts;
}
fclose(parFile);
}
//Read pipeline from cmd line
else if (!argv[0])
{
msdk_printf(MSDK_STRING ("error: pipeline description not found\n"));
return MFX_ERR_UNSUPPORTED;
}
else if (argv[0] && m_parName)
{
msdk_printf(MSDK_STRING ("error: simultaneously enabling parfile and description pipeline from command line forbidden\n"));
return MFX_ERR_UNSUPPORTED;
}
else
{
sts = ParseParamsForOneSession(argc, argv);
if (MFX_ERR_NONE != sts)
{
msdk_printf(MSDK_STRING("error: pipeline description is invalid\n"));
return sts;
}
}
return sts;
} //mfxStatus CmdProcessor::ParseCmdLine(int argc, msdk_char *argv[])
mfxStatus CmdProcessor::ParseParFile(FILE *parFile)
{
mfxStatus sts = MFX_ERR_UNSUPPORTED;
if (!parFile)
return MFX_ERR_UNSUPPORTED;
mfxU32 currPos = 0;
mfxU32 lineIndex = 0;
// calculate file size
fseek(parFile, 0, SEEK_END);
mfxU32 fileSize = ftell(parFile) + 1;
fseek(parFile, 0, SEEK_SET);
// allocate buffer for parsing
std::unique_ptr<msdk_char[]> parBuf(new msdk_char[fileSize]);
msdk_char *pCur;
while(currPos < fileSize)
{
pCur = /*_fgetts*/msdk_fgets(parBuf.get(), fileSize, parFile);
if (!pCur)
return MFX_ERR_NONE;
while(pCur[currPos] != '\n' && pCur[currPos] != 0)
{
currPos++;
if (pCur + currPos >= parBuf.get() + fileSize)
return sts;
}
// zero string
if (!currPos)
continue;
sts = TokenizeLine(pCur, currPos);
MSDK_CHECK_STATUS(sts, "TokenizeLine failed");
currPos = 0;
lineIndex++;
}
return MFX_ERR_NONE;
} //mfxStatus CmdProcessor::ParseParFile(FILE *parFile)
// calculate length of string literal, including leading and trailing "
// pTempLine = start of string (must begin with ")
// length = remaining characters in pTempLine
// returns length of string, or 0 if error
mfxU32 CmdProcessor::GetStringLength(msdk_char *pTempLine, mfxU32 length)
{
mfxU32 i;
// error - no leading " found
if (pTempLine[0] != '\"')
return 0;
for (i = 1; i < length; i++)
{
if (pTempLine[i] == '\"')
break;
}
// error - no closing " found
if (i == length)
return 0;
return i + 1;
}
mfxStatus CmdProcessor::TokenizeLine(msdk_char *pLine, mfxU32 length)
{
mfxU32 i, strArgLen;
const mfxU8 maxArgNum = 255;
msdk_char *argv[maxArgNum+1];
mfxU32 argc = 0;
std::unique_ptr<msdk_char[]> pMemLine(new msdk_char[length+2]);
msdk_char *pTempLine = pMemLine.get();
pTempLine[0] = ' ';
pTempLine++;
MSDK_MEMCPY_BUF(pTempLine,0 , length*sizeof(msdk_char), pLine, length*sizeof(msdk_char));
// parse into command streams
for (i = 0; i < length ; i++)
{
// check if separator
if (IS_SEPARATOR(pTempLine[-1]) && !IS_SEPARATOR(pTempLine[0]))
{
argv[argc++] = pTempLine;
if (argc > maxArgNum)
{
PrintError(MSDK_STRING("Too many parameters (reached maximum of %d)"), maxArgNum);
return MFX_ERR_UNSUPPORTED;
}
}
if (*pTempLine == '\"' )
{
strArgLen = GetStringLength(pTempLine, length - i);
if (!strArgLen)
{
PrintError(MSDK_STRING("Error parsing string literal"));
return MFX_ERR_UNSUPPORTED;
}
// remove leading and trailing ", bump pointer ahead to next argument
pTempLine[0] = ' ';
pTempLine[strArgLen-1] = ' ';
pTempLine += strArgLen;
i += strArgLen;
}
if (*pTempLine == ' ' || *pTempLine == '\r' || *pTempLine == '\n')
{
*pTempLine = 0;
}
pTempLine++;
}
// EOL for last parameter
pTempLine[0] = 0;
return ParseParamsForOneSession(argc, argv);
}
#if MFX_VERSION >= 1022
bool CmdProcessor::isspace(char a) { return (std::isspace(a) != 0); }
bool CmdProcessor::is_not_allowed_char(char a) {
return (std::isdigit(a) != 0) && (std::isspace(a) != 0) && (a != ';') && (a != '-');
}
bool CmdProcessor::ParseROIFile(const msdk_char *roi_file_name, std::vector<mfxExtEncoderROI>& m_ROIData)
{
FILE *roi_file = NULL;
MSDK_FOPEN(roi_file, roi_file_name, MSDK_STRING("rb"));
m_ROIData.clear();
if (roi_file)
{
// read file to buffer
fseek(roi_file, 0, SEEK_END);
long file_size = ftell(roi_file);
rewind (roi_file);
std::vector<char> buffer(file_size);
char *roi_data = &buffer[0];
if (file_size<0 || (size_t)file_size != fread(roi_data, 1, file_size, roi_file))
{
fclose(roi_file);
return false;
}
fclose(roi_file);
// search for not allowed characters
char *not_allowed_char = std::find_if(roi_data, roi_data + file_size,
is_not_allowed_char);
if (not_allowed_char != (roi_data + file_size))
{
return false;
}
// get unformatted roi data
std::string unformatted_roi_data;
unformatted_roi_data.clear();
std::remove_copy_if(roi_data, roi_data + file_size,
std::inserter(unformatted_roi_data, unformatted_roi_data.end()),
isspace);
// split data to items
std::stringstream unformatted_roi_data_ss(unformatted_roi_data);
std::vector<std::string> items;
items.clear();
std::string item;
while (std::getline(unformatted_roi_data_ss, item, ';'))
{
items.push_back(item);
}
// parse data and store roi data for each frame
unsigned int item_ind = 0;
while (1)
{
if (item_ind >= items.size()) break;
mfxExtEncoderROI frame_roi;
std::memset(&frame_roi, 0, sizeof(frame_roi));
frame_roi.Header.BufferId = MFX_EXTBUFF_ENCODER_ROI;
#if (MFX_VERSION >= 1022)
frame_roi.ROIMode = MFX_ROI_MODE_QP_DELTA;
#endif
int roi_num = std::atoi(items[item_ind].c_str());
if (roi_num < 0 || roi_num > (int)(sizeof(frame_roi.ROI) / sizeof(frame_roi.ROI[0])))
{
m_ROIData.clear();
return false;
}
if ((item_ind + 5 * roi_num) >= items.size())
{
m_ROIData.clear();
return false;
}
for (int i = 0; i < roi_num; i++)
{
// do not handle out of range integer errors
frame_roi.ROI[i].Left = std::atoi(items[item_ind + i * 5 + 1].c_str());
frame_roi.ROI[i].Top = std::atoi(items[item_ind + i * 5 + 2].c_str());
frame_roi.ROI[i].Right = std::atoi(items[item_ind + i * 5 + 3].c_str());
frame_roi.ROI[i].Bottom = std::atoi(items[item_ind + i * 5 + 4].c_str());
#if (MFX_VERSION >= 1022)
frame_roi.ROI[i].DeltaQP = (mfxI16) std::atoi(items[item_ind +i * 5 + 5].c_str());
#endif
}
frame_roi.NumROI = (mfxU16) roi_num;
m_ROIData.push_back(frame_roi);
item_ind = item_ind + roi_num * 5 + 1;
}
}
else {
return false;
}
return true;
}
#endif //MFX_VERSION >= 1022
#ifdef ENABLE_MCTF
// returns a pointer to start of argument with a number argn;
// if failes to find argn, returns NULL
msdk_char* ParseArgn(msdk_char* pIn, mfxU32 argn, msdk_char separator) {
msdk_char* pstr = pIn;
if (!argn)
return pIn;
else {
for (mfxU32 n = 0; n != argn; ++n) {
while (separator != *pstr && msdk_char('\0') != *pstr)
++pstr;
if (msdk_char('\0') == *pstr)
return NULL;
else
++pstr;
}
return pstr;
}
};
template <typename T>
bool ArgConvert(msdk_char* pIn, mfxU32 argn, const msdk_char* pattern, T* pArg, const T& ArgDefault, mfxU32& NumOfGoodConverts) {
bool bConvertIsOk = false;
msdk_char* pargs = ParseArgn(pIn, argn, msdk_char(':'));
if (pargs)
{
if (!msdk_sscanf(pargs, pattern, pArg))
*pArg = ArgDefault;
else {
++NumOfGoodConverts;
bConvertIsOk = true;
}
};
return bConvertIsOk;
}
//template <typename T=msdk_string>
bool ArgConvert(msdk_char* pIn, mfxU32 argn, const msdk_char* pattern, msdk_char* pArg, mfxU32 MaxChars2Read, mfxU32& NumOfGoodConverts) {
bool bConvertIsOk = false;
msdk_char* pargs = ParseArgn(pIn, argn, msdk_char(':'));
if (pargs)
{
// lets calculate length of potential name:
msdk_char* temp(pargs);
while (*temp != msdk_char(':') && *temp != msdk_char('\0'))
++temp;
std::iterator_traits<msdk_char*>::difference_type distance = std::distance(pargs, temp);
if (distance < std::iterator_traits<msdk_char*>::difference_type(MaxChars2Read))
{
if (msdk_sscanf(pargs, pattern, pArg, MaxChars2Read))
{
++NumOfGoodConverts;
bConvertIsOk = true;
}
};
};
return bConvertIsOk;
}
void ParseMCTFParams(msdk_char* strInput[], mfxU32 nArgNum, mfxU32& curArg, sInputParams * pParams)
{
mfxU32& i = curArg;
if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-mctf")))
{
pParams->mctfParam.mode = VPP_FILTER_ENABLED_DEFAULT;
pParams->mctfParam.params.FilterStrength = 0;
pParams->mctfParam.rtParams.Reset();
bool bFSByValue = true;
#if defined ENABLE_MCTF_EXT
pParams->mctfParam.params.TemporalMode = MFX_MCTF_TEMPORAL_MODE_2REF; // default
pParams->mctfParam.params.BitsPerPixelx100k = 0;
pParams->mctfParam.params.Deblocking = MFX_CODINGOPTION_OFF;
pParams->mctfParam.params.Overlap = MFX_CODINGOPTION_OFF;
pParams->mctfParam.params.MVPrecision = MFX_MVPRECISION_INTEGER;
#endif
if (i + 1 < nArgNum)
{
mfxU16 _strength(0);
mfxU32 strength_idx = 0;
mfxU32 ParsedArgsNumber = 0;
const mfxU32 max_name_len = 15;
const mfxU32 max_elems_in_file = 10000;
msdk_stringstream file_pattern;
file_pattern << MSDK_STRING("%") << max_name_len << MSDK_STRING("ls:%*c") << std::ends;
msdk_char _tmp_str[max_name_len + 1];
memset(_tmp_str, 0, sizeof(_tmp_str));
#if defined ENABLE_MCTF_EXT
strength_idx = 2;
#endif
//the order of arguments is:
// MctfMode:BitsPerPixel:Strength:ME:Overlap:DB
// try to read fs defined as a value:
bool res = ArgConvert(strInput[i + 1], strength_idx, MSDK_STRING("%hd:%*c"), &_strength, _strength, ParsedArgsNumber);
if (!res)
{
bFSByValue = false;
// if it was not possible, try to get a file-name (upto 15 chars):
res = ArgConvert(strInput[i + 1], strength_idx, file_pattern.str().c_str(), &(_tmp_str[0]), max_name_len, ParsedArgsNumber);
if (res)
{
msdk_fstream fs_file(_tmp_str, std::ios_base::in);
if (!fs_file.is_open())
{
msdk_printf(MSDK_STRING("MCTF Filter-strength file is not exist; decay to default FS value;.\n"));
bFSByValue = true;
}
else
{
mfxU32 nOfRTParams(0);
for (msdk_string line; std::getline(fs_file, line, msdk_char(',')) && nOfRTParams < max_elems_in_file; ++nOfRTParams)
{
// currently, there is just 1 param in the file;
sMctfRunTimeParam tmp;
if(msdk_sscanf(line.c_str(), MSDK_STRING("%hu:%*c"), &(tmp.FilterStrength)))
pParams->mctfParam.rtParams.RunTimeParams.push_back(tmp);
else
{
msdk_printf(MSDK_STRING("there was an error met during parsing FS file;.only a few values were parsed.\n"));
break;
}
}
}
}
else
bFSByValue = true;
}
#if defined ENABLE_MCTF_EXT
mfxU16 _refnum(2);
mfxF64 _bitsperpixel(0.0);
mfxU16 _me_precision(0);
mfxU16 _overlap(0);
mfxU16 _deblock(0);
ArgConvert(strInput[i + 1], 0, MSDK_STRING("%hd:%*c"), &_refnum, _refnum, ParsedArgsNumber);
ArgConvert(strInput[i + 1], 1, MSDK_STRING("%lf:%*c"), &_bitsperpixel, _bitsperpixel, ParsedArgsNumber);
ArgConvert(strInput[i + 1], 3, MSDK_STRING("%hd:%*c"), &_me_precision, _me_precision, ParsedArgsNumber);
ArgConvert(strInput[i + 1], 4, MSDK_STRING("%hd:%*c"), &_overlap, _overlap, ParsedArgsNumber);
ArgConvert(strInput[i + 1], 5, MSDK_STRING("%hd:%*c"), &_deblock, _deblock, ParsedArgsNumber);
#endif
if (0 == ParsedArgsNumber)
{
pParams->mctfParam.mode = VPP_FILTER_ENABLED_DEFAULT;
msdk_printf(MSDK_STRING("MCTF works in default mode; no parameters are passed.\n"));
}
else
{
pParams->mctfParam.mode = VPP_FILTER_ENABLED_CONFIGURED;
pParams->mctfParam.rtParams.Restart();
if (bFSByValue)
{
pParams->mctfParam.params.FilterStrength = _strength;
}
else
{
// take very first FS value from the file and use it as a value for FilterStrength
if(pParams->mctfParam.rtParams.GetCurParam())
{
pParams->mctfParam.params.FilterStrength = pParams->mctfParam.rtParams.GetCurParam()->FilterStrength;
}
}
#if defined ENABLE_MCTF_EXT
pParams->mctfParam.params.BitsPerPixelx100k = mfxU32(_bitsperpixel*MCTF_BITRATE_MULTIPLIER);
switch (_refnum) {
case 0:
pParams->mctfParam.params.TemporalMode = MFX_MCTF_TEMPORAL_MODE_SPATIAL;
break;
case 1:
pParams->mctfParam.params.TemporalMode = MFX_MCTF_TEMPORAL_MODE_1REF;
break;
case 2:
pParams->mctfParam.params.TemporalMode = MFX_MCTF_TEMPORAL_MODE_2REF;
break;
case 3:
pParams->mctfParam.params.TemporalMode = MFX_MCTF_TEMPORAL_MODE_4REF;
break;
default:
pParams->mctfParam.params.TemporalMode = MFX_MCTF_TEMPORAL_MODE_UNKNOWN;
};
switch (_deblock) {
case 0:
pParams->mctfParam.params.Deblocking = MFX_CODINGOPTION_OFF;
break;
case 1:
pParams->mctfParam.params.Deblocking = MFX_CODINGOPTION_ON;
break;
default:
pParams->mctfParam.params.Deblocking = MFX_CODINGOPTION_UNKNOWN;
};
switch (_overlap) {
case 0:
pParams->mctfParam.params.Overlap = MFX_CODINGOPTION_OFF;
break;
case 1:
pParams->mctfParam.params.Overlap = MFX_CODINGOPTION_ON;
break;
default:
pParams->mctfParam.params.Overlap = MFX_CODINGOPTION_UNKNOWN;
};
switch (_me_precision) {
case 0:
pParams->mctfParam.params.MVPrecision = MFX_MVPRECISION_INTEGER;
break;
case 1:
pParams->mctfParam.params.MVPrecision = MFX_MVPRECISION_QUARTERPEL;
break;
default:
pParams->mctfParam.params.MVPrecision = MFX_MVPRECISION_UNKNOWN;
};
#endif
}
if(ParsedArgsNumber)
i++;
}
else
{
msdk_printf(MSDK_STRING("MCTF works in default mode; no parameters are passed.\n"));
}
}
}
#endif
// return values:
// 0 if argv[i] is processed successfully (MFX_ERR_NONE)
// < 1 if argv[i] is processed and generates an error OR argv[i] is not processed (no match)
mfxStatus ParseAdditionalParams(msdk_char *argv[], mfxU32 argc, mfxU32& i, TranscodingSample::sInputParams& InputParams)
{
if (0 == msdk_strcmp(argv[i], MSDK_STRING("-AvcTemporalLayers")))
{
InputParams.nAvcTemp = 1;
VAL_CHECK(i + 1 >= argc, i, argv[i]);
mfxU16 arr[8] = { 0,0,0,0,0,0,0,0 };
int j, k;
k = msdk_sscanf(argv[i + 1], MSDK_STRING("%hu %hu %hu %hu %hu %hu %hu %hu"), &arr[0], &arr[1], &arr[2], &arr[3], &arr[4], &arr[5], &arr[6], &arr[7]);
if (k != 8)
{
PrintError(argv[0], MSDK_STRING("Invalid number of layers for AvcTemporalLayers"));
return MFX_ERR_UNSUPPORTED;
}
for (j = 0; j < 8; j++)
{
InputParams.nAvcTemporalLayers[j] = arr[j];
}
i += 1;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-BaseLayerPID")))
{
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.nBaseLayerPID))
{
PrintError(argv[0], MSDK_STRING("BaseLayerPID is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-SPSId")))
{
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.nSPSId))
{
PrintError(argv[0], MSDK_STRING("SPSId is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-PPSId")))
{
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.nPPSId))
{
PrintError(argv[0], MSDK_STRING("PPSId is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-lowpower:on")))
{
InputParams.enableQSVFF=true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-lowpower:off")))
{
InputParams.enableQSVFF=false;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-PicTimingSEI:on")))
{
InputParams.nPicTimingSEI = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-PicTimingSEI:off")))
{
InputParams.nPicTimingSEI = MFX_CODINGOPTION_OFF;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-NalHrdConformance:on")))
{
InputParams.nNalHrdConformance = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-NalHrdConformance:off")))
{
InputParams.nNalHrdConformance = MFX_CODINGOPTION_OFF;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-VuiNalHrdParameters:on")))
{
InputParams.nVuiNalHrdParameters = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-VuiNalHrdParameters:off")))
{
InputParams.nVuiNalHrdParameters = MFX_CODINGOPTION_OFF;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-BitrateLimit:on")))
{
InputParams.BitrateLimit = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-BitrateLimit:off")))
{
InputParams.BitrateLimit = MFX_CODINGOPTION_OFF;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-AdaptiveI:on")))
{
InputParams.AdaptiveI = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-AdaptiveI:off")))
{
InputParams.AdaptiveI = MFX_CODINGOPTION_OFF;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-AdaptiveB:on")))
{
InputParams.AdaptiveB = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-AdaptiveB:off")))
{
InputParams.AdaptiveB = MFX_CODINGOPTION_OFF;
}
#if (defined(_WIN32) || defined(_WIN64)) && (MFX_VERSION >= 1031)
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-iGfx")))
{
InputParams.bPrefferiGfx = true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-dGfx")))
{
InputParams.bPrefferdGfx = true;
}
#endif
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-avbr")))
{
InputParams.nRateControlMethod = MFX_RATECONTROL_AVBR;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-convergence")))
{
VAL_CHECK(i+1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.Convergence))
{
PrintError(argv[0], MSDK_STRING("Convergence param is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-accuracy")))
{
VAL_CHECK(i+1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.Accuracy))
{
PrintError(argv[0], MSDK_STRING("Accuracy param is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-qvbr")))
{
InputParams.nRateControlMethod = MFX_RATECONTROL_QVBR;
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.QVBRQuality))
{
PrintError(argv[0], MSDK_STRING("QVBRQuality param is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-icq")))
{
InputParams.nRateControlMethod = MFX_RATECONTROL_ICQ;
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.ICQQuality))
{
PrintError(argv[0], MSDK_STRING("ICQQuality param is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-dec::sys")))
{
InputParams.DecOutPattern = MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-ext_allocator")) || 0 == msdk_strcmp(argv[i], MSDK_STRING("-MemType::video")))
{
InputParams.bUseOpaqueMemory = false;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-sys")) || 0 == msdk_strcmp(argv[i], MSDK_STRING("-MemType::system")))
{
InputParams.bUseOpaqueMemory = false;
InputParams.bForceSysMem = true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-opaq")) || 0 == msdk_strcmp(argv[i], MSDK_STRING("-MemType::opaque")))
{
InputParams.bUseOpaqueMemory = true;
}
#if (MFX_VERSION >= 1027)
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-TargetBitDepthLuma")))
{
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.TargetBitDepthLuma))
{
PrintError(MSDK_STRING("TargetBitDepthLuma param is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-TargetBitDepthChroma")))
{
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.TargetBitDepthChroma))
{
PrintError(MSDK_STRING("TargetBitDepthChroma param is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
#endif
else
{
// no matching argument was found
return MFX_ERR_NOT_FOUND;
}
return MFX_ERR_NONE;
}
mfxStatus ParseVPPCmdLine(msdk_char *argv[], mfxU32 argc, mfxU32& index, TranscodingSample::sInputParams* params, mfxU32& skipped)
{
if (0 == msdk_strcmp(argv[index], MSDK_STRING("-denoise")))
{
VAL_CHECK(index+1 == argc, index, argv[index]);
index++;
if (MFX_ERR_NONE != msdk_opt_read(argv[index], params->DenoiseLevel) || !(params->DenoiseLevel>=0 && params->DenoiseLevel<=100))
{
PrintError(NULL, MSDK_STRING("-denoise \"%s\" is invalid"), argv[index]);
return MFX_ERR_UNSUPPORTED;
}
skipped+=2;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-detail")))
{
VAL_CHECK(index+1 == argc, index, argv[index]);
index++;
if (MFX_ERR_NONE != msdk_opt_read(argv[index], params->DetailLevel) || !(params->DetailLevel>=0 && params->DetailLevel<=100))
{
PrintError(NULL, MSDK_STRING("-detail \"%s\" is invalid"), argv[index]);
return MFX_ERR_UNSUPPORTED;
}
skipped+=2;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-FRC::PT")))
{
params->FRCAlgorithm=MFX_FRCALGM_PRESERVE_TIMESTAMP;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-FRC::DT")))
{
params->FRCAlgorithm=MFX_FRCALGM_DISTRIBUTED_TIMESTAMP;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-FRC::INTERP")))
{
params->FRCAlgorithm=MFX_FRCALGM_FRAME_INTERPOLATION;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-deinterlace")))
{
params->bEnableDeinterlacing = true;
params->DeinterlacingMode=0;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-deinterlace::ADI")))
{
params->bEnableDeinterlacing = true;
params->DeinterlacingMode=MFX_DEINTERLACING_ADVANCED;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-deinterlace::ADI_SCD")))
{
params->bEnableDeinterlacing = true;
params->DeinterlacingMode=MFX_DEINTERLACING_ADVANCED_SCD;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-deinterlace::BOB")))
{
params->bEnableDeinterlacing = true;
params->DeinterlacingMode=MFX_DEINTERLACING_BOB;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-deinterlace::ADI_NO_REF")))
{
params->bEnableDeinterlacing = true;
params->DeinterlacingMode=MFX_DEINTERLACING_ADVANCED_NOREF;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-scaling_mode")) )
{
VAL_CHECK(index+1 == argc, index, argv[index]);
index++;
if (0 == msdk_strcmp(argv[index], MSDK_STRING("lowpower")) )
params->ScalingMode = MFX_SCALING_MODE_LOWPOWER;
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("quality")) )
params->ScalingMode = MFX_SCALING_MODE_QUALITY;
else
{
PrintError(NULL, MSDK_STRING("-scaling_mode \"%s\" is invalid"), argv[index]);
return MFX_ERR_UNSUPPORTED;
}
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-ec::rgb4")))
{
params->EncoderFourCC = MFX_FOURCC_RGB4;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-ec::yuy2")))
{
params->EncoderFourCC = MFX_FOURCC_YUY2;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-ec::nv12")))
{
params->EncoderFourCC = MFX_FOURCC_NV12;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-ec::nv16")))
{
params->EncoderFourCC = MFX_FOURCC_NV16;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-ec::p010")))
{
params->EncoderFourCC = MFX_FOURCC_P010;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-ec::p210")))
{
params->EncoderFourCC = MFX_FOURCC_P210;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-dc::p010")))
{
params->DecoderFourCC = MFX_FOURCC_P010;
return MFX_ERR_NONE;
}
#if (MFX_VERSION >= 1031)
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-dc::p016")))
{
params->DecoderFourCC = MFX_FOURCC_P016;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-dc::y216")))
{
params->DecoderFourCC = MFX_FOURCC_Y216;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-dc::y416")))
{
params->DecoderFourCC = MFX_FOURCC_Y216;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-ec::p016")))
{
params->EncoderFourCC = MFX_FOURCC_P016;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-ec::y216")))
{
params->EncoderFourCC = MFX_FOURCC_Y216;
return MFX_ERR_NONE;
}
#endif
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-dc::rgb4")))
{
params->DecoderFourCC = MFX_FOURCC_RGB4;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-dc::yuy2")))
{
params->DecoderFourCC = MFX_FOURCC_YUY2;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-dc::nv12")))
{
params->DecoderFourCC = MFX_FOURCC_NV12;
return MFX_ERR_NONE;
}
#if (MFX_VERSION >= 1027)
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-dc::y210")))
{
params->DecoderFourCC = MFX_FOURCC_Y210;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-dc::y410")))
{
params->DecoderFourCC = MFX_FOURCC_Y410;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-ec::y210")))
{
params->EncoderFourCC = MFX_FOURCC_Y210;
return MFX_ERR_NONE;
}
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-ec::y410")))
{
params->EncoderFourCC = MFX_FOURCC_Y410;
return MFX_ERR_NONE;
}
#endif
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("-field_processing")) )
{
VAL_CHECK(index+1 == argc, index, argv[index]);
index++;
if (0 == msdk_strcmp(argv[index], MSDK_STRING("t2t")) )
params->fieldProcessingMode = FC_T2T;
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("t2b")) )
params->fieldProcessingMode = FC_T2B;
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("b2t")) )
params->fieldProcessingMode = FC_B2T;
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("b2b")) )
params->fieldProcessingMode = FC_B2B;
else if (0 == msdk_strcmp(argv[index], MSDK_STRING("fr2fr")) )
params->fieldProcessingMode = FC_FR2FR;
else
{
PrintError(NULL, MSDK_STRING("-field_processing \"%s\" is invalid"), argv[index]);
return MFX_ERR_UNSUPPORTED;
}
return MFX_ERR_NONE;
}
return MFX_ERR_MORE_DATA;
}
mfxStatus CmdProcessor::ParseParamsForOneSession(mfxU32 argc, msdk_char *argv[])
{
mfxStatus sts = MFX_ERR_NONE;
mfxStatus stsExtBuf = MFX_ERR_NONE;
mfxStatus stsAddlParams = MFX_ERR_NONE;
mfxU32 skipped = 0;
// save original cmd line for debug purpose
msdk_stringstream cmd;
for (mfxU32 i = 0; i <argc; i++)
cmd <<argv[i] << MSDK_STRING(" ");
m_lines.push_back(cmd.str());
TranscodingSample::sInputParams InputParams;
if (m_nTimeout)
InputParams.nTimeout = m_nTimeout;
if (bRobustFlag)
InputParams.bRobustFlag = true;
if (bSoftRobustFlag)
InputParams.bSoftRobustFlag = true;
InputParams.shouldUseGreedyFormula = shouldUseGreedyFormula;
InputParams.statisticsWindowSize = statisticsWindowSize;
InputParams.statisticsLogFile = statisticsLogFile;
//bind to a dump-log-file name
InputParams.DumpLogFileName = DumpLogFileName;
if (0 == msdk_strcmp(argv[0], MSDK_STRING("set")))
{
if (argc != 3) {
msdk_printf(MSDK_STRING("error: number of arguments for 'set' options is wrong"));
return MFX_ERR_UNSUPPORTED;
}
sts = ParseOption__set(argv[1], argv[2]);
return sts;
}
// default implementation
InputParams.libType = MFX_IMPL_HARDWARE_ANY;
#if defined(_WIN32) || defined(_WIN64)
InputParams.libType = MFX_IMPL_HARDWARE_ANY | MFX_IMPL_VIA_D3D11;
#endif
InputParams.bUseOpaqueMemory = false;
InputParams.eModeExt = Native;
for (mfxU32 i = 0; i < argc; i++)
{
// process multi-character options
if ( (0 == msdk_strncmp(MSDK_STRING("-i::"), argv[i], msdk_strlen(MSDK_STRING("-i::"))))
&& (0 != msdk_strncmp(argv[i]+4, MSDK_STRING("source"), msdk_strlen(MSDK_STRING("source")))) )
{
sts = StrFormatToCodecFormatFourCC(argv[i]+4, InputParams.DecodeId);
if (sts != MFX_ERR_NONE)
{
return MFX_ERR_UNSUPPORTED;
}
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
SIZE_CHECK((msdk_strlen(argv[i])+1) > MSDK_ARRAY_LEN(InputParams.strSrcFile));
msdk_opt_read(argv[i], InputParams.strSrcFile);
if (InputParams.eMode == Source)
{
switch(InputParams.DecodeId)
{
case MFX_CODEC_MPEG2:
case MFX_CODEC_HEVC:
case MFX_CODEC_AVC:
case MFX_CODEC_VC1:
case MFX_CODEC_VP9:
case MFX_CODEC_AV1:
case CODEC_MVC:
case MFX_CODEC_JPEG:
return MFX_ERR_UNSUPPORTED;
}
}
if (InputParams.DecodeId == CODEC_MVC)
{
InputParams.DecodeId = MFX_CODEC_AVC;
InputParams.bIsMVC = true;
}
}
else if ( (0 == msdk_strncmp(MSDK_STRING("-o::"), argv[i], msdk_strlen(MSDK_STRING("-o::"))))
&& (0 != msdk_strncmp(argv[i]+4, MSDK_STRING("sink"), msdk_strlen(MSDK_STRING("sink")))) )
{
sts = StrFormatToCodecFormatFourCC(argv[i]+4, InputParams.EncodeId);
if (sts != MFX_ERR_NONE)
{
return MFX_ERR_UNSUPPORTED;
}
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
SIZE_CHECK((msdk_strlen(argv[i])+1) > MSDK_ARRAY_LEN(InputParams.strDstFile));
msdk_opt_read(argv[i], InputParams.strDstFile);
if (InputParams.eMode == Sink || InputParams.bIsMVC)
{
switch(InputParams.EncodeId)
{
case MFX_CODEC_MPEG2:
case MFX_CODEC_HEVC:
case MFX_CODEC_AVC:
case MFX_CODEC_JPEG:
case MFX_CODEC_DUMP:
return MFX_ERR_UNSUPPORTED;
}
}
if (InputParams.EncodeId == CODEC_MVC)
{
if (InputParams.eMode == Sink)
return MFX_ERR_UNSUPPORTED;
InputParams.EncodeId = MFX_CODEC_AVC;
InputParams.bIsMVC = true;
}
}
#if MFX_VERSION >= 1022
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-roi_file")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
msdk_char strRoiFile[MSDK_MAX_FILENAME_LEN];
SIZE_CHECK((msdk_strlen(argv[i])+1) > MSDK_ARRAY_LEN(strRoiFile));
msdk_opt_read(argv[i], strRoiFile);
if(!ParseROIFile(strRoiFile, InputParams.m_ROIData)) {
PrintError(MSDK_STRING("Incorrect ROI file: \"%s\" "), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-p")))
{
if (m_PerfFILE)
{
msdk_printf(MSDK_STRING("error: only one performance file is supported"));
return MFX_ERR_UNSUPPORTED;
}
--argc;
++argv;
if (!argv[i]) {
msdk_printf(MSDK_STRING("error: no argument given for '-p' option\n"));
}
MSDK_FOPEN(m_PerfFILE, argv[i], MSDK_STRING("w"));
if (NULL == m_PerfFILE)
{
msdk_printf(MSDK_STRING("error: performance file \"%s\" not found"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-roi_qpmap")))
{
InputParams.bROIasQPMAP = true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-extmbqp")))
{
InputParams.bExtMBQP = true;
}
#endif //MFX_VERSION >= 1022
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-sw")))
{
InputParams.libType = MFX_IMPL_SOFTWARE;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-hw")))
{
#if defined(_WIN32) || defined(_WIN64)
InputParams.libType = MFX_IMPL_HARDWARE_ANY | MFX_IMPL_VIA_D3D11;
#elif defined(LIBVA_SUPPORT)
InputParams.libType = MFX_IMPL_HARDWARE_ANY;
#endif
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-hw_d3d11")))
{
InputParams.libType = MFX_IMPL_HARDWARE_ANY | MFX_IMPL_VIA_D3D11;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-hw_d3d9")))
{
InputParams.libType = MFX_IMPL_HARDWARE_ANY | MFX_IMPL_VIA_D3D9;
}
#if (defined(LINUX32) || defined(LINUX64))
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-device")))
{
if (!InputParams.strDevicePath.empty()){
msdk_printf(MSDK_STRING("error: you can specify only one device\n"));
return MFX_ERR_UNSUPPORTED;
}
VAL_CHECK(i+1 == argc, i, argv[i]);
InputParams.strDevicePath = argv[++i];
}
#endif
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-perf_opt")))
{
InputParams.bIsPerf = true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-robust")))
{
InputParams.bRobustFlag = true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-robust:soft")))
{
InputParams.bSoftRobustFlag = true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-threads")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nThreadsNum))
{
PrintError(MSDK_STRING("Threads number is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-f")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
// Temporary check for giving priority to -fe option
if(!InputParams.dVPPOutFramerate)
{
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.dVPPOutFramerate))
{
PrintError(MSDK_STRING("FrameRate \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-fe")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.dVPPOutFramerate))
{
PrintError(MSDK_STRING("FrameRate \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-fps")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nFPS))
{
PrintError(MSDK_STRING("FPS limit \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-b")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nBitRate))
{
PrintError(MSDK_STRING("BitRate \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-bm")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nBitRateMultiplier))
{
PrintError(MSDK_STRING("Bitrate multiplier \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-wb")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.WinBRCMaxAvgKbps))
{
PrintError(MSDK_STRING("Maximum bitrate for sliding window \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-ws")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.WinBRCSize))
{
PrintError(MSDK_STRING("Sliding window size \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-hrd")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.BufferSizeInKB))
{
PrintError(MSDK_STRING("Frame buffer size \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-dist")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.GopRefDist))
{
PrintError(MSDK_STRING("GOP reference distance \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-gop_size")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.GopPicSize))
{
PrintError(MSDK_STRING("GOP size \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-num_ref")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.NumRefFrame))
{
PrintError(MSDK_STRING("Number of reference frames \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-trows")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nEncTileRows))
{
PrintError(MSDK_STRING("Encoding tile row count \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-tcols")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nEncTileCols))
{
PrintError(MSDK_STRING("Encoding tile column count \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-CodecLevel")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.CodecLevel))
{
PrintError(MSDK_STRING("CodecLevel \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-CodecProfile")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.CodecProfile))
{
PrintError(MSDK_STRING("CodecProfile \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-MaxKbps")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.MaxKbps))
{
PrintError(MSDK_STRING("MaxKbps \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-InitialDelayInKB")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.InitialDelayInKB))
{
PrintError(MSDK_STRING("InitialDelayInKB \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-GopOptFlag:closed")))
{
InputParams.GopOptFlag = MFX_GOP_CLOSED;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-GopOptFlag:strict")))
{
InputParams.GopOptFlag = MFX_GOP_STRICT;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-bref")))
{
InputParams.nBRefType = MFX_B_REF_PYRAMID;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-nobref")))
{
InputParams.nBRefType = MFX_B_REF_OFF;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-gpb:on")))
{
InputParams.GPB = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-gpb:off")))
{
InputParams.GPB = MFX_CODINGOPTION_OFF;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-TransformSkip:on")))
{
InputParams.nTransformSkip = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-TransformSkip:off")))
{
InputParams.nTransformSkip = MFX_CODINGOPTION_OFF;
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-u")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
InputParams.nTargetUsage = StrToTargetUsage(argv[i]);
if (!InputParams.nTargetUsage)
{
PrintError(MSDK_STRING(" \"%s\" target usage is invalid. Balanced will be used."), argv[i]);
InputParams.nTargetUsage = MFX_TARGETUSAGE_BALANCED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-WeightedPred::default")))
{
InputParams.WeightedPred = MFX_WEIGHTED_PRED_DEFAULT;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-WeightedPred::implicit")))
{
InputParams.WeightedPred = MFX_WEIGHTED_PRED_IMPLICIT;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-WeightedBiPred::default")))
{
InputParams.WeightedBiPred = MFX_WEIGHTED_PRED_DEFAULT;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-WeightedBiPred::implicit")))
{
InputParams.WeightedBiPred = MFX_WEIGHTED_PRED_IMPLICIT;
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-q")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nQuality))
{
PrintError(MSDK_STRING(" \"%s\" quality is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-w")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nDstWidth))
{
PrintError(MSDK_STRING("width \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-h")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nDstHeight))
{
PrintError(MSDK_STRING("height \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-l")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nSlices))
{
PrintError(MSDK_STRING("numSlices \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-mss")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nMaxSliceSize))
{
PrintError(MSDK_STRING("maxSliceSize \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-async")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nAsyncDepth))
{
PrintError(MSDK_STRING("async \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-join")))
{
InputParams.bIsJoin = true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-priority")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.priority))
{
PrintError(MSDK_STRING("priority \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-i::source")))
{
if (InputParams.eMode != Native)
{
PrintError(NULL,"-i::source cannot be used here");
return MFX_ERR_UNSUPPORTED;
}
InputParams.eMode = Source;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-o::sink")))
{
if (InputParams.eMode != Native)
{
PrintError(NULL,"-o::sink cannot be used here");
return MFX_ERR_UNSUPPORTED;
}
InputParams.eMode = Sink;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp_comp")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
/* NB! numSurf4Comp should be equal to Number of decoding session */
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.numSurf4Comp))
{
PrintError(MSDK_STRING("-n \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
/* This is can init early */
if (InputParams.eModeExt == Native)
InputParams.eModeExt = VppComp;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp_comp_only")))
{
/* for VPP comp with rendering we have to use ext allocator */
#ifdef LIBVA_SUPPORT
InputParams.libvaBackend = MFX_LIBVA_DRM;
#endif
InputParams.bUseOpaqueMemory = false;
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
/* NB! numSurf4Comp should be equal to Number of decoding session */
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.numSurf4Comp))
{
PrintError(MSDK_STRING("-n \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
/* This is can init early */
if (InputParams.eModeExt == Native)
InputParams.eModeExt = VppCompOnly;
bool bOpaqueFlagChanged = false;
for (mfxU32 j = 0; j < m_SessionArray.size(); j++)
{
if (m_SessionArray[j].bUseOpaqueMemory)
{
m_SessionArray[j].bUseOpaqueMemory = false;
bOpaqueFlagChanged = true;
}
}
if (bOpaqueFlagChanged)
{
msdk_printf(MSDK_STRING("WARNING: internal allocators were disabled because of composition+rendering requirement \n\n"));
}
}
else if (0 == msdk_strncmp(MSDK_STRING("-vpp_comp_dump"), argv[i], msdk_strlen(MSDK_STRING("-vpp_comp_dump"))))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
SIZE_CHECK((msdk_strlen(argv[i])+1) > MSDK_ARRAY_LEN(InputParams.strDumpVppCompFile));
msdk_opt_read(argv[i], InputParams.strDumpVppCompFile);
}
#if defined(LIBVA_X11_SUPPORT)
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-rx11")))
{
InputParams.libvaBackend = MFX_LIBVA_X11;
}
#endif
#if defined(LIBVA_WAYLAND_SUPPORT)
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-rwld")))
{
InputParams.nRenderWinX = 0;
InputParams.nRenderWinY = 0;
InputParams.bPerfMode = false;
InputParams.libvaBackend = MFX_LIBVA_WAYLAND;
}
#endif
#if defined(LIBVA_DRM_SUPPORT)
else if (0 == msdk_strncmp(argv[i], MSDK_STRING("-rdrm"), 5))
{
InputParams.libvaBackend = MFX_LIBVA_DRM_MODESET;
InputParams.monitorType = getMonitorType(&argv[i][5]);
if (argv[i][5]) {
if (argv[i][5] != '-') {
PrintError(MSDK_STRING("unsupported monitor type"));
return MFX_ERR_UNSUPPORTED;
}
InputParams.monitorType = getMonitorType(&argv[i][6]);
if (InputParams.monitorType >= MFX_MONITOR_MAXNUMBER) {
PrintError(MSDK_STRING("unsupported monitor type"));
return MFX_ERR_UNSUPPORTED;
}
} else {
InputParams.monitorType = MFX_MONITOR_AUTO; // that's case of "-rdrm" pure option
}
}
#endif
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp::sys")))
{
InputParams.VppOutPattern = MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp::vid")))
{
InputParams.VppOutPattern = MFX_IOPATTERN_OUT_VIDEO_MEMORY;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp_comp_dst_x")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nVppCompDstX))
{
PrintError(MSDK_STRING("vpp_comp_dst_x %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
if (InputParams.eModeExt != VppComp)
InputParams.eModeExt = VppComp;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp_comp_dst_y")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nVppCompDstY))
{
PrintError(MSDK_STRING("-vpp_comp_dst_y %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
if (InputParams.eModeExt != VppComp)
InputParams.eModeExt = VppComp;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp_comp_dst_w")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nVppCompDstW))
{
PrintError(MSDK_STRING("-vpp_comp_dst_w %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
if (InputParams.eModeExt != VppComp)
InputParams.eModeExt = VppComp;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp_comp_dst_h")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nVppCompDstH))
{
PrintError(MSDK_STRING("-vpp_comp_dst_h %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
if (InputParams.eModeExt != VppComp)
InputParams.eModeExt = VppComp;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp_comp_src_w")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nVppCompSrcW))
{
PrintError(MSDK_STRING("-vpp_comp_src_w %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
if (InputParams.eModeExt != VppComp)
InputParams.eModeExt = VppComp;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp_comp_src_h")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nVppCompSrcH))
{
PrintError(MSDK_STRING("-vpp_comp_src_h %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
if (InputParams.eModeExt != VppComp)
InputParams.eModeExt = VppComp;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp_comp_num_tiles")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.numTiles4Comp))
{
PrintError(MSDK_STRING("-vpp_comp_num_tiles %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
if (InputParams.eModeExt != VppCompOnly)
InputParams.eModeExt = VppCompOnly;
}
#if MFX_VERSION >= 1023
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp_comp_tile_id")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nVppCompTileId))
{
PrintError(MSDK_STRING("-vpp_comp_tile_id %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
#endif
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vpp_comp_render")))
{
if (InputParams.eModeExt != VppComp)
InputParams.eModeExt = VppComp;
}
#if MFX_VERSION >= 1022
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-dec_postproc")))
{
InputParams.bDecoderPostProcessing = true;
}
#endif //MFX_VERSION >= 1022
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-n")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.MaxFrameNumber))
{
PrintError(MSDK_STRING("-n %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-angle")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nRotationAngle))
{
PrintError(MSDK_STRING("-angle %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
if (InputParams.strVPPPluginDLLPath[0] == '\0') {
msdk_opt_read(MSDK_CPU_ROTATE_PLUGIN, InputParams.strVPPPluginDLLPath);
}
}
#if (MFX_VERSION >= 1025)
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-mfe_frames")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.numMFEFrames))
{
PrintError(MSDK_STRING("-mfe_frames %s num frames is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-mfe_mode")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.MFMode))
{
PrintError(MSDK_STRING("-mfe_mode %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if(0 == msdk_strcmp(argv[i], MSDK_STRING("-mfe_timeout")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.mfeTimeout))
{
PrintError(MSDK_STRING("-mfe_timeout %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
#endif
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-timeout")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nTimeout))
{
PrintError(MSDK_STRING("-timeout %s is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
skipped+=2;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-dump")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.strMfxParamsDumpFile))
{
PrintError(MSDK_STRING("Dump file name \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-robust")))
{
InputParams.bRobustFlag = true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-opencl")))
{
msdk_opt_read(MSDK_OCL_ROTATE_PLUGIN, InputParams.strVPPPluginDLLPath);
InputParams.bOpenCL = true;
}
// output PicStruct
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-la_ext")))
{
InputParams.bEnableExtLA = true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-la")))
{
InputParams.bLABRC = true;
InputParams.nRateControlMethod = MFX_RATECONTROL_LA;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vbr")))
{
InputParams.nRateControlMethod = MFX_RATECONTROL_VBR;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-cbr")))
{
InputParams.nRateControlMethod = MFX_RATECONTROL_CBR;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-vcm")))
{
InputParams.nRateControlMethod = MFX_RATECONTROL_VCM;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-bpyr")))
{
InputParams.bEnableBPyramid = true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-lad")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
InputParams.nRateControlMethod = MFX_RATECONTROL_LA;
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.nLADepth))
{
PrintError(MSDK_STRING("look ahead depth \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-pe")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
InputParams.encoderPluginParams = ParsePluginGuid(argv[i + 1]);
if (AreGuidsEqual(InputParams.encoderPluginParams.pluginGuid, MSDK_PLUGINGUID_NULL))
{
PrintError(MSDK_STRING("Invalid encoder guid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
i++;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-pd")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
InputParams.decoderPluginParams = ParsePluginGuid(argv[i + 1]);
if (AreGuidsEqual(InputParams.encoderPluginParams.pluginGuid, MSDK_PLUGINGUID_NULL))
{
PrintError(MSDK_STRING("Invalid decoder guid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
i++;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-override_decoder_framerate")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.dDecoderFrameRateOverride))
{
PrintError(MSDK_STRING("Framerate \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-override_encoder_framerate")))
{
VAL_CHECK(i+1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.dEncoderFrameRateOverride))
{
PrintError(MSDK_STRING("Framerate \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-override_encoder_picstruct")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
i++;
if (MFX_ERR_NONE != msdk_opt_read(argv[i], InputParams.EncoderPicstructOverride))
{
PrintError(MSDK_STRING("Picstruct \"%s\" is invalid"), argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-gpucopy::on")))
{
InputParams.nGpuCopyMode = MFX_GPUCOPY_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-gpucopy::off")))
{
InputParams.nGpuCopyMode = MFX_GPUCOPY_OFF;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-repartitioncheck::on")))
{
InputParams.RepartitionCheckMode = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-repartitioncheck::off")))
{
InputParams.RepartitionCheckMode = MFX_CODINGOPTION_OFF;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-cqp")))
{
InputParams.nRateControlMethod = MFX_RATECONTROL_CQP;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-qpi")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.nQPI))
{
PrintError(MSDK_STRING("Quantizer for I frames is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-qpp")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.nQPP))
{
PrintError(MSDK_STRING("Quantizer for P frames is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-qpb")))
{
VAL_CHECK(i + 1 == argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.nQPB))
{
PrintError(MSDK_STRING("Quantizer for B frames is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-DisableQPOffset")))
{
InputParams.bDisableQPOffset=true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-qsv-ff")))
{
InputParams.enableQSVFF=true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-single_texture_d3d11")))
{
InputParams.bSingleTexture = true;
}
#if (MFX_VERSION >= 1024)
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-extbrc::on")))
{
InputParams.nExtBRC = EXTBRC_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-extbrc::off")))
{
InputParams.nExtBRC = EXTBRC_OFF;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-extbrc::implicit")))
{
InputParams.nExtBRC = EXTBRC_IMPLICIT;
}
#endif
#if (MFX_VERSION >= 1026)
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-ExtBrcAdaptiveLTR:on")))
{
InputParams.ExtBrcAdaptiveLTR = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-ExtBrcAdaptiveLTR:off")))
{
InputParams.ExtBrcAdaptiveLTR = MFX_CODINGOPTION_OFF;
}
#endif
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-pp")))
{
InputParams.shouldPrintPresets = true;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-preset")))
{
msdk_char presetName[MSDK_MAX_FILENAME_LEN];
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], presetName))
{
PrintError(MSDK_STRING("Preset Name is not defined"));
return MFX_ERR_UNSUPPORTED;
}
InputParams.PresetMode = CPresetManager::PresetNameToMode(presetName);
if (InputParams.PresetMode == PRESET_MAX_MODES)
{
PrintError(MSDK_STRING("Preset Name is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-ir_type")))
{
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.IntRefType))
{
PrintError( MSDK_STRING("Intra refresh type is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-ir_cycle_size")))
{
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.IntRefCycleSize))
{
PrintError( MSDK_STRING("IR refresh cycle size param is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-ir_qp_delta")))
{
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.IntRefQPDelta))
{
PrintError( MSDK_STRING("IR QP delta param is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-ir_cycle_dist")))
{
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.IntRefCycleDist))
{
PrintError( MSDK_STRING("IR cycle distance param is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-LowDelayBRC")))
{
InputParams.LowDelayBRC = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-amfs:on")))
{
InputParams.nAdaptiveMaxFrameSize = MFX_CODINGOPTION_ON;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-amfs:off")))
{
InputParams.nAdaptiveMaxFrameSize = MFX_CODINGOPTION_OFF;
}
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-mfs")))
{
VAL_CHECK(i + 1 >= argc, i, argv[i]);
if (MFX_ERR_NONE != msdk_opt_read(argv[++i], InputParams.nMaxFrameSize))
{
PrintError( MSDK_STRING("MaxFrameSize is invalid"));
return MFX_ERR_UNSUPPORTED;
}
}
else if ((stsExtBuf = ParseVPPCmdLine(argv,argc,i,&InputParams,skipped)) !=MFX_ERR_MORE_DATA)
{
if (stsExtBuf==MFX_ERR_UNSUPPORTED)
{
return MFX_ERR_UNSUPPORTED;
}
}
#ifdef ENABLE_MCTF
else if (0 == msdk_strcmp(argv[i], MSDK_STRING("-mctf")))
{
ParseMCTFParams(argv, argc, i, &InputParams);
}
#endif
else
{
// WA for compiler error C1061 (too many chained else-if clauses)
// ParseAdditionalParams returns:
// 0 if argv[i] is processed successfully by this function
// < 1 if argv[i] is processed and generates an error
// OR
// if argv[i] was not processed (did not match any switches)
stsAddlParams = ParseAdditionalParams(argv, argc, i, InputParams);
// either unrecognized parameter, or parse error with recognized parameter
if (stsAddlParams)
{
if (stsAddlParams == MFX_ERR_NOT_FOUND)
PrintError(MSDK_STRING("Invalid input argument number %d %s"), i, argv[i]);
return MFX_ERR_UNSUPPORTED;
}
}
}
if (skipped < argc)
{
sts = VerifyAndCorrectInputParams(InputParams);
MSDK_CHECK_STATUS(sts, "VerifyAndCorrectInputParams failed");
m_SessionArray.push_back(InputParams);
}
return MFX_ERR_NONE;
} //mfxStatus CmdProcessor::ParseParamsForOneSession(msdk_char *pLine, mfxU32 length)
mfxStatus CmdProcessor::ParseOption__set(msdk_char* strCodecType, msdk_char* strPluginGuid)
{
mfxU32 codecid = 0;
mfxU32 type = 0;
sPluginParams pluginParams;
//Parse codec type - decoder or encoder
if (0 == msdk_strncmp(MSDK_STRING("-i::"), strCodecType, 4))
{
type = MSDK_VDECODE;
}
else if (0 == msdk_strncmp(MSDK_STRING("-o::"), strCodecType, 4))
{
type = MSDK_VENCODE;
}
else
{
msdk_printf(MSDK_STRING("error: incorrect definition codec type (must be -i:: or -o::)\n"));
return MFX_ERR_UNSUPPORTED;
}
if (StrFormatToCodecFormatFourCC(strCodecType+4, codecid) != MFX_ERR_NONE)
{
msdk_printf(MSDK_STRING("error: codec is unknown\n"));
return MFX_ERR_UNSUPPORTED;
}
if (!IsPluginCodecSupported(codecid))
{
msdk_printf(MSDK_STRING("error: codec is unsupported\n"));
return MFX_ERR_UNSUPPORTED;
}
pluginParams = ParsePluginGuid(strPluginGuid);
if (AreGuidsEqual(pluginParams.pluginGuid, MSDK_PLUGINGUID_NULL))
{
msdk_printf(MSDK_STRING("error: invalid codec guid\n"));
return MFX_ERR_UNSUPPORTED;
}
if (type == MSDK_VDECODE)
m_decoderPlugins.insert(std::pair<mfxU32, sPluginParams>(codecid, pluginParams));
else
m_encoderPlugins.insert(std::pair<mfxU32, sPluginParams>(codecid, pluginParams));
return MFX_ERR_NONE;
};
mfxStatus CmdProcessor::VerifyAndCorrectInputParams(TranscodingSample::sInputParams &InputParams)
{
if (0 == msdk_strlen(InputParams.strSrcFile) && (InputParams.eMode == Sink || InputParams.eMode == Native))
{
PrintError(MSDK_STRING("Source file name not found"));
return MFX_ERR_UNSUPPORTED;
};
if ( 0 == msdk_strlen(InputParams.strDstFile)
&& (InputParams.eMode == Source || InputParams.eMode == Native || InputParams.eMode == VppComp) && InputParams.eModeExt != VppCompOnly)
{
PrintError(MSDK_STRING("Destination file name not found"));
return MFX_ERR_UNSUPPORTED;
};
if (MFX_CODEC_JPEG != InputParams.EncodeId && MFX_CODEC_MPEG2 != InputParams.EncodeId &&
MFX_CODEC_AVC != InputParams.EncodeId && MFX_CODEC_HEVC != InputParams.EncodeId &&
MFX_CODEC_VP9 != InputParams.EncodeId && MFX_CODEC_DUMP != InputParams.EncodeId &&
InputParams.eMode != Sink && InputParams.eModeExt != VppCompOnly)
{
PrintError(MSDK_STRING("Unknown encoder\n"));
return MFX_ERR_UNSUPPORTED;
}
if (MFX_CODEC_MPEG2 != InputParams.DecodeId &&
MFX_CODEC_AVC != InputParams.DecodeId &&
MFX_CODEC_HEVC != InputParams.DecodeId &&
MFX_CODEC_VC1 != InputParams.DecodeId &&
MFX_CODEC_JPEG != InputParams.DecodeId &&
MFX_CODEC_VP9 != InputParams.DecodeId &&
MFX_CODEC_AV1 != InputParams.DecodeId &&
MFX_CODEC_RGB4 != InputParams.DecodeId &&
MFX_CODEC_NV12 != InputParams.DecodeId &&
MFX_CODEC_I420 != InputParams.DecodeId &&
InputParams.eMode != Source)
{
PrintError(MSDK_STRING("Unknown decoder\n"));
return MFX_ERR_UNSUPPORTED;
}
if (MFX_CODEC_I420 == InputParams.DecodeId ||
MFX_CODEC_NV12 == InputParams.DecodeId)
{
InputParams.rawInput = true;
}
else
{
InputParams.rawInput = false;
}
if (MFX_CODEC_RGB4 == InputParams.DecodeId &&
( !InputParams.nVppCompSrcH ||
!InputParams.nVppCompSrcW ))
{
PrintError(MSDK_STRING("VppCompSrcH and VppCompSrcW must be specified in case of -i::rgb4_frame\n"));
return MFX_ERR_UNSUPPORTED;
}
if((!InputParams.FRCAlgorithm && !InputParams.bEnableDeinterlacing) && InputParams.dVPPOutFramerate)
{
msdk_printf(MSDK_STRING("-f option is ignored, it can be used with FRC or deinterlace options only. \n"));
InputParams.dVPPOutFramerate=0;
}
if(InputParams.FRCAlgorithm && InputParams.bEnableExtLA)
{
PrintError(MSDK_STRING("-la_ext and FRC options cannot be used together\n"));
return MFX_ERR_UNSUPPORTED;
}
if (InputParams.nQuality && InputParams.EncodeId && (MFX_CODEC_JPEG != InputParams.EncodeId))
{
PrintError(MSDK_STRING("-q option is supported only for JPEG encoder\n"));
return MFX_ERR_UNSUPPORTED;
}
if ((InputParams.nTargetUsage || InputParams.nBitRate) && (MFX_CODEC_JPEG == InputParams.EncodeId))
{
PrintError(MSDK_STRING("-b and -u options are supported only for H.264, MPEG2 and MVC encoders. For JPEG encoder use -q\n"));
return MFX_ERR_UNSUPPORTED;
}
// valid target usage range is: [MFX_TARGETUSAGE_BEST_QUALITY .. MFX_TARGETUSAGE_BEST_SPEED] (at the moment [1..7])
// If target usage is kept unknown - presets manager will fill in proper value
if ((InputParams.nTargetUsage < MFX_TARGETUSAGE_UNKNOWN) ||
(InputParams.nTargetUsage > MFX_TARGETUSAGE_BEST_SPEED) )
{
PrintError(MSDK_STRING("Unsupported target usage"));
return MFX_ERR_UNSUPPORTED;
}
// Ignoring user-defined Async Depth for LA
if (InputParams.nMaxSliceSize)
{
InputParams.nAsyncDepth = 1;
}
// For decoder session of inter-session case, let's set AsyncDepth to 4 by default
if (InputParams.eMode == Sink && !InputParams.nAsyncDepth)
{
InputParams.nAsyncDepth = 4;
}
if (InputParams.bLABRC && !(InputParams.libType & MFX_IMPL_HARDWARE_ANY))
{
PrintError(MSDK_STRING("Look ahead BRC is supported only with -hw option!"));
return MFX_ERR_UNSUPPORTED;
}
if (InputParams.bLABRC && (InputParams.EncodeId != MFX_CODEC_AVC) && (InputParams.eMode == Source))
{
PrintError(MSDK_STRING("Look ahead BRC is supported only with H.264 encoder!"));
return MFX_ERR_UNSUPPORTED;
}
if ( (InputParams.nRateControlMethod == MFX_RATECONTROL_LA ||
InputParams.nRateControlMethod == MFX_RATECONTROL_LA_EXT ||
InputParams.nRateControlMethod == MFX_RATECONTROL_LA_ICQ ||
InputParams.nRateControlMethod == MFX_RATECONTROL_LA_HRD) &&
InputParams.nLADepth > 100 )
{
PrintError(MSDK_STRING("Unsupported value of -lad parameter, must be in range [1,100] or 0 for automatic selection"));
return MFX_ERR_UNSUPPORTED;
}
if ((InputParams.nMaxSliceSize) && !(InputParams.libType & MFX_IMPL_HARDWARE_ANY))
{
PrintError(MSDK_STRING("MaxSliceSize option is supported only with -hw option!"));
return MFX_ERR_UNSUPPORTED;
}
if ((InputParams.nMaxSliceSize) && (InputParams.nSlices))
{
PrintError(MSDK_STRING("-mss and -l options are not compatible!"));
}
if ((InputParams.nMaxSliceSize) && (InputParams.EncodeId != MFX_CODEC_AVC) && (InputParams.EncodeId != MFX_CODEC_HEVC))
{
PrintError(MSDK_STRING("MaxSliceSize option is supported only with H.264 and H.265(HEVC) encoder!"));
return MFX_ERR_UNSUPPORTED;
}
if(InputParams.BitrateLimit == MFX_CODINGOPTION_UNKNOWN)
{
InputParams.BitrateLimit = MFX_CODINGOPTION_OFF;
}
if(InputParams.enableQSVFF && InputParams.eMode == Sink)
{
msdk_printf(MSDK_STRING("WARNING: -lowpower(-qsv-ff) option is not valid for decoder-only sessions, this parameter will be ignored.\n"));
}
std::map<mfxU32, sPluginParams>::iterator it;
// Set decoder plugins parameters only if they were not set before
if (!memcmp(InputParams.decoderPluginParams.pluginGuid.Data, MSDK_PLUGINGUID_NULL.Data, sizeof(MSDK_PLUGINGUID_NULL)) &&
!strcmp(InputParams.decoderPluginParams.strPluginPath,""))
{
it = m_decoderPlugins.find(InputParams.DecodeId);
if (it != m_decoderPlugins.end())
InputParams.decoderPluginParams = it->second;
}
else
{
// Decoding plugin was set manually, so let's check if codec supports plugins
if (!IsPluginCodecSupported(InputParams.DecodeId))
{
msdk_printf(MSDK_STRING("error: decoder does not support plugins\n"));
return MFX_ERR_UNSUPPORTED;
}
}
// Set encoder plugins parameters only if they were not set before
if (!memcmp(InputParams.encoderPluginParams.pluginGuid.Data, MSDK_PLUGINGUID_NULL.Data, sizeof(MSDK_PLUGINGUID_NULL)) &&
!strcmp(InputParams.encoderPluginParams.strPluginPath, ""))
{
it = m_encoderPlugins.find(InputParams.EncodeId);
if (it != m_encoderPlugins.end())
InputParams.encoderPluginParams = it->second;
}
else
{
// Encoding plugin was set manually, so let's check if codec supports plugins
if (!IsPluginCodecSupported(InputParams.EncodeId))
{
msdk_printf(MSDK_STRING("error: encoder does not support plugins\n"));
return MFX_ERR_UNSUPPORTED;
}
}
if(InputParams.EncoderFourCC && InputParams.eMode == Sink)
{
msdk_printf(MSDK_STRING("WARNING: -ec option is used in session without encoder, this parameter will be ignored \n"));
}
if(InputParams.DecoderFourCC && InputParams.eMode != Native && InputParams.eMode != Sink)
{
msdk_printf(MSDK_STRING("WARNING: -dc option is used in session without decoder, this parameter will be ignored \n"));
}
if(InputParams.EncoderFourCC && InputParams.EncoderFourCC != MFX_FOURCC_NV12 &&
InputParams.EncoderFourCC != MFX_FOURCC_RGB4 && InputParams.EncoderFourCC != MFX_FOURCC_YUY2 &&
InputParams.EncodeId == MFX_CODEC_DUMP)
{
PrintError(MSDK_STRING("-o::raw option can be used with NV12, RGB4 and YUY2 color formats only.\n"));
return MFX_ERR_UNSUPPORTED;
}
if ((InputParams.nEncTileRows || InputParams.nEncTileCols) && (InputParams.EncodeId != MFX_CODEC_HEVC)
#if (MFX_VERSION >= 1029)
&& (InputParams.EncodeId != MFX_CODEC_VP9)
#endif
)
{
msdk_printf(MSDK_STRING("WARNING: -trows and -tcols are only supported for")
#if (MFX_VERSION >= 1029)
MSDK_STRING(" VP9 and")
#endif
MSDK_STRING(" HEVC encoder, these parameters will be ignored.\n"));
InputParams.nEncTileRows = 0;
InputParams.nEncTileCols = 0;
}
#if (defined(_WIN32) || defined(_WIN64)) && (MFX_VERSION >= 1031)
if (InputParams.bPrefferiGfx && InputParams.bPrefferdGfx)
{
msdk_printf(MSDK_STRING("WARNING: both dGfx and iGfx flags set. iGfx will be preffered\n"));
InputParams.bPrefferdGfx = false;
}
#endif
return MFX_ERR_NONE;
} //mfxStatus CmdProcessor::VerifyAndCorrectInputParams(TranscodingSample::sInputParams &InputParams)
bool CmdProcessor::GetNextSessionParams(TranscodingSample::sInputParams &InputParams)
{
if (!m_SessionArray.size())
return false;
if (m_SessionParamId == m_SessionArray.size())
{
return false;
}
InputParams = m_SessionArray[m_SessionParamId];
m_SessionParamId++;
return true;
} //bool CmdProcessor::GetNextSessionParams(TranscodingSample::sInputParams &InputParams)
|
//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
#include "nf_hardware_ti_native.h"
// declare a shorter type to make code readable
typedef Library_nf_hardware_ti_native_nanoFramework_Hardware_TI_Power__PinWakeupConfig PinWakeupConfig;
HRESULT Library_nf_hardware_ti_native_nanoFramework_Hardware_TI_Power::
ConfigureWakeupFromGpioPin___STATIC__VOID__SZARRAY_nanoFrameworkHardwareTIPowerPinWakeupConfig(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
int32_t configCount;
int32_t index = 0;
PIN_Config *wakeupConfigurations = NULL;
CLR_RT_HeapBlock *pinWakeupConfig = NULL;
CLR_RT_HeapBlock_Array *configArray = stack.Arg0().DereferenceArray();
FAULT_ON_NULL(configArray);
// how many configurations are in the array
configCount = configArray->m_numOfElements;
if (configCount > 0)
{
// allocate config array
// need an extra position to store the "terminator"
wakeupConfigurations = (PIN_Config *)platform_malloc((configCount + 1) * sizeof(PIN_Config));
// check allocation
if (wakeupConfigurations != NULL)
{
// clear memory
memset(wakeupConfigurations, 0, configCount * sizeof(PIN_Config));
// build the array of configuration
while (index < configCount)
{
// get a pointer to the configuration
pinWakeupConfig = ((CLR_RT_HeapBlock *)configArray->GetElement(index))->Dereference();
// get pin number
wakeupConfigurations[index] = PIN_ID(pinWakeupConfig[PinWakeupConfig::FIELD___pin].NumericByRef().s4);
// pin is always input
wakeupConfigurations[index] |= PIN_INPUT_EN;
// grab and set pullup/down option
wakeupConfigurations[index] |=
(Power_PinPullUpDown)pinWakeupConfig[PinWakeupConfig::FIELD___pinPullUpDown].NumericByRef().u4;
// grab and set wakeup option
wakeupConfigurations[index] |=
(Power_PinWakeupEdge)pinWakeupConfig[PinWakeupConfig::FIELD___wakeupConfig].NumericByRef().u4;
// move to the next configuration element
index++;
}
// add "terminator" to the array
wakeupConfigurations[index] = PIN_TERMINATE;
// configure DIO for wakeup from shutdown
PINCC26XX_setWakeup(wakeupConfigurations);
// done here, free memory
platform_free(wakeupConfigurations);
}
else
{
// failed to allocate memory
NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_MEMORY);
}
}
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_hardware_ti_native_nanoFramework_Hardware_TI_Power::
get_SourceOfReset___STATIC__nanoFrameworkHardwareTIPowerResetSource(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
stack.SetResult_U4(WakeupReasonStore);
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_hardware_ti_native_nanoFramework_Hardware_TI_Power::NativeEnterShutdownMode___STATIC__VOID(
CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
Power_shutdown(0, 0);
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_hardware_ti_native_nanoFramework_Hardware_TI_Power::
NativeEnterStandbyMode___STATIC__VOID__SystemTimeSpan(CLR_RT_StackFrame &stack)
{
NANOCLR_HEADER();
CLR_UINT64 standbyDurationMilsec;
// debounceTimeout field its a TimeSpan, which is a primitive type stored as an heap block, therefore needs to
// be accessed indirectly
CLR_INT64 *standbyDuration = Library_corlib_native_System_TimeSpan::GetValuePtr(stack.Arg0());
FAULT_ON_NULL(standbyDuration);
standbyDurationMilsec = *(CLR_UINT64 *)standbyDuration / TIME_CONVERSION__TO_SECONDS;
ClockP_sleep(standbyDurationMilsec);
// need to reset the CPU after waking from standby
CPU_Reset();
//////////////////////////////////////
// THE EXECUTION NEVER REACHES HERE //
//////////////////////////////////////
NANOCLR_NOCLEANUP();
}
|
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include "utility.h"
#include "VMparser.h"
#include "CodeWriter.h"
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
const char FILE_SEPARATOR = '\\';
#else
const char FILE_SEPARATOR = '/';
#endif
////////////////////////////////////////////////////////////////////////////////
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
// Get local path and output filename
string local_path = string(1,'.') + string(1,FILE_SEPARATOR);
string asm_filename("a.asm");
string asm_filepath = local_path + asm_filename;
std::ofstream output_asm_file;
std::ifstream input_vm_file;
output_asm_file.open(asm_filepath,std::ios::out);
// Write initialize assembly code
output_asm_file << "@256\nD=A\n@SP\nM=D\n@MAIN\n0;JMP\n"
<< "(PUSH_TRUE)\n@SP\nA=M\nM=0\nM=M-1\n@SP\nM=M+1\n"
<< "@LCL\nA=M\n0;JMP\n(MAIN)\n";
CodeWriter writer(output_asm_file);
Parser parser;
for(int i = 1; i != argc; ++i)
{
// Get the filename of current file
int offset=0,size=0;
for(int j = 0; argv[i][j] != '\0'; ++j)
{
if(argv[i][j] == FILE_SEPARATOR)
offset = j+1;
if(argv[i][j] == '.')
size = j-offset;
}
string vm_filename = string(argv[i]).substr(offset,size);
input_vm_file.open(argv[i],std::ios::in);
writer.setFileName(vm_filename);
parser.constructor(input_vm_file);
while(parser.hasMoreCommands())
{
if(parser.advance())
{
switch(parser.commandType())
{
case C_PUSH:
case C_POP:
writer.writePushPop(parser.commandType(),parser.arg1(),parser.arg2());
break;
case C_ARITHMETIC:
writer.writeArithmetic(parser.arg1());
break;
default:
exit(-1);
}
}
else
break;
}
input_vm_file.close();
SEGMENT_MAP["static"] += 10;
}
output_asm_file.close();
}
|
_declspec(dllexport) int add(int a, int b)
{
return a + b;
}
|
// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL: https://hpctoolkit.googlecode.com/svn/branches/hpctoolkit-hpcserver/src/tool/hpcserver/SpaceTimeDataController.cpp $
// $Id: SpaceTimeDataController.cpp 4317 2013-07-25 16:32:22Z felipet1326@gmail.com $
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2016, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// $HeadURL: https://hpctoolkit.googlecode.com/svn/branches/hpctoolkit-hpcserver/src/tool/hpcserver/SpaceTimeDataController.cpp $
//
// Purpose:
// Manages much of the flow of data through the program
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************
#include "SpaceTimeDataController.hpp"
#include "FileData.hpp"
#include <iostream>
using namespace std;
namespace TraceviewerServer
{
//ImageTraceAttributes* Attributes;
//ProcessTimeline** Traces;
//int TracesLength;
SpaceTimeDataController::SpaceTimeDataController(FileData* locations)
{
attributes = new ImageTraceAttributes();
//This could potentially be a problem if the header size is not the
//default because we might not be able to read the number of ranks correctly.
//For now, it's not an issue, and the data dependencies make changing this
//complicated.
dataTrace = new FilteredBaseData(locations->fileTrace, DEFAULT_HEADER_SIZE);
height = dataTrace->getNumberOfRanks();
experimentXML = locations->fileXML;
fileTrace = locations->fileTrace;
tracesInitialized = false;
}
//called once the INFO packet has been received to add the information to the controller
void SpaceTimeDataController::setInfo(Time _minBegTime, Time _maxEndTime,
int _headerSize)
{
minBegTime = _minBegTime;
maxEndTime = _maxEndTime;
headerSize = _headerSize;
delete dataTrace;
dataTrace = new FilteredBaseData(fileTrace, headerSize);
}
int SpaceTimeDataController::getNumRanks()
{
return height;
}
string SpaceTimeDataController::getExperimentXML()
{
return experimentXML;
}
ProcessTimeline* SpaceTimeDataController::getNextTrace()
{
if (attributes->lineNum
< min(attributes->numPixelsV, attributes->endProcess - attributes->begProcess))
{
ProcessTimeline* toReturn = new ProcessTimeline(*attributes, attributes->lineNum, dataTrace,
minBegTime + attributes->begTime, headerSize);
attributes->lineNum++;
return toReturn;
}
return NULL;
}
void SpaceTimeDataController::addNextTrace(ProcessTimeline* NextPtl)
{
if (NextPtl == NULL)
cerr << "Saving a null PTL?" << endl;
traces[NextPtl->line()] = NextPtl;
}
//Don't call if in MPI mode
void SpaceTimeDataController::fillTraces()
{
//Traces might be null. resetTraces will fix that.
resetTraces();
//Taken straight from TimelineThread
ProcessTimeline* nextTrace = getNextTrace();
while (nextTrace != NULL)
{
nextTrace->readInData();
addNextTrace(nextTrace);
nextTrace = getNextTrace();
}
}
int* SpaceTimeDataController::getValuesXProcessID()
{
return dataTrace->getProcessIDs();
}
short* SpaceTimeDataController::getValuesXThreadID()
{
return dataTrace->getThreadIDs();
}
void SpaceTimeDataController::resetTraces()
{
int numTraces = min(attributes->numPixelsV,
attributes->endProcess - attributes->begProcess);
deleteTraces();
traces = new ProcessTimeline*[numTraces];
tracesLength = numTraces;
tracesInitialized = true;
}
void SpaceTimeDataController::applyFilters(FilterSet filters)
{
dataTrace->setFilters(filters);
}
void SpaceTimeDataController::deleteTraces()
{
if (tracesInitialized) {
for (int var = 0; var < tracesLength; var++)
{
delete (traces[var]);
}
delete[] traces;
}
traces = NULL;
tracesInitialized = false;
}
SpaceTimeDataController::~SpaceTimeDataController()
{
delete attributes;
delete dataTrace;
//The MPI implementation actually doesn't use the Traces array at all!
//It does call getNextTrace, but changedBounds is always true so
//tracesInitialized is always false for MPI
deleteTraces();
}
} /* namespace TraceviewerServer */
|
/**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
stepper_dac.cpp - To set stepper current via DAC
Part of Marlin
Copyright (c) 2016 MarlinFirmware
Marlin is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Marlin is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Marlin. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Marlin.h"
#if ENABLED(DAC_STEPPER_CURRENT)
#include "stepper_dac.h"
bool dac_present = false;
const uint8_t dac_order[NUM_AXIS] = DAC_STEPPER_ORDER;
uint8_t dac_channel_pct[XYZE] = DAC_MOTOR_CURRENT_DEFAULT;
int dac_init() {
#if PIN_EXISTS(DAC_DISABLE)
OUT_WRITE(DAC_DISABLE_PIN, LOW); // set pin low to enable DAC
#endif
mcp4728_init();
if (mcp4728_simpleCommand(RESET)) return -1;
dac_present = true;
mcp4728_setVref_all(DAC_STEPPER_VREF);
mcp4728_setGain_all(DAC_STEPPER_GAIN);
if (mcp4728_getDrvPct(0) < 1 || mcp4728_getDrvPct(1) < 1 || mcp4728_getDrvPct(2) < 1 || mcp4728_getDrvPct(3) < 1 ) {
mcp4728_setDrvPct(dac_channel_pct);
mcp4728_eepromWrite();
}
return 0;
}
void dac_current_percent(uint8_t channel, float val) {
if (!dac_present) return;
NOMORE(val, 100);
mcp4728_analogWrite(dac_order[channel], val * 0.01 * (DAC_STEPPER_MAX));
mcp4728_simpleCommand(UPDATE);
}
void dac_current_raw(uint8_t channel, uint16_t val) {
if (!dac_present) return;
NOMORE(val, DAC_STEPPER_MAX);
mcp4728_analogWrite(dac_order[channel], val);
mcp4728_simpleCommand(UPDATE);
}
static float dac_perc(int8_t n) { return 100.0 * mcp4728_getValue(dac_order[n]) * (1.0 / (DAC_STEPPER_MAX)); }
static float dac_amps(int8_t n) { return mcp4728_getDrvPct(dac_order[n]) * (DAC_STEPPER_MAX) * 0.125 * (1.0 / (DAC_STEPPER_SENSE)); }
uint8_t dac_current_get_percent(const AxisEnum axis) { return mcp4728_getDrvPct(dac_order[axis]); }
void dac_current_set_percents(const uint8_t pct[XYZE]) {
LOOP_XYZE(i) dac_channel_pct[i] = pct[dac_order[i]];
mcp4728_setDrvPct(dac_channel_pct);
}
void dac_print_values() {
if (!dac_present) return;
SERIAL_ECHO_START();
SERIAL_ECHOLNPGM("Stepper current values in % (Amps):");
SERIAL_ECHO_START();
SERIAL_ECHOPAIR(" X:", dac_perc(X_AXIS));
SERIAL_ECHOPAIR(" (", dac_amps(X_AXIS));
SERIAL_ECHOPAIR(") Y:", dac_perc(Y_AXIS));
SERIAL_ECHOPAIR(" (", dac_amps(Y_AXIS));
SERIAL_ECHOPAIR(") Z:", dac_perc(Z_AXIS));
SERIAL_ECHOPAIR(" (", dac_amps(Z_AXIS));
SERIAL_ECHOPAIR(") E:", dac_perc(E_AXIS));
SERIAL_ECHOPAIR(" (", dac_amps(E_AXIS));
SERIAL_ECHOLN(")");
}
void dac_commit_eeprom() {
if (!dac_present) return;
mcp4728_eepromWrite();
}
#endif // DAC_STEPPER_CURRENT
|
#pragma once
#include <memory>
#include <iostream>
namespace util::allocator {
void add_memory (uintmax_t amount);
void free_memory (uintmax_t amount);
uintmax_t peak (void);
uintmax_t total (void);
uintmax_t freed (void);
uintmax_t now (void);
template <typename T>
class allocator {
public:
using base = std::allocator<T>;
private:
base alloc_;
public:
using value_type = typename base::value_type;
using size_type = typename base::size_type;
using difference_type = typename base::difference_type;
using propagate_on_container_move_assignment = typename base::propagate_on_container_move_assignment;
using is_always_equal = typename base::is_always_equal;
template <typename... ARGS>
allocator (ARGS&&... args) : alloc_{ std::forward<ARGS>(args)... } {}
template <typename... ARGS>
[[nodiscard]] T* allocate (std::size_t n, ARGS&&... args) {
// Log allocation
add_memory(n * sizeof(T));
// Calls base allocator
return this->alloc_.allocate(n, std::forward<ARGS>(args)...);
}
template <typename... ARGS>
void deallocate (T* p, std::size_t n, ARGS&&... args) {
// Log deallocation
free_memory(n * sizeof(T));
// Calls base deallocator
this->alloc_.deallocate(p, n, std::forward<ARGS>(args)...);
}
bool operator == (allocator const& ot) const {
return this->alloc_ == ot.alloc_;
}
bool operator != (allocator const& ot) const {
return this->alloc_ != ot.alloc_;
}
};
};
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Configuration.proto
#include "Configuration.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/wire_format_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
namespace aapt {
namespace pb {
class ConfigurationDefaultTypeInternal {
public:
::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<Configuration> _instance;
} _Configuration_default_instance_;
} // namespace pb
} // namespace aapt
static void InitDefaultsscc_info_Configuration_Configuration_2eproto() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::aapt::pb::_Configuration_default_instance_;
new (ptr) ::aapt::pb::Configuration();
::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr);
}
::aapt::pb::Configuration::InitAsDefaultInstance();
}
::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Configuration_Configuration_2eproto =
{{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_Configuration_Configuration_2eproto}, {}};
static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_Configuration_2eproto[1];
static const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* file_level_enum_descriptors_Configuration_2eproto[14];
static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_Configuration_2eproto = nullptr;
const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_Configuration_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, mcc_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, mnc_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, locale_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, layout_direction_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, screen_width_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, screen_height_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, screen_width_dp_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, screen_height_dp_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, smallest_screen_width_dp_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, screen_layout_size_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, screen_layout_long_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, screen_round_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, wide_color_gamut_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, hdr_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, orientation_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, ui_mode_type_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, ui_mode_night_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, density_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, touchscreen_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, keys_hidden_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, keyboard_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, nav_hidden_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, navigation_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, sdk_version_),
PROTOBUF_FIELD_OFFSET(::aapt::pb::Configuration, product_),
};
static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::aapt::pb::Configuration)},
};
static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = {
reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::aapt::pb::_Configuration_default_instance_),
};
const char descriptor_table_protodef_Configuration_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) =
"\n\023Configuration.proto\022\007aapt.pb\"\331\024\n\rConfi"
"guration\022\013\n\003mcc\030\001 \001(\r\022\013\n\003mnc\030\002 \001(\r\022\016\n\006lo"
"cale\030\003 \001(\t\022@\n\020layout_direction\030\004 \001(\0162&.a"
"apt.pb.Configuration.LayoutDirection\022\024\n\014"
"screen_width\030\005 \001(\r\022\025\n\rscreen_height\030\006 \001("
"\r\022\027\n\017screen_width_dp\030\007 \001(\r\022\030\n\020screen_hei"
"ght_dp\030\010 \001(\r\022 \n\030smallest_screen_width_dp"
"\030\t \001(\r\022C\n\022screen_layout_size\030\n \001(\0162\'.aap"
"t.pb.Configuration.ScreenLayoutSize\022C\n\022s"
"creen_layout_long\030\013 \001(\0162\'.aapt.pb.Config"
"uration.ScreenLayoutLong\0228\n\014screen_round"
"\030\014 \001(\0162\".aapt.pb.Configuration.ScreenRou"
"nd\022\?\n\020wide_color_gamut\030\r \001(\0162%.aapt.pb.C"
"onfiguration.WideColorGamut\022\'\n\003hdr\030\016 \001(\016"
"2\032.aapt.pb.Configuration.Hdr\0227\n\013orientat"
"ion\030\017 \001(\0162\".aapt.pb.Configuration.Orient"
"ation\0227\n\014ui_mode_type\030\020 \001(\0162!.aapt.pb.Co"
"nfiguration.UiModeType\0229\n\rui_mode_night\030"
"\021 \001(\0162\".aapt.pb.Configuration.UiModeNigh"
"t\022\017\n\007density\030\022 \001(\r\0227\n\013touchscreen\030\023 \001(\0162"
"\".aapt.pb.Configuration.Touchscreen\0226\n\013k"
"eys_hidden\030\024 \001(\0162!.aapt.pb.Configuration"
".KeysHidden\0221\n\010keyboard\030\025 \001(\0162\037.aapt.pb."
"Configuration.Keyboard\0224\n\nnav_hidden\030\026 \001"
"(\0162 .aapt.pb.Configuration.NavHidden\0225\n\n"
"navigation\030\027 \001(\0162!.aapt.pb.Configuration"
".Navigation\022\023\n\013sdk_version\030\030 \001(\r\022\017\n\007prod"
"uct\030\031 \001(\t\"a\n\017LayoutDirection\022\032\n\026LAYOUT_D"
"IRECTION_UNSET\020\000\022\030\n\024LAYOUT_DIRECTION_LTR"
"\020\001\022\030\n\024LAYOUT_DIRECTION_RTL\020\002\"\252\001\n\020ScreenL"
"ayoutSize\022\034\n\030SCREEN_LAYOUT_SIZE_UNSET\020\000\022"
"\034\n\030SCREEN_LAYOUT_SIZE_SMALL\020\001\022\035\n\031SCREEN_"
"LAYOUT_SIZE_NORMAL\020\002\022\034\n\030SCREEN_LAYOUT_SI"
"ZE_LARGE\020\003\022\035\n\031SCREEN_LAYOUT_SIZE_XLARGE\020"
"\004\"m\n\020ScreenLayoutLong\022\034\n\030SCREEN_LAYOUT_L"
"ONG_UNSET\020\000\022\033\n\027SCREEN_LAYOUT_LONG_LONG\020\001"
"\022\036\n\032SCREEN_LAYOUT_LONG_NOTLONG\020\002\"X\n\013Scre"
"enRound\022\026\n\022SCREEN_ROUND_UNSET\020\000\022\026\n\022SCREE"
"N_ROUND_ROUND\020\001\022\031\n\025SCREEN_ROUND_NOTROUND"
"\020\002\"h\n\016WideColorGamut\022\032\n\026WIDE_COLOR_GAMUT"
"_UNSET\020\000\022\033\n\027WIDE_COLOR_GAMUT_WIDECG\020\001\022\035\n"
"\031WIDE_COLOR_GAMUT_NOWIDECG\020\002\"3\n\003Hdr\022\r\n\tH"
"DR_UNSET\020\000\022\016\n\nHDR_HIGHDR\020\001\022\r\n\tHDR_LOWDR\020"
"\002\"h\n\013Orientation\022\025\n\021ORIENTATION_UNSET\020\000\022"
"\024\n\020ORIENTATION_PORT\020\001\022\024\n\020ORIENTATION_LAN"
"D\020\002\022\026\n\022ORIENTATION_SQUARE\020\003\"\327\001\n\nUiModeTy"
"pe\022\026\n\022UI_MODE_TYPE_UNSET\020\000\022\027\n\023UI_MODE_TY"
"PE_NORMAL\020\001\022\025\n\021UI_MODE_TYPE_DESK\020\002\022\024\n\020UI"
"_MODE_TYPE_CAR\020\003\022\033\n\027UI_MODE_TYPE_TELEVIS"
"ION\020\004\022\032\n\026UI_MODE_TYPE_APPLIANCE\020\005\022\026\n\022UI_"
"MODE_TYPE_WATCH\020\006\022\032\n\026UI_MODE_TYPE_VRHEAD"
"SET\020\007\"[\n\013UiModeNight\022\027\n\023UI_MODE_NIGHT_UN"
"SET\020\000\022\027\n\023UI_MODE_NIGHT_NIGHT\020\001\022\032\n\026UI_MOD"
"E_NIGHT_NOTNIGHT\020\002\"m\n\013Touchscreen\022\025\n\021TOU"
"CHSCREEN_UNSET\020\000\022\027\n\023TOUCHSCREEN_NOTOUCH\020"
"\001\022\026\n\022TOUCHSCREEN_STYLUS\020\002\022\026\n\022TOUCHSCREEN"
"_FINGER\020\003\"v\n\nKeysHidden\022\025\n\021KEYS_HIDDEN_U"
"NSET\020\000\022\033\n\027KEYS_HIDDEN_KEYSEXPOSED\020\001\022\032\n\026K"
"EYS_HIDDEN_KEYSHIDDEN\020\002\022\030\n\024KEYS_HIDDEN_K"
"EYSSOFT\020\003\"`\n\010Keyboard\022\022\n\016KEYBOARD_UNSET\020"
"\000\022\023\n\017KEYBOARD_NOKEYS\020\001\022\023\n\017KEYBOARD_QWERT"
"Y\020\002\022\026\n\022KEYBOARD_TWELVEKEY\020\003\"V\n\tNavHidden"
"\022\024\n\020NAV_HIDDEN_UNSET\020\000\022\031\n\025NAV_HIDDEN_NAV"
"EXPOSED\020\001\022\030\n\024NAV_HIDDEN_NAVHIDDEN\020\002\"}\n\nN"
"avigation\022\024\n\020NAVIGATION_UNSET\020\000\022\024\n\020NAVIG"
"ATION_NONAV\020\001\022\023\n\017NAVIGATION_DPAD\020\002\022\030\n\024NA"
"VIGATION_TRACKBALL\020\003\022\024\n\020NAVIGATION_WHEEL"
"\020\004B\022\n\020com.android.aaptb\006proto3"
;
static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_Configuration_2eproto_deps[1] = {
};
static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_Configuration_2eproto_sccs[1] = {
&scc_info_Configuration_Configuration_2eproto.base,
};
static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_Configuration_2eproto_once;
static bool descriptor_table_Configuration_2eproto_initialized = false;
const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_Configuration_2eproto = {
&descriptor_table_Configuration_2eproto_initialized, descriptor_table_protodef_Configuration_2eproto, "Configuration.proto", 2710,
&descriptor_table_Configuration_2eproto_once, descriptor_table_Configuration_2eproto_sccs, descriptor_table_Configuration_2eproto_deps, 1, 0,
schemas, file_default_instances, TableStruct_Configuration_2eproto::offsets,
file_level_metadata_Configuration_2eproto, 1, file_level_enum_descriptors_Configuration_2eproto, file_level_service_descriptors_Configuration_2eproto,
};
// Force running AddDescriptors() at dynamic initialization time.
static bool dynamic_init_dummy_Configuration_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_Configuration_2eproto), true);
namespace aapt {
namespace pb {
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_LayoutDirection_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[0];
}
bool Configuration_LayoutDirection_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_LayoutDirection Configuration::LAYOUT_DIRECTION_UNSET;
constexpr Configuration_LayoutDirection Configuration::LAYOUT_DIRECTION_LTR;
constexpr Configuration_LayoutDirection Configuration::LAYOUT_DIRECTION_RTL;
constexpr Configuration_LayoutDirection Configuration::LayoutDirection_MIN;
constexpr Configuration_LayoutDirection Configuration::LayoutDirection_MAX;
constexpr int Configuration::LayoutDirection_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_ScreenLayoutSize_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[1];
}
bool Configuration_ScreenLayoutSize_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_ScreenLayoutSize Configuration::SCREEN_LAYOUT_SIZE_UNSET;
constexpr Configuration_ScreenLayoutSize Configuration::SCREEN_LAYOUT_SIZE_SMALL;
constexpr Configuration_ScreenLayoutSize Configuration::SCREEN_LAYOUT_SIZE_NORMAL;
constexpr Configuration_ScreenLayoutSize Configuration::SCREEN_LAYOUT_SIZE_LARGE;
constexpr Configuration_ScreenLayoutSize Configuration::SCREEN_LAYOUT_SIZE_XLARGE;
constexpr Configuration_ScreenLayoutSize Configuration::ScreenLayoutSize_MIN;
constexpr Configuration_ScreenLayoutSize Configuration::ScreenLayoutSize_MAX;
constexpr int Configuration::ScreenLayoutSize_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_ScreenLayoutLong_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[2];
}
bool Configuration_ScreenLayoutLong_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_ScreenLayoutLong Configuration::SCREEN_LAYOUT_LONG_UNSET;
constexpr Configuration_ScreenLayoutLong Configuration::SCREEN_LAYOUT_LONG_LONG;
constexpr Configuration_ScreenLayoutLong Configuration::SCREEN_LAYOUT_LONG_NOTLONG;
constexpr Configuration_ScreenLayoutLong Configuration::ScreenLayoutLong_MIN;
constexpr Configuration_ScreenLayoutLong Configuration::ScreenLayoutLong_MAX;
constexpr int Configuration::ScreenLayoutLong_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_ScreenRound_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[3];
}
bool Configuration_ScreenRound_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_ScreenRound Configuration::SCREEN_ROUND_UNSET;
constexpr Configuration_ScreenRound Configuration::SCREEN_ROUND_ROUND;
constexpr Configuration_ScreenRound Configuration::SCREEN_ROUND_NOTROUND;
constexpr Configuration_ScreenRound Configuration::ScreenRound_MIN;
constexpr Configuration_ScreenRound Configuration::ScreenRound_MAX;
constexpr int Configuration::ScreenRound_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_WideColorGamut_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[4];
}
bool Configuration_WideColorGamut_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_WideColorGamut Configuration::WIDE_COLOR_GAMUT_UNSET;
constexpr Configuration_WideColorGamut Configuration::WIDE_COLOR_GAMUT_WIDECG;
constexpr Configuration_WideColorGamut Configuration::WIDE_COLOR_GAMUT_NOWIDECG;
constexpr Configuration_WideColorGamut Configuration::WideColorGamut_MIN;
constexpr Configuration_WideColorGamut Configuration::WideColorGamut_MAX;
constexpr int Configuration::WideColorGamut_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_Hdr_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[5];
}
bool Configuration_Hdr_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_Hdr Configuration::HDR_UNSET;
constexpr Configuration_Hdr Configuration::HDR_HIGHDR;
constexpr Configuration_Hdr Configuration::HDR_LOWDR;
constexpr Configuration_Hdr Configuration::Hdr_MIN;
constexpr Configuration_Hdr Configuration::Hdr_MAX;
constexpr int Configuration::Hdr_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_Orientation_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[6];
}
bool Configuration_Orientation_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_Orientation Configuration::ORIENTATION_UNSET;
constexpr Configuration_Orientation Configuration::ORIENTATION_PORT;
constexpr Configuration_Orientation Configuration::ORIENTATION_LAND;
constexpr Configuration_Orientation Configuration::ORIENTATION_SQUARE;
constexpr Configuration_Orientation Configuration::Orientation_MIN;
constexpr Configuration_Orientation Configuration::Orientation_MAX;
constexpr int Configuration::Orientation_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_UiModeType_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[7];
}
bool Configuration_UiModeType_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_UiModeType Configuration::UI_MODE_TYPE_UNSET;
constexpr Configuration_UiModeType Configuration::UI_MODE_TYPE_NORMAL;
constexpr Configuration_UiModeType Configuration::UI_MODE_TYPE_DESK;
constexpr Configuration_UiModeType Configuration::UI_MODE_TYPE_CAR;
constexpr Configuration_UiModeType Configuration::UI_MODE_TYPE_TELEVISION;
constexpr Configuration_UiModeType Configuration::UI_MODE_TYPE_APPLIANCE;
constexpr Configuration_UiModeType Configuration::UI_MODE_TYPE_WATCH;
constexpr Configuration_UiModeType Configuration::UI_MODE_TYPE_VRHEADSET;
constexpr Configuration_UiModeType Configuration::UiModeType_MIN;
constexpr Configuration_UiModeType Configuration::UiModeType_MAX;
constexpr int Configuration::UiModeType_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_UiModeNight_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[8];
}
bool Configuration_UiModeNight_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_UiModeNight Configuration::UI_MODE_NIGHT_UNSET;
constexpr Configuration_UiModeNight Configuration::UI_MODE_NIGHT_NIGHT;
constexpr Configuration_UiModeNight Configuration::UI_MODE_NIGHT_NOTNIGHT;
constexpr Configuration_UiModeNight Configuration::UiModeNight_MIN;
constexpr Configuration_UiModeNight Configuration::UiModeNight_MAX;
constexpr int Configuration::UiModeNight_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_Touchscreen_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[9];
}
bool Configuration_Touchscreen_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_Touchscreen Configuration::TOUCHSCREEN_UNSET;
constexpr Configuration_Touchscreen Configuration::TOUCHSCREEN_NOTOUCH;
constexpr Configuration_Touchscreen Configuration::TOUCHSCREEN_STYLUS;
constexpr Configuration_Touchscreen Configuration::TOUCHSCREEN_FINGER;
constexpr Configuration_Touchscreen Configuration::Touchscreen_MIN;
constexpr Configuration_Touchscreen Configuration::Touchscreen_MAX;
constexpr int Configuration::Touchscreen_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_KeysHidden_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[10];
}
bool Configuration_KeysHidden_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_KeysHidden Configuration::KEYS_HIDDEN_UNSET;
constexpr Configuration_KeysHidden Configuration::KEYS_HIDDEN_KEYSEXPOSED;
constexpr Configuration_KeysHidden Configuration::KEYS_HIDDEN_KEYSHIDDEN;
constexpr Configuration_KeysHidden Configuration::KEYS_HIDDEN_KEYSSOFT;
constexpr Configuration_KeysHidden Configuration::KeysHidden_MIN;
constexpr Configuration_KeysHidden Configuration::KeysHidden_MAX;
constexpr int Configuration::KeysHidden_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_Keyboard_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[11];
}
bool Configuration_Keyboard_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_Keyboard Configuration::KEYBOARD_UNSET;
constexpr Configuration_Keyboard Configuration::KEYBOARD_NOKEYS;
constexpr Configuration_Keyboard Configuration::KEYBOARD_QWERTY;
constexpr Configuration_Keyboard Configuration::KEYBOARD_TWELVEKEY;
constexpr Configuration_Keyboard Configuration::Keyboard_MIN;
constexpr Configuration_Keyboard Configuration::Keyboard_MAX;
constexpr int Configuration::Keyboard_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_NavHidden_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[12];
}
bool Configuration_NavHidden_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_NavHidden Configuration::NAV_HIDDEN_UNSET;
constexpr Configuration_NavHidden Configuration::NAV_HIDDEN_NAVEXPOSED;
constexpr Configuration_NavHidden Configuration::NAV_HIDDEN_NAVHIDDEN;
constexpr Configuration_NavHidden Configuration::NavHidden_MIN;
constexpr Configuration_NavHidden Configuration::NavHidden_MAX;
constexpr int Configuration::NavHidden_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Configuration_Navigation_descriptor() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_Configuration_2eproto);
return file_level_enum_descriptors_Configuration_2eproto[13];
}
bool Configuration_Navigation_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
return true;
default:
return false;
}
}
#if (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
constexpr Configuration_Navigation Configuration::NAVIGATION_UNSET;
constexpr Configuration_Navigation Configuration::NAVIGATION_NONAV;
constexpr Configuration_Navigation Configuration::NAVIGATION_DPAD;
constexpr Configuration_Navigation Configuration::NAVIGATION_TRACKBALL;
constexpr Configuration_Navigation Configuration::NAVIGATION_WHEEL;
constexpr Configuration_Navigation Configuration::Navigation_MIN;
constexpr Configuration_Navigation Configuration::Navigation_MAX;
constexpr int Configuration::Navigation_ARRAYSIZE;
#endif // (__cplusplus < 201703) && (!defined(_MSC_VER) || _MSC_VER >= 1900)
// ===================================================================
void Configuration::InitAsDefaultInstance() {
}
class Configuration::_Internal {
public:
};
Configuration::Configuration()
: ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) {
SharedCtor();
// @@protoc_insertion_point(constructor:aapt.pb.Configuration)
}
Configuration::Configuration(const Configuration& from)
: ::PROTOBUF_NAMESPACE_ID::Message(),
_internal_metadata_(nullptr) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
locale_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from.locale().empty()) {
locale_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.locale_);
}
product_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
if (!from.product().empty()) {
product_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.product_);
}
::memcpy(&mcc_, &from.mcc_,
static_cast<size_t>(reinterpret_cast<char*>(&sdk_version_) -
reinterpret_cast<char*>(&mcc_)) + sizeof(sdk_version_));
// @@protoc_insertion_point(copy_constructor:aapt.pb.Configuration)
}
void Configuration::SharedCtor() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_Configuration_Configuration_2eproto.base);
locale_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
product_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
::memset(&mcc_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&sdk_version_) -
reinterpret_cast<char*>(&mcc_)) + sizeof(sdk_version_));
}
Configuration::~Configuration() {
// @@protoc_insertion_point(destructor:aapt.pb.Configuration)
SharedDtor();
}
void Configuration::SharedDtor() {
locale_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
product_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
}
void Configuration::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const Configuration& Configuration::default_instance() {
::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_Configuration_Configuration_2eproto.base);
return *internal_default_instance();
}
void Configuration::Clear() {
// @@protoc_insertion_point(message_clear_start:aapt.pb.Configuration)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
locale_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
product_.ClearToEmptyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited());
::memset(&mcc_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&sdk_version_) -
reinterpret_cast<char*>(&mcc_)) + sizeof(sdk_version_));
_internal_metadata_.Clear();
}
#if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
const char* Configuration::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) {
#define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure
while (!ctx->Done(&ptr)) {
::PROTOBUF_NAMESPACE_ID::uint32 tag;
ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag);
CHK_(ptr);
switch (tag >> 3) {
// uint32 mcc = 1;
case 1:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) {
mcc_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// uint32 mnc = 2;
case 2:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) {
mnc_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// string locale = 3;
case 3:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_locale(), ptr, ctx, "aapt.pb.Configuration.locale");
CHK_(ptr);
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.LayoutDirection layout_direction = 4;
case 4:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_layout_direction(static_cast<::aapt::pb::Configuration_LayoutDirection>(val));
} else goto handle_unusual;
continue;
// uint32 screen_width = 5;
case 5:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) {
screen_width_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// uint32 screen_height = 6;
case 6:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) {
screen_height_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// uint32 screen_width_dp = 7;
case 7:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 56)) {
screen_width_dp_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// uint32 screen_height_dp = 8;
case 8:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) {
screen_height_dp_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// uint32 smallest_screen_width_dp = 9;
case 9:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 72)) {
smallest_screen_width_dp_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.ScreenLayoutSize screen_layout_size = 10;
case 10:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_screen_layout_size(static_cast<::aapt::pb::Configuration_ScreenLayoutSize>(val));
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.ScreenLayoutLong screen_layout_long = 11;
case 11:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 88)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_screen_layout_long(static_cast<::aapt::pb::Configuration_ScreenLayoutLong>(val));
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.ScreenRound screen_round = 12;
case 12:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 96)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_screen_round(static_cast<::aapt::pb::Configuration_ScreenRound>(val));
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.WideColorGamut wide_color_gamut = 13;
case 13:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 104)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_wide_color_gamut(static_cast<::aapt::pb::Configuration_WideColorGamut>(val));
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.Hdr hdr = 14;
case 14:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 112)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_hdr(static_cast<::aapt::pb::Configuration_Hdr>(val));
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.Orientation orientation = 15;
case 15:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 120)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_orientation(static_cast<::aapt::pb::Configuration_Orientation>(val));
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.UiModeType ui_mode_type = 16;
case 16:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 128)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_ui_mode_type(static_cast<::aapt::pb::Configuration_UiModeType>(val));
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.UiModeNight ui_mode_night = 17;
case 17:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 136)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_ui_mode_night(static_cast<::aapt::pb::Configuration_UiModeNight>(val));
} else goto handle_unusual;
continue;
// uint32 density = 18;
case 18:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 144)) {
density_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.Touchscreen touchscreen = 19;
case 19:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 152)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_touchscreen(static_cast<::aapt::pb::Configuration_Touchscreen>(val));
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.KeysHidden keys_hidden = 20;
case 20:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 160)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_keys_hidden(static_cast<::aapt::pb::Configuration_KeysHidden>(val));
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.Keyboard keyboard = 21;
case 21:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 168)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_keyboard(static_cast<::aapt::pb::Configuration_Keyboard>(val));
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.NavHidden nav_hidden = 22;
case 22:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 176)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_nav_hidden(static_cast<::aapt::pb::Configuration_NavHidden>(val));
} else goto handle_unusual;
continue;
// .aapt.pb.Configuration.Navigation navigation = 23;
case 23:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 184)) {
::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
set_navigation(static_cast<::aapt::pb::Configuration_Navigation>(val));
} else goto handle_unusual;
continue;
// uint32 sdk_version = 24;
case 24:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 192)) {
sdk_version_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr);
CHK_(ptr);
} else goto handle_unusual;
continue;
// string product = 25;
case 25:
if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 202)) {
ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParserUTF8(mutable_product(), ptr, ctx, "aapt.pb.Configuration.product");
CHK_(ptr);
} else goto handle_unusual;
continue;
default: {
handle_unusual:
if ((tag & 7) == 4 || tag == 0) {
ctx->SetLastTag(tag);
goto success;
}
ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx);
CHK_(ptr != nullptr);
continue;
}
} // switch
} // while
success:
return ptr;
failure:
ptr = nullptr;
goto success;
#undef CHK_
}
#else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
bool Configuration::MergePartialFromCodedStream(
::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure
::PROTOBUF_NAMESPACE_ID::uint32 tag;
// @@protoc_insertion_point(parse_start:aapt.pb.Configuration)
for (;;) {
::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// uint32 mcc = 1;
case 1: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32>(
input, &mcc_)));
} else {
goto handle_unusual;
}
break;
}
// uint32 mnc = 2;
case 2: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (16 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32>(
input, &mnc_)));
} else {
goto handle_unusual;
}
break;
}
// string locale = 3;
case 3: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString(
input, this->mutable_locale()));
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->locale().data(), static_cast<int>(this->locale().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE,
"aapt.pb.Configuration.locale"));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.LayoutDirection layout_direction = 4;
case 4: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (32 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_layout_direction(static_cast< ::aapt::pb::Configuration_LayoutDirection >(value));
} else {
goto handle_unusual;
}
break;
}
// uint32 screen_width = 5;
case 5: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (40 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32>(
input, &screen_width_)));
} else {
goto handle_unusual;
}
break;
}
// uint32 screen_height = 6;
case 6: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (48 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32>(
input, &screen_height_)));
} else {
goto handle_unusual;
}
break;
}
// uint32 screen_width_dp = 7;
case 7: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (56 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32>(
input, &screen_width_dp_)));
} else {
goto handle_unusual;
}
break;
}
// uint32 screen_height_dp = 8;
case 8: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (64 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32>(
input, &screen_height_dp_)));
} else {
goto handle_unusual;
}
break;
}
// uint32 smallest_screen_width_dp = 9;
case 9: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (72 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32>(
input, &smallest_screen_width_dp_)));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.ScreenLayoutSize screen_layout_size = 10;
case 10: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (80 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_screen_layout_size(static_cast< ::aapt::pb::Configuration_ScreenLayoutSize >(value));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.ScreenLayoutLong screen_layout_long = 11;
case 11: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (88 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_screen_layout_long(static_cast< ::aapt::pb::Configuration_ScreenLayoutLong >(value));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.ScreenRound screen_round = 12;
case 12: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (96 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_screen_round(static_cast< ::aapt::pb::Configuration_ScreenRound >(value));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.WideColorGamut wide_color_gamut = 13;
case 13: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (104 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_wide_color_gamut(static_cast< ::aapt::pb::Configuration_WideColorGamut >(value));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.Hdr hdr = 14;
case 14: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (112 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_hdr(static_cast< ::aapt::pb::Configuration_Hdr >(value));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.Orientation orientation = 15;
case 15: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (120 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_orientation(static_cast< ::aapt::pb::Configuration_Orientation >(value));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.UiModeType ui_mode_type = 16;
case 16: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (128 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_ui_mode_type(static_cast< ::aapt::pb::Configuration_UiModeType >(value));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.UiModeNight ui_mode_night = 17;
case 17: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (136 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_ui_mode_night(static_cast< ::aapt::pb::Configuration_UiModeNight >(value));
} else {
goto handle_unusual;
}
break;
}
// uint32 density = 18;
case 18: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (144 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32>(
input, &density_)));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.Touchscreen touchscreen = 19;
case 19: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (152 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_touchscreen(static_cast< ::aapt::pb::Configuration_Touchscreen >(value));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.KeysHidden keys_hidden = 20;
case 20: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (160 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_keys_hidden(static_cast< ::aapt::pb::Configuration_KeysHidden >(value));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.Keyboard keyboard = 21;
case 21: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (168 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_keyboard(static_cast< ::aapt::pb::Configuration_Keyboard >(value));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.NavHidden nav_hidden = 22;
case 22: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (176 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_nav_hidden(static_cast< ::aapt::pb::Configuration_NavHidden >(value));
} else {
goto handle_unusual;
}
break;
}
// .aapt.pb.Configuration.Navigation navigation = 23;
case 23: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (184 & 0xFF)) {
int value = 0;
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
int, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_navigation(static_cast< ::aapt::pb::Configuration_Navigation >(value));
} else {
goto handle_unusual;
}
break;
}
// uint32 sdk_version = 24;
case 24: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (192 & 0xFF)) {
DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive<
::PROTOBUF_NAMESPACE_ID::uint32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_UINT32>(
input, &sdk_version_)));
} else {
goto handle_unusual;
}
break;
}
// string product = 25;
case 25: {
if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (202 & 0xFF)) {
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadString(
input, this->mutable_product()));
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->product().data(), static_cast<int>(this->product().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE,
"aapt.pb.Configuration.product"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:aapt.pb.Configuration)
return true;
failure:
// @@protoc_insertion_point(parse_failure:aapt.pb.Configuration)
return false;
#undef DO_
}
#endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
void Configuration::SerializeWithCachedSizes(
::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:aapt.pb.Configuration)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint32 mcc = 1;
if (this->mcc() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32(1, this->mcc(), output);
}
// uint32 mnc = 2;
if (this->mnc() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32(2, this->mnc(), output);
}
// string locale = 3;
if (this->locale().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->locale().data(), static_cast<int>(this->locale().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"aapt.pb.Configuration.locale");
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased(
3, this->locale(), output);
}
// .aapt.pb.Configuration.LayoutDirection layout_direction = 4;
if (this->layout_direction() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
4, this->layout_direction(), output);
}
// uint32 screen_width = 5;
if (this->screen_width() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32(5, this->screen_width(), output);
}
// uint32 screen_height = 6;
if (this->screen_height() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32(6, this->screen_height(), output);
}
// uint32 screen_width_dp = 7;
if (this->screen_width_dp() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32(7, this->screen_width_dp(), output);
}
// uint32 screen_height_dp = 8;
if (this->screen_height_dp() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32(8, this->screen_height_dp(), output);
}
// uint32 smallest_screen_width_dp = 9;
if (this->smallest_screen_width_dp() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32(9, this->smallest_screen_width_dp(), output);
}
// .aapt.pb.Configuration.ScreenLayoutSize screen_layout_size = 10;
if (this->screen_layout_size() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
10, this->screen_layout_size(), output);
}
// .aapt.pb.Configuration.ScreenLayoutLong screen_layout_long = 11;
if (this->screen_layout_long() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
11, this->screen_layout_long(), output);
}
// .aapt.pb.Configuration.ScreenRound screen_round = 12;
if (this->screen_round() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
12, this->screen_round(), output);
}
// .aapt.pb.Configuration.WideColorGamut wide_color_gamut = 13;
if (this->wide_color_gamut() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
13, this->wide_color_gamut(), output);
}
// .aapt.pb.Configuration.Hdr hdr = 14;
if (this->hdr() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
14, this->hdr(), output);
}
// .aapt.pb.Configuration.Orientation orientation = 15;
if (this->orientation() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
15, this->orientation(), output);
}
// .aapt.pb.Configuration.UiModeType ui_mode_type = 16;
if (this->ui_mode_type() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
16, this->ui_mode_type(), output);
}
// .aapt.pb.Configuration.UiModeNight ui_mode_night = 17;
if (this->ui_mode_night() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
17, this->ui_mode_night(), output);
}
// uint32 density = 18;
if (this->density() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32(18, this->density(), output);
}
// .aapt.pb.Configuration.Touchscreen touchscreen = 19;
if (this->touchscreen() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
19, this->touchscreen(), output);
}
// .aapt.pb.Configuration.KeysHidden keys_hidden = 20;
if (this->keys_hidden() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
20, this->keys_hidden(), output);
}
// .aapt.pb.Configuration.Keyboard keyboard = 21;
if (this->keyboard() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
21, this->keyboard(), output);
}
// .aapt.pb.Configuration.NavHidden nav_hidden = 22;
if (this->nav_hidden() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
22, this->nav_hidden(), output);
}
// .aapt.pb.Configuration.Navigation navigation = 23;
if (this->navigation() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnum(
23, this->navigation(), output);
}
// uint32 sdk_version = 24;
if (this->sdk_version() != 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32(24, this->sdk_version(), output);
}
// string product = 25;
if (this->product().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->product().data(), static_cast<int>(this->product().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"aapt.pb.Configuration.product");
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringMaybeAliased(
25, this->product(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:aapt.pb.Configuration)
}
::PROTOBUF_NAMESPACE_ID::uint8* Configuration::InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:aapt.pb.Configuration)
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint32 mcc = 1;
if (this->mcc() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->mcc(), target);
}
// uint32 mnc = 2;
if (this->mnc() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->mnc(), target);
}
// string locale = 3;
if (this->locale().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->locale().data(), static_cast<int>(this->locale().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"aapt.pb.Configuration.locale");
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray(
3, this->locale(), target);
}
// .aapt.pb.Configuration.LayoutDirection layout_direction = 4;
if (this->layout_direction() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
4, this->layout_direction(), target);
}
// uint32 screen_width = 5;
if (this->screen_width() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(5, this->screen_width(), target);
}
// uint32 screen_height = 6;
if (this->screen_height() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->screen_height(), target);
}
// uint32 screen_width_dp = 7;
if (this->screen_width_dp() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(7, this->screen_width_dp(), target);
}
// uint32 screen_height_dp = 8;
if (this->screen_height_dp() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(8, this->screen_height_dp(), target);
}
// uint32 smallest_screen_width_dp = 9;
if (this->smallest_screen_width_dp() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(9, this->smallest_screen_width_dp(), target);
}
// .aapt.pb.Configuration.ScreenLayoutSize screen_layout_size = 10;
if (this->screen_layout_size() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
10, this->screen_layout_size(), target);
}
// .aapt.pb.Configuration.ScreenLayoutLong screen_layout_long = 11;
if (this->screen_layout_long() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
11, this->screen_layout_long(), target);
}
// .aapt.pb.Configuration.ScreenRound screen_round = 12;
if (this->screen_round() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
12, this->screen_round(), target);
}
// .aapt.pb.Configuration.WideColorGamut wide_color_gamut = 13;
if (this->wide_color_gamut() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
13, this->wide_color_gamut(), target);
}
// .aapt.pb.Configuration.Hdr hdr = 14;
if (this->hdr() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
14, this->hdr(), target);
}
// .aapt.pb.Configuration.Orientation orientation = 15;
if (this->orientation() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
15, this->orientation(), target);
}
// .aapt.pb.Configuration.UiModeType ui_mode_type = 16;
if (this->ui_mode_type() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
16, this->ui_mode_type(), target);
}
// .aapt.pb.Configuration.UiModeNight ui_mode_night = 17;
if (this->ui_mode_night() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
17, this->ui_mode_night(), target);
}
// uint32 density = 18;
if (this->density() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(18, this->density(), target);
}
// .aapt.pb.Configuration.Touchscreen touchscreen = 19;
if (this->touchscreen() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
19, this->touchscreen(), target);
}
// .aapt.pb.Configuration.KeysHidden keys_hidden = 20;
if (this->keys_hidden() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
20, this->keys_hidden(), target);
}
// .aapt.pb.Configuration.Keyboard keyboard = 21;
if (this->keyboard() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
21, this->keyboard(), target);
}
// .aapt.pb.Configuration.NavHidden nav_hidden = 22;
if (this->nav_hidden() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
22, this->nav_hidden(), target);
}
// .aapt.pb.Configuration.Navigation navigation = 23;
if (this->navigation() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray(
23, this->navigation(), target);
}
// uint32 sdk_version = 24;
if (this->sdk_version() != 0) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(24, this->sdk_version(), target);
}
// string product = 25;
if (this->product().size() > 0) {
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(
this->product().data(), static_cast<int>(this->product().length()),
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE,
"aapt.pb.Configuration.product");
target =
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteStringToArray(
25, this->product(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:aapt.pb.Configuration)
return target;
}
size_t Configuration::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:aapt.pb.Configuration)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
// string locale = 3;
if (this->locale().size() > 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->locale());
}
// string product = 25;
if (this->product().size() > 0) {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize(
this->product());
}
// uint32 mcc = 1;
if (this->mcc() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->mcc());
}
// uint32 mnc = 2;
if (this->mnc() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->mnc());
}
// .aapt.pb.Configuration.LayoutDirection layout_direction = 4;
if (this->layout_direction() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->layout_direction());
}
// uint32 screen_width = 5;
if (this->screen_width() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->screen_width());
}
// uint32 screen_height = 6;
if (this->screen_height() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->screen_height());
}
// uint32 screen_width_dp = 7;
if (this->screen_width_dp() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->screen_width_dp());
}
// uint32 screen_height_dp = 8;
if (this->screen_height_dp() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->screen_height_dp());
}
// uint32 smallest_screen_width_dp = 9;
if (this->smallest_screen_width_dp() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->smallest_screen_width_dp());
}
// .aapt.pb.Configuration.ScreenLayoutSize screen_layout_size = 10;
if (this->screen_layout_size() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->screen_layout_size());
}
// .aapt.pb.Configuration.ScreenLayoutLong screen_layout_long = 11;
if (this->screen_layout_long() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->screen_layout_long());
}
// .aapt.pb.Configuration.ScreenRound screen_round = 12;
if (this->screen_round() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->screen_round());
}
// .aapt.pb.Configuration.WideColorGamut wide_color_gamut = 13;
if (this->wide_color_gamut() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->wide_color_gamut());
}
// .aapt.pb.Configuration.Hdr hdr = 14;
if (this->hdr() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->hdr());
}
// .aapt.pb.Configuration.Orientation orientation = 15;
if (this->orientation() != 0) {
total_size += 1 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->orientation());
}
// .aapt.pb.Configuration.UiModeType ui_mode_type = 16;
if (this->ui_mode_type() != 0) {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->ui_mode_type());
}
// .aapt.pb.Configuration.UiModeNight ui_mode_night = 17;
if (this->ui_mode_night() != 0) {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->ui_mode_night());
}
// uint32 density = 18;
if (this->density() != 0) {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->density());
}
// .aapt.pb.Configuration.Touchscreen touchscreen = 19;
if (this->touchscreen() != 0) {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->touchscreen());
}
// .aapt.pb.Configuration.KeysHidden keys_hidden = 20;
if (this->keys_hidden() != 0) {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->keys_hidden());
}
// .aapt.pb.Configuration.Keyboard keyboard = 21;
if (this->keyboard() != 0) {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->keyboard());
}
// .aapt.pb.Configuration.NavHidden nav_hidden = 22;
if (this->nav_hidden() != 0) {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->nav_hidden());
}
// .aapt.pb.Configuration.Navigation navigation = 23;
if (this->navigation() != 0) {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->navigation());
}
// uint32 sdk_version = 24;
if (this->sdk_version() != 0) {
total_size += 2 +
::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size(
this->sdk_version());
}
int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void Configuration::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:aapt.pb.Configuration)
GOOGLE_DCHECK_NE(&from, this);
const Configuration* source =
::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<Configuration>(
&from);
if (source == nullptr) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:aapt.pb.Configuration)
::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:aapt.pb.Configuration)
MergeFrom(*source);
}
}
void Configuration::MergeFrom(const Configuration& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:aapt.pb.Configuration)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.locale().size() > 0) {
locale_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.locale_);
}
if (from.product().size() > 0) {
product_.AssignWithDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), from.product_);
}
if (from.mcc() != 0) {
set_mcc(from.mcc());
}
if (from.mnc() != 0) {
set_mnc(from.mnc());
}
if (from.layout_direction() != 0) {
set_layout_direction(from.layout_direction());
}
if (from.screen_width() != 0) {
set_screen_width(from.screen_width());
}
if (from.screen_height() != 0) {
set_screen_height(from.screen_height());
}
if (from.screen_width_dp() != 0) {
set_screen_width_dp(from.screen_width_dp());
}
if (from.screen_height_dp() != 0) {
set_screen_height_dp(from.screen_height_dp());
}
if (from.smallest_screen_width_dp() != 0) {
set_smallest_screen_width_dp(from.smallest_screen_width_dp());
}
if (from.screen_layout_size() != 0) {
set_screen_layout_size(from.screen_layout_size());
}
if (from.screen_layout_long() != 0) {
set_screen_layout_long(from.screen_layout_long());
}
if (from.screen_round() != 0) {
set_screen_round(from.screen_round());
}
if (from.wide_color_gamut() != 0) {
set_wide_color_gamut(from.wide_color_gamut());
}
if (from.hdr() != 0) {
set_hdr(from.hdr());
}
if (from.orientation() != 0) {
set_orientation(from.orientation());
}
if (from.ui_mode_type() != 0) {
set_ui_mode_type(from.ui_mode_type());
}
if (from.ui_mode_night() != 0) {
set_ui_mode_night(from.ui_mode_night());
}
if (from.density() != 0) {
set_density(from.density());
}
if (from.touchscreen() != 0) {
set_touchscreen(from.touchscreen());
}
if (from.keys_hidden() != 0) {
set_keys_hidden(from.keys_hidden());
}
if (from.keyboard() != 0) {
set_keyboard(from.keyboard());
}
if (from.nav_hidden() != 0) {
set_nav_hidden(from.nav_hidden());
}
if (from.navigation() != 0) {
set_navigation(from.navigation());
}
if (from.sdk_version() != 0) {
set_sdk_version(from.sdk_version());
}
}
void Configuration::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:aapt.pb.Configuration)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Configuration::CopyFrom(const Configuration& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:aapt.pb.Configuration)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Configuration::IsInitialized() const {
return true;
}
void Configuration::InternalSwap(Configuration* other) {
using std::swap;
_internal_metadata_.Swap(&other->_internal_metadata_);
locale_.Swap(&other->locale_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
product_.Swap(&other->product_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
swap(mcc_, other->mcc_);
swap(mnc_, other->mnc_);
swap(layout_direction_, other->layout_direction_);
swap(screen_width_, other->screen_width_);
swap(screen_height_, other->screen_height_);
swap(screen_width_dp_, other->screen_width_dp_);
swap(screen_height_dp_, other->screen_height_dp_);
swap(smallest_screen_width_dp_, other->smallest_screen_width_dp_);
swap(screen_layout_size_, other->screen_layout_size_);
swap(screen_layout_long_, other->screen_layout_long_);
swap(screen_round_, other->screen_round_);
swap(wide_color_gamut_, other->wide_color_gamut_);
swap(hdr_, other->hdr_);
swap(orientation_, other->orientation_);
swap(ui_mode_type_, other->ui_mode_type_);
swap(ui_mode_night_, other->ui_mode_night_);
swap(density_, other->density_);
swap(touchscreen_, other->touchscreen_);
swap(keys_hidden_, other->keys_hidden_);
swap(keyboard_, other->keyboard_);
swap(nav_hidden_, other->nav_hidden_);
swap(navigation_, other->navigation_);
swap(sdk_version_, other->sdk_version_);
}
::PROTOBUF_NAMESPACE_ID::Metadata Configuration::GetMetadata() const {
return GetMetadataStatic();
}
// @@protoc_insertion_point(namespace_scope)
} // namespace pb
} // namespace aapt
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_NOINLINE ::aapt::pb::Configuration* Arena::CreateMaybeMessage< ::aapt::pb::Configuration >(Arena* arena) {
return Arena::CreateInternal< ::aapt::pb::Configuration >(arena);
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
|
/* Copyright (c) 2015-2018 The Khronos Group Inc.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and/or associated documentation files (the
"Materials"), to deal in the Materials without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Materials, and to
permit persons to whom the Materials are 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 Materials.
MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS
KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS
SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT
https://www.khronos.org/registry/
THE MATERIALS ARE 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
MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
#include "gmock/gmock.h"
#include <algorithm>
#include <iterator>
#include <vector>
#include <experimental/algorithm>
#include <sycl/execution_policy>
#include <sycl/helpers/sycl_usm_vector.hpp>
namespace parallel = std::experimental::parallel;
struct GenerateNAlgorithm : public testing::Test {};
TEST_F(GenerateNAlgorithm, TestStdGenerateN) {
sycl::helpers::usm_vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};
sycl::helpers::usm_vector<int> result = {1, 1, 1, 1, 1, 1, 1, 1};
std::generate_n(begin(v), v.size(), []() { return 1; });
EXPECT_TRUE(std::equal(begin(v), end(v), begin(result)));
}
TEST_F(GenerateNAlgorithm, TestStd2GenerateN) {
sycl::helpers::usm_vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};
sycl::helpers::usm_vector<int> result = {1, 1, 1, 1, 5, 6, 7, 8};
std::generate_n(begin(v), 4, []() { return 1; });
EXPECT_TRUE(std::equal(begin(v), end(v), begin(result)));
}
TEST_F(GenerateNAlgorithm, TestStd3GenerateN) {
sycl::helpers::usm_vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};
sycl::helpers::usm_vector<int> result = v;
int negative_count = -v.size();
std::generate_n(begin(v), negative_count, []() { return 1; });
EXPECT_TRUE(std::equal(begin(v), end(v), begin(result)));
}
TEST_F(GenerateNAlgorithm, TestSyclGenerateN) {
sycl::helpers::usm_vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};
sycl::helpers::usm_vector<int> result = {1, 1, 1, 1, 1, 1, 1, 1};
cl::sycl::queue q;
sycl::sycl_execution_policy<class GenerateNAlgorithm> snp(q);
parallel::generate_n(snp, begin(v), v.size(), []() { return 1; });
EXPECT_TRUE(std::equal(begin(v), end(v), begin(result)));
}
TEST_F(GenerateNAlgorithm, TestSycl2GenerateN) {
sycl::helpers::usm_vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};
sycl::helpers::usm_vector<int> result = {1, 1, 1, 1, 5, 6, 7, 8};
cl::sycl::queue q;
sycl::sycl_execution_policy<class GenerateN2Algorithm> snp(q);
parallel::generate_n(snp, begin(v), 4, []() { return 1; });
EXPECT_TRUE(std::equal(begin(v), end(v), begin(result)));
}
TEST_F(GenerateNAlgorithm, TestSycl3GenerateN) {
sycl::helpers::usm_vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8};
sycl::helpers::usm_vector<int> result = v;
cl::sycl::queue q;
sycl::sycl_execution_policy<class GenerateN3Algorithm> snp(q);
int negative_count = -v.size();
parallel::generate_n(snp, begin(v), negative_count, []() { return 1; });
EXPECT_TRUE(std::equal(begin(v), end(v), begin(result)));
}
|
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2022, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "HookStateImage.h"
#include "Image.h"
#include "NebulaUtil.h"
#include "SSLUtil.h"
using namespace std;
bool HookStateImage::trigger(Image * image)
{
return image->has_changed_state();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string HookStateImage::format_message(Image * image)
{
std::ostringstream oss;
std::string image_xml;
std::string base64;
oss << "<HOOK_MESSAGE>"
<< "<HOOK_TYPE>STATE</HOOK_TYPE>"
<< "<HOOK_OBJECT>IMAGE</HOOK_OBJECT>"
<< "<STATE>" << Image::state_to_str(image->get_state()) << "</STATE>"
<< "<RESOURCE_ID>" << image->get_oid() << "</RESOURCE_ID>"
<< image->to_xml(image_xml)
<< "</HOOK_MESSAGE>";
ssl_util::base64_encode(oss.str(), base64);
return base64;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int HookStateImage::parse_template(Template * tmpl, std::string& error_str)
{
std::string state_str;
if (!tmpl->get("STATE", state_str))
{
error_str = "Hook STATE attribute not found or invalid";
return -1;
}
Image::ImageState state = Image::str_to_state(state_str);
if ( state == Image::INIT )
{
error_str = "Invalid or unkown STATE condition: " + state_str;
return -1;
}
tmpl->replace("STATE", Image::state_to_str(state));
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int HookStateImage::from_template(const Template * tmpl, string& error)
{
std::string state_str;
if ( tmpl->get("STATE", state_str) )
{
Image::ImageState is = Image::str_to_state(state_str);
if (is == Image::INIT)
{
error = "Invalid or unknown STATE attribute";
return -1;
}
}
else
{
error = "STATE attribute not found or invalid";
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int HookStateImage::post_update_template(Template * tmpl, std::string& error)
{
std::string new_state_str;
if ( tmpl->get("STATE", new_state_str) )
{
Image::ImageState new_state = Image::str_to_state(new_state_str);
if ( new_state != Image::INIT )
{
state = new_state;
tmpl->replace("STATE", new_state_str);
}
}
else
{
error = "The STATE attribute is not defined or it's invalid.";
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
|
//
// Created by xxzxcuzx_me on 10.03.19.
//
#include "Tree.h"
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <random>
Tree::Tree() noexcept {
size = 0;
//Przygotuj wartownika
guard = std::make_shared<ElementTree>();
guard->isBlack = true;
guard->parent = guard;
guard->leftChild = guard;
guard->rightChild = guard;
root = guard;
}
//Wykonaj operację obrotu w lewo wokół wskazanego węzła
void Tree::rotateLeft(std::shared_ptr<Tree::ElementTree> currentElement) {
auto y = currentElement->rightChild;
if(y != guard) {
auto p = currentElement->parent;
currentElement->rightChild = y->leftChild;
if(currentElement->rightChild != guard)
currentElement->rightChild->parent = currentElement;
y->leftChild = currentElement;
y->parent = p;
currentElement->parent = y;
if(p != guard) {
if(p->leftChild == currentElement)
p->leftChild = y;
else
p->rightChild = y;
} else
root = y;
}
}
//Wykonaj operację obrotu w prawo wokół wskazanego węzła
void Tree::rotateRight(std::shared_ptr<Tree::ElementTree> currentElement) {
auto y = currentElement->leftChild;
if(y != guard) {
auto p = currentElement->parent;
currentElement->leftChild = y->rightChild;
if(currentElement->leftChild != guard)
currentElement->leftChild->parent = currentElement;
y->rightChild = currentElement;
y->parent = p;
currentElement->parent = y;
if(p != guard) {
if(p->leftChild == currentElement)
p->leftChild = y;
else
p->rightChild = y;
} else
root = y;
}
}
void Tree::add(int value) {
auto Y = std::make_shared<ElementTree>();
auto X = std::make_shared<ElementTree>(value);
X->value = value;
X->leftChild = guard;
X->rightChild = guard;
X->parent = root;
//Sprawdź czy dodajesz pierwszy element
if(X->parent == guard) {
root = X;
size++;
}
else {
while(true) {
if(value < X->parent->value) {
if(X->parent->leftChild == guard) {
X->parent->leftChild = X;
break;
}
X->parent = X->parent->leftChild;
} else if(value > X->parent->value) {
if(X->parent->rightChild == guard) {
X->parent->rightChild = X;
break;
}
X->parent = X->parent->rightChild;
} else
return;
}
//Ustaw kolor węzła na czerwony
X->isBlack = false;
//Napraw drzewo
while((X != root) && (!X->parent->isBlack)) {
if(X->parent == X->parent->parent->leftChild) {
Y = X->parent->parent->rightChild;
if(!Y->isBlack) {
X->parent->isBlack = true;
Y->isBlack = true;
X->parent->parent->isBlack = false;
X = X->parent->parent;
continue;
}
if(X == X->parent->rightChild) {
X = X->parent;
rotateLeft(X);
}
X->parent->isBlack = true;
X->parent->parent->isBlack = false;
rotateRight(X->parent->parent);
break;
} else {
//Obsłuż przypadki symetryczne
Y = X->parent->parent->leftChild;
if(!Y->isBlack) {
X->parent->isBlack = true;
Y->isBlack = true;
X->parent->parent->isBlack = false;
X = X->parent->parent;
continue;
}
if(X == X->parent->leftChild) {
X = X->parent;
rotateRight(X);
}
X->parent->isBlack = true;
X->parent->parent->isBlack = false;
rotateLeft(X->parent->parent);
break;
}
}
root->isBlack = true;
size++;
}
}
void Tree::remove(int value) {
auto toRemove = findElement(value, root);
if(toRemove == guard)
std::cout<<"Takiej wartosci nie ma w drzewie\n";
std::shared_ptr<ElementTree> W, Y, Z;
if(toRemove->leftChild == guard || toRemove->rightChild == guard)
Y = toRemove;
else
Y = findNextElement(toRemove);
if(Y->leftChild != guard)
Z = Y->leftChild;
else
Z = Y->rightChild;
Z->parent = Y->parent;
if(Y->parent == guard)
root = Z;
else if(Y == Y->parent->leftChild)
Y->parent->leftChild = Z;
else
Y->parent->rightChild = Z;
if(Y != toRemove)
toRemove->value = Y->value;
//Napraw drzewo
if(Y->isBlack) {
while(Z != root && Z->isBlack) {
if(Z->parent->leftChild) {
W = Z->parent->rightChild;
if(!W->isBlack) {
W->isBlack = true;
Z->parent->isBlack = false;
rotateLeft(Z->parent);
W = Z->parent->rightChild;
}
if(W->leftChild->isBlack && W->rightChild->isBlack) {
W->isBlack = false;
Z = Z->parent;
continue;
}
if(W->rightChild->isBlack) {
W->leftChild->isBlack = true;
W->isBlack = false;
rotateRight(W);
W = Z->parent->rightChild;
}
W->isBlack = Z->parent->isBlack;
Z->parent->isBlack = true;
W->rightChild->isBlack = true;
rotateLeft(Z->parent);
Z = root;
} else {
//Obsłuż przypadki symetryczne
W = Z->parent->leftChild;
if(!W->isBlack) {
W->isBlack = true;
Z->parent->isBlack = false;
rotateLeft(Z->parent);
W = Z->parent->leftChild;
}
if(W->leftChild->isBlack && W->rightChild->isBlack) {
W->isBlack = true;
Z = Z->parent;
continue;
}
if(W->leftChild->isBlack) {
W->rightChild->isBlack = true;
W->isBlack = false;
rotateLeft(W);
W = Z->parent->leftChild;
}
W->isBlack = Z->parent->isBlack;
Z->parent->isBlack = true;
W->leftChild->isBlack = true;
rotateRight(Z->parent);
Z = root;
}
}
}
Z->isBlack = false;
size--;
}
void Tree::printTree() {
std::cout<<"Drzewo czerwono-czarne: (czerwone w nawiasach okraglych, a czarne w kwadratowych)\n";
if(root != nullptr && root != guard)
printNodeAndItsChildren(root, "", true);
else if(size == 0)
std::cout<<"W drzewie nie ma ani jednego elementu\n";
else //Nie powinno do tego dojść
std::cout<<"Wskaźnik na drzewo został uszkodzony\n";
}
void Tree::printNodeAndItsChildren(std::shared_ptr<ElementTree> currentElement, std::string indent, bool last) {
std::cout<<indent;
if(last) {
std::cout<<"\\-";
indent += " ";
} else {
std::cout<<"|-";
indent += "| ";
}
if(currentElement->isBlack)
std::cout<<" ["<<currentElement->value<<"]\n";
else
std::cout<<" ("<<currentElement->value<<")\n";
//Jeśli istnieje lewy potomek węzła to go wypisz
if(currentElement->leftChild != guard)
printNodeAndItsChildren(currentElement->leftChild, indent, false);
//Jeśli istnieje prawy potomek węzła to go wypisz
if(currentElement->rightChild != guard)
printNodeAndItsChildren(currentElement->rightChild, indent, true);
}
std::shared_ptr<Tree::ElementTree> Tree::findElement(int value, std::shared_ptr<ElementTree> localRoot) {
if(localRoot != guard) {
if(localRoot->value == value)
return localRoot;
if(value > localRoot->value)
return findElement(value, localRoot->rightChild);
else
return findElement(value, localRoot->leftChild);
}
return guard;
}
std::shared_ptr<Tree::ElementTree> Tree::findNextElement(std::shared_ptr<Tree::ElementTree> localRoot) {
if(localRoot != guard) {
if(localRoot->rightChild != guard)
return findSmallestElement(localRoot->rightChild);
else {
auto nextElement = localRoot->parent;
while((nextElement != guard) && (localRoot == nextElement->rightChild)) {
localRoot = nextElement;
nextElement = nextElement->parent;
}
return nextElement;
}
}
return guard;
}
std::shared_ptr<Tree::ElementTree> Tree::findSmallestElement(std::shared_ptr<Tree::ElementTree> localRoot) {
if(localRoot != guard)
while(localRoot->leftChild != guard)
localRoot = localRoot->leftChild;
return localRoot;
}
void Tree::findValue(int value) {
if(findElement(value, root) != guard)
return;
//std::cout<<"Wartosc "<<value<<" znajduje sie w drzewie\n";
else
std::cout<<"Wartosc "<<value<<" nie znajduje sie w drzewie\n";
}
void Tree::clear() {
size = 0;
//Przygotuj wartownika
guard = std::make_shared<ElementTree>();
guard->isBlack = true;
guard->parent = guard;
guard->leftChild = guard;
guard->rightChild = guard;
root = guard;
}
int Tree::returnRandomValue() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 9);
auto currentElement = root;
//Drzewo jest puste
if(currentElement == guard)
return 0;
int shouldStop = dis(gen);
//20 procent szans na zatrzymanie się w obecnym węźle
while(shouldStop<7) {
//50 procent szans na pójście w lewo
int shouldGoLeft = dis(gen)%2;
if(shouldGoLeft) {
if(currentElement->leftChild != guard)
currentElement = currentElement->leftChild;
else if(currentElement->rightChild != guard)
currentElement = currentElement->rightChild;
else
return currentElement->value;
} else {
if(currentElement->rightChild != guard)
currentElement = currentElement->rightChild;
else if(currentElement->leftChild != guard)
currentElement = currentElement->leftChild;
else
return currentElement->value;
}
shouldStop = dis(gen);
}
return currentElement->value;
}
|
// Copyright (c) 2010, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// crash_generation_server_test.cc
// Unit tests for CrashGenerationServer
#include <dirent.h>
#include <glob.h>
#include <stdint.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string>
#include "breakpad_googletest_includes.h"
#include "client/mac/crash_generation/client_info.h"
#include "client/mac/crash_generation/crash_generation_client.h"
#include "client/mac/crash_generation/crash_generation_server.h"
#include "client/mac/handler/exception_handler.h"
#include "client/mac/tests/spawn_child_process.h"
#include "common/tests/auto_tempdir.h"
#include "google_breakpad/processor/minidump.h"
namespace google_breakpad {
// This acts as the log sink for INFO logging from the processor
// logging code. The logging output confuses XCode and makes it think
// there are unit test failures. testlogging.h handles the overriding.
std::ostringstream info_log;
}
namespace {
using std::string;
using google_breakpad::AutoTempDir;
using google_breakpad::ClientInfo;
using google_breakpad::CrashGenerationClient;
using google_breakpad::CrashGenerationServer;
using google_breakpad::ExceptionHandler;
using google_breakpad::Minidump;
using google_breakpad::MinidumpContext;
using google_breakpad::MinidumpException;
using google_breakpad::MinidumpModule;
using google_breakpad::MinidumpModuleList;
using google_breakpad::MinidumpSystemInfo;
using google_breakpad::MinidumpThread;
using google_breakpad::MinidumpThreadList;
using testing::Test;
using namespace google_breakpad_test;
class CrashGenerationServerTest : public Test {
public:
// The port name to receive messages on
char mach_port_name[128];
// Filename of the last dump that was generated
string last_dump_name;
// PID of the child process
pid_t child_pid;
// A temp dir
AutoTempDir temp_dir;
// Counter just to ensure that we don't hit the same port again
static int i;
void SetUp() {
sprintf(mach_port_name,
"com.google.breakpad.ServerTest.%d.%d", getpid(),
CrashGenerationServerTest::i++);
child_pid = (pid_t)-1;
}
};
int CrashGenerationServerTest::i = 0;
// Test that starting and stopping a server works
TEST_F(CrashGenerationServerTest, testStartStopServer) {
CrashGenerationServer server(mach_port_name,
NULL, // dump callback
NULL, // dump context
NULL, // exit callback
NULL, // exit context
false, // generate dumps
""); // dump path
ASSERT_TRUE(server.Start());
ASSERT_TRUE(server.Stop());
}
// Test that requesting a dump via CrashGenerationClient works
// Test without actually dumping
TEST_F(CrashGenerationServerTest, testRequestDumpNoDump) {
CrashGenerationServer server(mach_port_name,
NULL, // dump callback
NULL, // dump context
NULL, // exit callback
NULL, // exit context
false, // don't generate dumps
temp_dir.path()); // dump path
ASSERT_TRUE(server.Start());
pid_t pid = fork();
ASSERT_NE(-1, pid);
if (pid == 0) {
CrashGenerationClient client(mach_port_name);
bool result = client.RequestDump();
exit(result ? 0 : 1);
}
int ret;
ASSERT_EQ(pid, waitpid(pid, &ret, 0));
EXPECT_TRUE(WIFEXITED(ret));
EXPECT_EQ(0, WEXITSTATUS(ret));
EXPECT_TRUE(server.Stop());
// check that no minidump was written
string pattern = temp_dir.path() + "/*";
glob_t dirContents;
ret = glob(pattern.c_str(), GLOB_NOSORT, NULL, &dirContents);
EXPECT_EQ(GLOB_NOMATCH, ret);
if (ret != GLOB_NOMATCH)
globfree(&dirContents);
}
void dumpCallback(void *context, const ClientInfo &client_info,
const std::string &file_path) {
if (context) {
CrashGenerationServerTest* self =
reinterpret_cast<CrashGenerationServerTest*>(context);
if (!file_path.empty())
self->last_dump_name = file_path;
self->child_pid = client_info.pid();
}
}
void *RequestDump(void *context) {
CrashGenerationClient client((const char*)context);
bool result = client.RequestDump();
return (void*)(result ? 0 : 1);
}
// Test that actually writing a minidump works
TEST_F(CrashGenerationServerTest, testRequestDump) {
CrashGenerationServer server(mach_port_name,
dumpCallback, // dump callback
this, // dump context
NULL, // exit callback
NULL, // exit context
true, // generate dumps
temp_dir.path()); // dump path
ASSERT_TRUE(server.Start());
pid_t pid = fork();
ASSERT_NE(-1, pid);
if (pid == 0) {
// Have to spawn off a separate thread to request the dump,
// because MinidumpGenerator assumes the handler thread is not
// the only thread
pthread_t thread;
if (pthread_create(&thread, NULL, RequestDump, (void*)mach_port_name) != 0)
exit(1);
void* result;
pthread_join(thread, &result);
exit(reinterpret_cast<intptr_t>(result));
}
int ret;
ASSERT_EQ(pid, waitpid(pid, &ret, 0));
EXPECT_TRUE(WIFEXITED(ret));
EXPECT_EQ(0, WEXITSTATUS(ret));
EXPECT_TRUE(server.Stop());
// check that minidump was written
ASSERT_FALSE(last_dump_name.empty());
struct stat st;
EXPECT_EQ(0, stat(last_dump_name.c_str(), &st));
EXPECT_LT(0, st.st_size);
// check client's PID
ASSERT_EQ(pid, child_pid);
}
static void Crasher() {
int *a = (int*)0x42;
fprintf(stdout, "Going to crash...\n");
fprintf(stdout, "A = %d", *a);
}
// Test that crashing a child process with an OOP ExceptionHandler installed
// results in a minidump being written by the CrashGenerationServer in
// the parent.
TEST_F(CrashGenerationServerTest, testChildProcessCrash) {
CrashGenerationServer server(mach_port_name,
dumpCallback, // dump callback
this, // dump context
NULL, // exit callback
NULL, // exit context
true, // generate dumps
temp_dir.path()); // dump path
ASSERT_TRUE(server.Start());
pid_t pid = fork();
ASSERT_NE(-1, pid);
if (pid == 0) {
// Instantiate an OOP exception handler.
ExceptionHandler eh("", NULL, NULL, NULL, true, mach_port_name);
Crasher();
// not reached
exit(0);
}
int ret;
ASSERT_EQ(pid, waitpid(pid, &ret, 0));
EXPECT_FALSE(WIFEXITED(ret));
EXPECT_TRUE(server.Stop());
// check that minidump was written
ASSERT_FALSE(last_dump_name.empty());
struct stat st;
EXPECT_EQ(0, stat(last_dump_name.c_str(), &st));
EXPECT_LT(0, st.st_size);
// Read the minidump, sanity check some data.
Minidump minidump(last_dump_name.c_str());
ASSERT_TRUE(minidump.Read());
MinidumpSystemInfo* system_info = minidump.GetSystemInfo();
ASSERT_TRUE(system_info);
const MDRawSystemInfo* raw_info = system_info->system_info();
ASSERT_TRUE(raw_info);
EXPECT_EQ(kNativeArchitecture, raw_info->processor_architecture);
MinidumpThreadList* thread_list = minidump.GetThreadList();
ASSERT_TRUE(thread_list);
ASSERT_EQ((unsigned int)1, thread_list->thread_count());
MinidumpThread* main_thread = thread_list->GetThreadAtIndex(0);
ASSERT_TRUE(main_thread);
MinidumpContext* context = main_thread->GetContext();
ASSERT_TRUE(context);
EXPECT_EQ(kNativeContext, context->GetContextCPU());
MinidumpModuleList* module_list = minidump.GetModuleList();
ASSERT_TRUE(module_list);
const MinidumpModule* main_module = module_list->GetMainModule();
ASSERT_TRUE(main_module);
EXPECT_EQ(GetExecutablePath(), main_module->code_file());
}
#if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6) && \
(defined(__x86_64__) || defined(__i386__))
// Test that crashing a child process of a different architecture
// produces a valid minidump.
TEST_F(CrashGenerationServerTest, testChildProcessCrashCrossArchitecture) {
CrashGenerationServer server(mach_port_name,
dumpCallback, // dump callback
this, // dump context
NULL, // exit callback
NULL, // exit context
true, // generate dumps
temp_dir.path()); // dump path
ASSERT_TRUE(server.Start());
// Spawn a child process
string helper_path = GetHelperPath();
const char* argv[] = {
helper_path.c_str(),
"crash",
mach_port_name,
NULL
};
pid_t pid = spawn_child_process(argv);
ASSERT_NE(-1, pid);
int ret;
ASSERT_EQ(pid, waitpid(pid, &ret, 0));
EXPECT_FALSE(WIFEXITED(ret));
EXPECT_TRUE(server.Stop());
// check that minidump was written
ASSERT_FALSE(last_dump_name.empty());
struct stat st;
EXPECT_EQ(0, stat(last_dump_name.c_str(), &st));
EXPECT_LT(0, st.st_size);
const MDCPUArchitecture kExpectedArchitecture =
#if defined(__x86_64__)
MD_CPU_ARCHITECTURE_X86
#elif defined(__i386__)
MD_CPU_ARCHITECTURE_AMD64
#endif
;
const u_int32_t kExpectedContext =
#if defined(__i386__)
MD_CONTEXT_AMD64
#elif defined(__x86_64__)
MD_CONTEXT_X86
#endif
;
// Read the minidump, sanity check some data.
Minidump minidump(last_dump_name.c_str());
ASSERT_TRUE(minidump.Read());
MinidumpSystemInfo* system_info = minidump.GetSystemInfo();
ASSERT_TRUE(system_info);
const MDRawSystemInfo* raw_info = system_info->system_info();
ASSERT_TRUE(raw_info);
EXPECT_EQ(kExpectedArchitecture, raw_info->processor_architecture);
MinidumpThreadList* thread_list = minidump.GetThreadList();
ASSERT_TRUE(thread_list);
ASSERT_EQ((unsigned int)1, thread_list->thread_count());
MinidumpThread* main_thread = thread_list->GetThreadAtIndex(0);
ASSERT_TRUE(main_thread);
MinidumpContext* context = main_thread->GetContext();
ASSERT_TRUE(context);
EXPECT_EQ(kExpectedContext, context->GetContextCPU());
MinidumpModuleList* module_list = minidump.GetModuleList();
ASSERT_TRUE(module_list);
const MinidumpModule* main_module = module_list->GetMainModule();
ASSERT_TRUE(main_module);
EXPECT_EQ(helper_path, main_module->code_file());
}
#endif
} // namespace
|
#include "Line.h"
#include "OrientationTest.h"
bool Line::IsIntersecting(cv::Point2f a, cv::Point2f b, cv::Point2f c, cv::Point2f d)
{
//we check the condition for non - intersection
bool firstCombo = ((OrientationTest::getSign(a, b, c) == OrientationTest::getSign(a, b, d)) && (OrientationTest::getSign(c, d, a) != OrientationTest::getSign(c, d, b)));
bool secondCombo = ((OrientationTest::getSign(a, b, c) != OrientationTest::getSign(a, b, d)) && (OrientationTest::getSign(c, d, a) == OrientationTest::getSign(c, d, b)));
// we return the not of the answe because we look for intersection
return !(firstCombo || secondCombo);
}
|
/*
* Copyright (c) 2018 oxarbitrage and contributors.
*
* The MIT License
*
* 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 <boost/test/unit_test.hpp>
#include <graphene/chain/hardfork.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/balance_object.hpp>
#include <graphene/chain/vesting_balance_object.hpp>
#include <graphene/chain/witness_object.hpp>
#include <graphene/chain/committee_member_object.hpp>
#include <graphene/chain/worker_object.hpp>
#include "../common/database_fixture.hpp"
#include <graphene/app/database_api.hpp>
using namespace graphene::chain;
using namespace graphene::chain::test;
struct gpos_fixture: database_fixture
{
const worker_object& create_worker( const account_id_type owner, const share_type daily_pay,
const fc::microseconds& duration ) {
worker_create_operation op;
op.owner = owner;
op.daily_pay = daily_pay;
op.initializer = vesting_balance_worker_initializer(1);
op.work_begin_date = db.head_block_time();
op.work_end_date = op.work_begin_date + duration;
trx.operations.push_back(op);
set_expiration(db, trx);
trx.validate();
processed_transaction ptx = db.push_transaction(trx, ~0);
trx.clear();
return db.get<worker_object>(ptx.operation_results[0].get<object_id_type>());
}
const vesting_balance_object& create_vesting(const account_id_type owner, const asset amount,
const vesting_balance_type type)
{
vesting_balance_create_operation op;
op.creator = owner;
op.owner = owner;
op.amount = amount;
op.balance_type = type;
trx.operations.push_back(op);
set_expiration(db, trx);
processed_transaction ptx = PUSH_TX(db, trx, ~0);
trx.clear();
return db.get<vesting_balance_object>(ptx.operation_results[0].get<object_id_type>());
}
void withdraw_gpos_vesting(const vesting_balance_id_type v_bid, const account_id_type owner, const asset amount,
/*const vesting_balance_type type, */const fc::ecc::private_key& key)
{
vesting_balance_withdraw_operation op;
op.vesting_balance = v_bid;
op.owner = owner;
op.amount = amount;
//op.balance_type = type;
trx.operations.push_back(op);
set_expiration(db, trx);
trx.validate();
sign(trx, key);
PUSH_TX(db, trx);
trx.clear();
}
void update_payout_interval(std::string asset_name, fc::time_point start, uint32_t interval)
{
auto dividend_holder_asset_object = get_asset(asset_name);
asset_update_dividend_operation op;
op.issuer = dividend_holder_asset_object.issuer;
op.asset_to_update = dividend_holder_asset_object.id;
op.new_options.next_payout_time = start;
op.new_options.payout_interval = interval;
trx.operations.push_back(op);
set_expiration(db, trx);
PUSH_TX(db, trx, ~0);
trx.operations.clear();
}
void update_gpos_global(uint32_t vesting_period, uint32_t vesting_subperiod, fc::time_point_sec period_start)
{
db.modify(db.get_global_properties(), [vesting_period, vesting_subperiod, period_start](global_property_object& p) {
p.parameters.extensions.value.gpos_period = vesting_period;
p.parameters.extensions.value.gpos_subperiod = vesting_subperiod;
p.parameters.extensions.value.gpos_period_start = period_start.sec_since_epoch();
p.parameters.extensions.value.gpos_vesting_lockin_period = vesting_subperiod;
});
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period(), vesting_period);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_subperiod(), vesting_subperiod);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period_start(), period_start.sec_since_epoch());
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_vesting_lockin_period(), vesting_subperiod);
}
void update_maintenance_interval(uint32_t new_interval)
{
db.modify(db.get_global_properties(), [new_interval](global_property_object& p) {
p.parameters.maintenance_interval = new_interval;
});
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.maintenance_interval, new_interval);
}
void vote_for(const account_id_type account_id, const vote_id_type vote_for, const fc::ecc::private_key& key)
{
account_update_operation op;
op.account = account_id;
op.new_options = account_id(db).options;
op.new_options->votes.insert(vote_for);
op.extensions.value.update_last_voting_time = true;
trx.operations.push_back(op);
set_expiration(db, trx);
trx.validate();
sign(trx, key);
PUSH_TX(db, trx);
trx.clear();
}
void fill_reserve_pool(const account_id_type account_id, asset amount)
{
asset_reserve_operation op;
op.payer = account_id;
op.amount_to_reserve = amount;
trx.operations.push_back(op);
trx.validate();
set_expiration(db, trx);
PUSH_TX( db, trx, ~0 );
trx.clear();
}
void advance_x_maint(int periods)
{
for(int i=0; i<periods; i++)
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
}
};
BOOST_FIXTURE_TEST_SUITE( gpos_tests, gpos_fixture )
BOOST_AUTO_TEST_CASE(gpos_vesting_type)
{
ACTORS((alice)(bob));
try
{
const auto& core = asset_id_type()(db);
// send some asset to alice and bob
transfer( committee_account, alice_id, core.amount( 1000 ) );
transfer( committee_account, bob_id, core.amount( 1000 ) );
generate_block();
// gpos balance creation is not allowed before HF
vesting_balance_create_operation op;
op.creator = alice_id;
op.owner = alice_id;
op.amount = core.amount(100);
op.balance_type = vesting_balance_type::gpos;
trx.operations.push_back(op);
set_expiration(db, trx);
GRAPHENE_REQUIRE_THROW( PUSH_TX(db, trx, ~0), fc::exception );
trx.clear();
// pass hardfork
generate_blocks( HARDFORK_GPOS_TIME );
generate_block();
// repeat operation
trx.operations.push_back(op);
set_expiration(db, trx);
processed_transaction ptx = PUSH_TX(db, trx, ~0);
trx.clear();
generate_block();
auto alice_vesting = db.get<vesting_balance_object>(ptx.operation_results[0].get<object_id_type>());
// check created vesting amount and policy
BOOST_CHECK_EQUAL(alice_vesting.balance.amount.value, 100);
BOOST_CHECK_EQUAL(alice_vesting.policy.get<linear_vesting_policy>().vesting_duration_seconds,
db.get_global_properties().parameters.gpos_subperiod());
BOOST_CHECK_EQUAL(alice_vesting.policy.get<linear_vesting_policy>().vesting_cliff_seconds,
db.get_global_properties().parameters.gpos_subperiod());
// bob creates a gpos vesting with his custom policy
{
vesting_balance_create_operation op;
op.creator = bob_id;
op.owner = bob_id;
op.amount = core.amount(200);
op.balance_type = vesting_balance_type::gpos;
op.policy = cdd_vesting_policy_initializer{ 60*60*24 };
trx.operations.push_back(op);
set_expiration(db, trx);
ptx = PUSH_TX(db, trx, ~0);
trx.clear();
}
auto bob_vesting = db.get<vesting_balance_object>(ptx.operation_results[0].get<object_id_type>());
generate_block();
// policy is not the one defined by the user but default
BOOST_CHECK_EQUAL(bob_vesting.balance.amount.value, 200);
BOOST_CHECK_EQUAL(bob_vesting.policy.get<linear_vesting_policy>().vesting_duration_seconds,
db.get_global_properties().parameters.gpos_subperiod());
BOOST_CHECK_EQUAL(bob_vesting.policy.get<linear_vesting_policy>().vesting_cliff_seconds,
db.get_global_properties().parameters.gpos_subperiod());
}
catch (fc::exception& e)
{
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( dividends )
{
ACTORS((alice)(bob));
try
{
// move to 1 week before hardfork
generate_blocks( HARDFORK_GPOS_TIME - fc::days(7) );
generate_block();
const auto& core = asset_id_type()(db);
// all core coins are in the committee_account
BOOST_CHECK_EQUAL(get_balance(committee_account(db), core), 1000000000000000);
// transfer half of the total stake to alice so not all the dividends will go to the committee_account
transfer( committee_account, alice_id, core.amount( 500000000000000 ) );
generate_block();
// send some to bob
transfer( committee_account, bob_id, core.amount( 1000 ) );
generate_block();
// committee balance
BOOST_CHECK_EQUAL(get_balance(committee_account(db), core), 499999999999000);
// alice balance
BOOST_CHECK_EQUAL(get_balance(alice_id(db), core), 500000000000000);
// bob balance
BOOST_CHECK_EQUAL(get_balance(bob_id(db), core), 1000);
// get core asset object
const auto& dividend_holder_asset_object = get_asset(GRAPHENE_SYMBOL);
// by default core token pays dividends once per month
const auto& dividend_data = dividend_holder_asset_object.dividend_data(db);
BOOST_CHECK_EQUAL(*dividend_data.options.payout_interval, 2592000); // 30 days
// update the payout interval for speed purposes of the test
update_payout_interval(core.symbol, db.head_block_time() + fc::minutes(1), 60 * 60 * 24); // 1 day
generate_block();
BOOST_CHECK_EQUAL(*dividend_data.options.payout_interval, 86400); // 1 day now
// get the dividend distribution account
const account_object& dividend_distribution_account = dividend_data.dividend_distribution_account(db);
// transfering some coins to distribution account.
// simulating the blockchain haves some dividends to pay.
transfer( committee_account, dividend_distribution_account.id, core.amount( 100 ) );
generate_block();
// committee balance
BOOST_CHECK_EQUAL(get_balance(committee_account(db), core), 499999999998900 );
// distribution account balance
BOOST_CHECK_EQUAL(get_balance(dividend_distribution_account, core), 100);
// get when is the next payout time as we need to advance there
auto next_payout_time = dividend_data.options.next_payout_time;
// advance to next payout
generate_blocks(*next_payout_time);
wdump((*next_payout_time));
// advance to next maint after payout time arrives
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// check balances now, dividends are paid "normally"
BOOST_CHECK_EQUAL(get_balance(committee_account(db), core), 499999999998949 );
BOOST_CHECK_EQUAL(get_balance(alice_id(db), core), 500000000000050 );
BOOST_CHECK_EQUAL(get_balance(bob_id(db), core), 1000 );
BOOST_CHECK_EQUAL(get_balance(dividend_distribution_account, core), 1);
// advance to hardfork
generate_blocks( HARDFORK_GPOS_TIME );
// advance to next maint
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// send 99 to the distribution account so it will have 100 PPY again to share
transfer( committee_account, dividend_distribution_account.id, core.amount( 99 ) );
generate_block();
// get when is the next payout time as we need to advance there
next_payout_time = dividend_data.options.next_payout_time;
// advance to next payout
generate_blocks(*next_payout_time);
// advance to next maint
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// make sure no dividends were paid "normally"
BOOST_CHECK_EQUAL(get_balance(committee_account(db), core), 499999999998850 );
BOOST_CHECK_EQUAL(get_balance(alice_id(db), core), 500000000000050 );
BOOST_CHECK_EQUAL(get_balance(bob_id(db), core), 1000 );
BOOST_CHECK_EQUAL(get_balance(dividend_distribution_account, core), 100);
// create vesting balance
create_vesting(bob_id, core.amount(100), vesting_balance_type::gpos);
// need to vote to get paid
auto witness1 = witness_id_type(1)(db);
vote_for(bob_id, witness1.vote_id, bob_private_key);
generate_block();
// check balances
BOOST_CHECK_EQUAL(get_balance(bob_id(db), core), 900 );
BOOST_CHECK_EQUAL(get_balance(dividend_distribution_account, core), 100);
// advance to next payout
generate_blocks(*next_payout_time);
// advance to next maint
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// check balances, dividends paid to bob
BOOST_CHECK_EQUAL(get_balance(bob_id(db), core), 1000 );
BOOST_CHECK_EQUAL(get_balance(dividend_distribution_account, core), 0);
}
catch (fc::exception& e)
{
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( gpos_basic_dividend_distribution_to_core_asset )
{
using namespace graphene;
ACTORS((alice)(bob)(carol)(dave));
try {
const auto& core = asset_id_type()(db);
BOOST_TEST_MESSAGE("Creating test asset");
{
asset_create_operation creator;
creator.issuer = account_id_type();
creator.fee = asset();
creator.symbol = "TESTB";
creator.common_options.max_supply = 100000000;
creator.precision = 2;
creator.common_options.market_fee_percent = GRAPHENE_MAX_MARKET_FEE_PERCENT/100; /*1%*/
creator.common_options.issuer_permissions = UIA_ASSET_ISSUER_PERMISSION_MASK;
creator.common_options.flags = charge_market_fee;
creator.common_options.core_exchange_rate = price({asset(2),asset(1,asset_id_type(1))});
trx.operations.push_back(std::move(creator));
set_expiration(db, trx);
PUSH_TX( db, trx, ~0 );
trx.operations.clear();
}
// pass hardfork
generate_blocks( HARDFORK_GPOS_TIME );
generate_block();
const auto& dividend_holder_asset_object = asset_id_type(0)(db);
const auto& dividend_data = dividend_holder_asset_object.dividend_data(db);
const account_object& dividend_distribution_account = dividend_data.dividend_distribution_account(db);
const account_object& alice = get_account("alice");
const account_object& bob = get_account("bob");
const account_object& carol = get_account("carol");
const account_object& dave = get_account("dave");
const auto& test_asset_object = get_asset("TESTB");
auto issue_asset_to_account = [&](const asset_object& asset_to_issue, const account_object& destination_account, int64_t amount_to_issue)
{
asset_issue_operation op;
op.issuer = asset_to_issue.issuer;
op.asset_to_issue = asset(amount_to_issue, asset_to_issue.id);
op.issue_to_account = destination_account.id;
trx.operations.push_back( op );
set_expiration(db, trx);
PUSH_TX( db, trx, ~0 );
trx.operations.clear();
};
auto verify_pending_balance = [&](const account_object& holder_account_obj, const asset_object& payout_asset_obj, int64_t expected_balance) {
int64_t pending_balance = get_dividend_pending_payout_balance(dividend_holder_asset_object.id,
holder_account_obj.id,
payout_asset_obj.id);
BOOST_CHECK_EQUAL(pending_balance, expected_balance);
};
auto advance_to_next_payout_time = [&]() {
// Advance to the next upcoming payout time
BOOST_REQUIRE(dividend_data.options.next_payout_time);
fc::time_point_sec next_payout_scheduled_time = *dividend_data.options.next_payout_time;
idump((next_payout_scheduled_time));
// generate blocks up to the next scheduled time
generate_blocks(next_payout_scheduled_time);
// if the scheduled time fell on a maintenance interval, then we should have paid out.
// if not, we need to advance to the next maintenance interval to trigger the payout
if (dividend_data.options.next_payout_time)
{
// we know there was a next_payout_time set when we entered this, so if
// it has been cleared, we must have already processed payouts, no need to
// further advance time.
BOOST_REQUIRE(dividend_data.options.next_payout_time);
if (*dividend_data.options.next_payout_time == next_payout_scheduled_time)
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block(); // get the maintenance skip slots out of the way
}
idump((db.head_block_time()));
};
// the first test will be testing pending balances, so we need to hit a
// maintenance interval that isn't the payout interval. Payout is
// every 3 days, maintenance interval is every 1 day.
advance_to_next_payout_time();
// Set up the first test, issue alice, bob, and carol, and dave each 1/4 of the total
// supply of the core asset.
// Then deposit 400 TEST in the distribution account, and see that they
// each are credited 100 TEST.
transfer( committee_account(db), alice, asset( 250000000000000 ) );
transfer( committee_account(db), bob, asset( 250000000000000 ) );
transfer( committee_account(db), carol, asset( 250000000000000 ) );
transfer( committee_account(db), dave, asset( 250000000000000 ) );
// create vesting balance
// bob has not vested anything
create_vesting(alice_id, core.amount(25000000), vesting_balance_type::gpos);
create_vesting(carol_id, core.amount(25000000), vesting_balance_type::gpos);
create_vesting(dave_id, core.amount(25000000), vesting_balance_type::gpos);
// need to vote to get paid
// carol doesn't participate in voting
auto witness1 = witness_id_type(1)(db);
vote_for(alice_id, witness1.vote_id, alice_private_key);
vote_for(bob_id, witness1.vote_id, bob_private_key);
vote_for(dave_id, witness1.vote_id, dave_private_key);
// issuing 30000 TESTB to the dividend account
// alice and dave should receive 10000 TESTB as they have gpos vesting and
// participated in voting
// bob should not receive any TESTB as he doesn't have gpos vested
// carol should not receive any TESTB as she doesn't participated in voting
// remaining 10000 TESTB should be deposited in commitee_accoount.
BOOST_TEST_MESSAGE("Issuing 30000 TESTB to the dividend account");
issue_asset_to_account(test_asset_object, dividend_distribution_account, 30000);
generate_block();
BOOST_TEST_MESSAGE( "Generating blocks until next maintenance interval" );
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block(); // get the maintenance skip slots out of the way
verify_pending_balance(alice, test_asset_object, 10000);
verify_pending_balance(bob, test_asset_object, 0);
verify_pending_balance(carol, test_asset_object, 0);
verify_pending_balance(dave, test_asset_object, 10000);
advance_to_next_payout_time();
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block(); // get the maintenance skip slots out of the way
auto verify_dividend_payout_operations = [&](const account_object& destination_account, const asset& expected_payout)
{
BOOST_TEST_MESSAGE("Verifying the virtual op was created");
const account_transaction_history_index& hist_idx = db.get_index_type<account_transaction_history_index>();
auto account_history_range = hist_idx.indices().get<by_seq>().equal_range(boost::make_tuple(destination_account.id));
BOOST_REQUIRE(account_history_range.first != account_history_range.second);
const operation_history_object& history_object = std::prev(account_history_range.second)->operation_id(db);
const asset_dividend_distribution_operation& distribution_operation = history_object.op.get<asset_dividend_distribution_operation>();
BOOST_CHECK(distribution_operation.account_id == destination_account.id);
BOOST_CHECK(std::find(distribution_operation.amounts.begin(), distribution_operation.amounts.end(), expected_payout)
!= distribution_operation.amounts.end());
};
BOOST_TEST_MESSAGE("Verifying the payouts");
BOOST_CHECK_EQUAL(get_balance(alice, test_asset_object), 10000);
verify_dividend_payout_operations(alice, asset(10000, test_asset_object.id));
verify_pending_balance(alice, test_asset_object, 0);
BOOST_CHECK_EQUAL(get_balance(bob, test_asset_object), 0);
verify_pending_balance(bob, test_asset_object, 0);
BOOST_CHECK_EQUAL(get_balance(carol, test_asset_object), 0);
verify_pending_balance(carol, test_asset_object, 0);
BOOST_CHECK_EQUAL(get_balance(dave, test_asset_object), 10000);
verify_dividend_payout_operations(dave, asset(10000, test_asset_object.id));
verify_pending_balance(dave, test_asset_object, 0);
BOOST_CHECK_EQUAL(get_balance(account_id_type(0)(db), test_asset_object), 10000);
} catch(fc::exception& e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( votes_on_gpos_activation )
{
ACTORS((alice)(bob));
try {
const auto& core = asset_id_type()(db);
// send some asset to alice and bob
transfer( committee_account, alice_id, core.amount( 1000 ) );
transfer( committee_account, bob_id, core.amount( 1000 ) );
generate_block();
// update default gpos
// 5184000 = 60x60x24x6 = 6 days
// 864000 = 60x60x24x1 = 1 days
update_gpos_global(518400, 86400, HARDFORK_GPOS_TIME);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period(), 518400);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_subperiod(), 86400);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period_start(), HARDFORK_GPOS_TIME.sec_since_epoch());
// no votes for witness 1
auto witness1 = witness_id_type(1)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 0);
// no votes for witness 2
auto witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness2.total_votes, 0);
// vote for witness1 and witness2 - this before GPOS period starts
vote_for(alice_id, witness1.vote_id, alice_private_key);
vote_for(bob_id, witness2.vote_id, bob_private_key);
// go to maint
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// vote is the same as amount in the first subperiod since voting
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 1000);
BOOST_CHECK_EQUAL(witness2.total_votes, 1000);
update_maintenance_interval(3600); //update maintenance interval to 1hr to evaluate sub-periods
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.maintenance_interval, 3600);
// move to hardfork
generate_blocks( HARDFORK_GPOS_TIME );
generate_block();
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 1000);
BOOST_CHECK_EQUAL(witness2.total_votes, 1000);
// add some vesting to alice and don't add anything for Bob
create_vesting(alice_id, core.amount(99), vesting_balance_type::gpos);
generate_block();
vote_for(alice_id, witness1.vote_id, alice_private_key);
generate_block();
advance_x_maint(1);
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
//System needs to consider votes based on both regular balance + GPOS balance for 1/2 sub-period on GPOS activation
BOOST_CHECK_EQUAL(witness1.total_votes, 1000);
BOOST_CHECK_EQUAL(witness2.total_votes, 1000);
advance_x_maint(6);
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 1000);
BOOST_CHECK_EQUAL(witness2.total_votes, 1000);
advance_x_maint(5);
generate_block();
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
//Since Alice has votes, votes should be based on GPOS balance i.e 99
//Since Bob not voted after GPOS activation, witness2 votes should be 0 after crossing 1/2 sub-period(12 maintanence intervals in this case)
BOOST_CHECK_EQUAL(witness1.total_votes, 99);
BOOST_CHECK_EQUAL(witness2.total_votes, 0);
}
catch (fc::exception &e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( voting )
{
ACTORS((alice)(bob));
try {
// move to hardfork
generate_blocks( HARDFORK_GPOS_TIME );
generate_block();
auto now = HARDFORK_GPOS_TIME;
const auto& core = asset_id_type()(db);
// send some asset to alice and bob
transfer( committee_account, alice_id, core.amount( 1000 ) );
transfer( committee_account, bob_id, core.amount( 1000 ) );
generate_block();
// default maintenance_interval is 1 day
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.maintenance_interval, 86400);
// add some vesting to alice and bob
create_vesting(alice_id, core.amount(100), vesting_balance_type::gpos);
create_vesting(bob_id, core.amount(100), vesting_balance_type::gpos);
generate_block();
// default gpos values
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period(), 15552000);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_subperiod(), 2592000);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period_start(), HARDFORK_GPOS_TIME.sec_since_epoch());
// update default gpos for test speed
// 5184000 = 60x60x24x60 = 60 days
// 864000 = 60x60x24x10 = 10 days
update_gpos_global(5184000, 864000, now);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period(), 5184000);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_subperiod(), 864000);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period_start(), now.sec_since_epoch());
// end global changes
generate_block();
// no votes for witness 1
auto witness1 = witness_id_type(1)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 0);
// no votes for witness 2
auto witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness2.total_votes, 0);
// vesting performance is 0 for both alice and bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 0);
// vote for witness1 and witness2 - sub-period 1
vote_for(alice_id, witness1.vote_id, alice_private_key);
vote_for(bob_id, witness2.vote_id, bob_private_key);
// after voting, vesting performance is 1 for both alice and bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 1);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
// go to maint
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// need to consider both gpos and regular balance for first 1/2 sub period
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 1000);
BOOST_CHECK_EQUAL(witness2.total_votes, 1000);
// vesting performance is 1 for both alice and bob during whole gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 1);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(6);
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 100);
BOOST_CHECK_EQUAL(witness2.total_votes, 100);
// vesting performance is 1 for both alice and bob during whole gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 1);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(3);
// vesting performance is 1 for both alice and bob during whole gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 1);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(1);
// new subperiod started, vesting performance is decreased to 5/6 for both alice and bob, until they vote
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 5.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 5.0/6.0);
//Bob votes for witness2 - sub-period 2
vote_for(bob_id, witness2.vote_id, bob_private_key);
// after voting, vesting performance is 5/6 for alice and 1 for bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 5.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
// go to maint
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// vote decay as time pass
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 83);
BOOST_CHECK_EQUAL(witness2.total_votes, 100);
// after voting, vesting performance is 5/6 for alice and 1 for bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 5.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(4);
// vesting performance does not change during gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 5.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(4);
// vesting performance does not change during gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 5.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(1);
// new subperiod started, vesting performance is decreased to 4/6 for alice and 5/6 for bob, until they vote
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 4.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 5.0/6.0);
//Bob votes for witness2 - sub-period 3
vote_for(bob_id, witness2.vote_id, bob_private_key);
// after voting, vesting performance is 4/6 for alice and 1 for bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 4.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// decay more
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 66);
BOOST_CHECK_EQUAL(witness2.total_votes, 100);
// after voting, vesting performance is 4/6 for alice and 1 for bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 4.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(4);
// vesting performance does not change during gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 4.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(4);
// vesting performance does not change during gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 4.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(1);
// new subperiod started, vesting performance is decreased to 3/6 for alice and 5/6 for bob, until they vote
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 3.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 5.0/6.0);
// Bob votes for witness2 - sub-period 4
vote_for(bob_id, witness2.vote_id, bob_private_key);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// decay more
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 50);
BOOST_CHECK_EQUAL(witness2.total_votes, 100);
// after voting, vesting performance is 3/6 for alice and 1 for bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 3.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(4);
// vesting performance does not change during gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 3.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(4);
// vesting performance does not change during gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 3.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(1);
// new subperiod started, vesting performance is decreased to 2/6 for alice and 5/6 for bob, until they vote
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 2.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 5.0/6.0);
// Bob votes for witness2 - sub-period 5
vote_for(bob_id, witness2.vote_id, bob_private_key);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// decay more
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 33);
BOOST_CHECK_EQUAL(witness2.total_votes, 100);
// after voting, vesting performance is 2/6 for alice and 1 for bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 2.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(4);
// vesting performance does not change during gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 2.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(4);
// vesting performance does not change during gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 2.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(1);
// new subperiod started, vesting performance is decreased to 1/6 for alice and 5/6 for bob, until they vote
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 1.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 5.0/6.0);
// Bob votes for witness2 - sub-period 6
vote_for(bob_id, witness2.vote_id, bob_private_key);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// decay more
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 16);
BOOST_CHECK_EQUAL(witness2.total_votes, 100);
// after voting, vesting performance is 1/6 for alice and 1 for bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 1.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
// we are still in gpos period 1
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period_start(), now.sec_since_epoch());
advance_x_maint(8);
// vesting performance does not change during gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 1.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(1);
// a new GPOS period is in but vote from user is before the start. Whoever votes in 6th sub-period, votes will carry
now = db.head_block_time();
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period_start(), HARDFORK_GPOS_TIME.sec_since_epoch() + db.get_global_properties().parameters.gpos_period());
// new gpos period and his first subperiod started,
// vesting performance is decreased to 0 for alice, as she did not vote
// but stays 1 for bob, as he voted in last subperiod in previous gpos period
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1 );
generate_block();
// we are in the second GPOS period, at subperiod 1,
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 0);
//It's critical here, since bob votes in 6th sub-period of last vesting period, witness2 should retain his votes
BOOST_CHECK_EQUAL(witness2.total_votes, 100);
// lets vote here from alice to generate votes for witness 1
//vote from bob to reatin VF 1
vote_for(alice_id, witness1.vote_id, alice_private_key);
vote_for(bob_id, witness2.vote_id, bob_private_key);
// after voting, vesting performance is 1 for both alice and bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 1);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
// go to maint
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 100);
BOOST_CHECK_EQUAL(witness2.total_votes, 100);
advance_x_maint(8);
// vesting performance does not change during gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 1);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(1);
// new subperiod started, vesting performance is decreased to 5/6 for both alice and bob, until they vote
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 5.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 5.0/6.0);
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 83);
BOOST_CHECK_EQUAL(witness2.total_votes, 83);
vote_for(bob_id, witness2.vote_id, bob_private_key);
generate_block();
// after voting, vesting performance is 5/6 for alice and 1 for bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 5.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(9);
// vesting performance does not change during gpos subperiod
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 5.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 1);
advance_x_maint(1);
// new subperiod started, vesting performance is decreased to 4/6 for alice and 5/6 for bob, until they vote
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 4.0/6.0);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 5.0/6.0);
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 66);
BOOST_CHECK_EQUAL(witness2.total_votes, 83);
// alice votes again, now for witness 2, her vote worth 100 now
vote_for(alice_id, witness2.vote_id, alice_private_key);
// after voting, vesting performance is 1 for alice and 5.0/6.0 for bob
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(alice_id(db)), 1);
BOOST_CHECK_EQUAL(db.calculate_vesting_factor(bob_id(db)), 5.0/6.0);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
witness1 = witness_id_type(1)(db);
witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 100);
BOOST_CHECK_EQUAL(witness2.total_votes, 183);
}
catch (fc::exception &e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( rolling_period_start )
{
// period start rolls automatically after HF
try {
// update default gpos global parameters to make this thing faster
update_gpos_global(518400, 86400, HARDFORK_GPOS_TIME);
generate_blocks(HARDFORK_GPOS_TIME);
update_maintenance_interval(3600); //update maintenance interval to 1hr to evaluate sub-periods
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.maintenance_interval, 3600);
auto vesting_period_1 = db.get_global_properties().parameters.gpos_period_start();
auto now = db.head_block_time();
// moving outside period:
while( db.head_block_time() <= now + fc::days(6) )
{
generate_block();
}
generate_block();
auto vesting_period_2 = db.get_global_properties().parameters.gpos_period_start();
//difference between start of two consecutive vesting periods should be 6 days
BOOST_CHECK_EQUAL(vesting_period_1 + 518400, vesting_period_2);
}
catch (fc::exception &e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( worker_dividends_voting )
{
try {
// advance to HF
fc::time_point_sec GPOS_HARDFORK_TIME =
fc::time_point_sec(1581976800); // Use mainnet GPOS hardfork time
generate_blocks(GPOS_HARDFORK_TIME);
generate_block();
// update default gpos global parameters to 4 days
auto now = db.head_block_time();
update_gpos_global(345600, 86400, now);
generate_block();
set_expiration(db, trx);
const auto& core = asset_id_type()(db);
// get core asset object
const auto& dividend_holder_asset_object = get_asset(GRAPHENE_SYMBOL);
// by default core token pays dividends once per month
const auto& dividend_data = dividend_holder_asset_object.dividend_data(db);
BOOST_CHECK_EQUAL(*dividend_data.options.payout_interval, 2592000); // 30 days
// update the payout interval to 1 day for speed purposes of the test
update_payout_interval(core.symbol, db.head_block_time() + fc::minutes(1), 60 * 60 * 24); // 1 day
generate_block();
// get the dividend distribution account
const account_object& dividend_distribution_account = dividend_data.dividend_distribution_account(db);
// transfering some coins to distribution account.
transfer( committee_account, dividend_distribution_account.id, core.amount( 100 ) );
generate_block();
ACTORS((nathan)(voter1)(voter2)(voter3));
transfer( committee_account, nathan_id, core.amount( 1000 ) );
transfer( committee_account, voter1_id, core.amount( 1000 ) );
transfer( committee_account, voter2_id, core.amount( 1000 ) );
generate_block();
upgrade_to_lifetime_member(nathan_id);
auto worker = create_worker(nathan_id, 10, fc::days(6));
// add some vesting to voter1
create_vesting(voter1_id, core.amount(100), vesting_balance_type::gpos);
// add some vesting to voter2
create_vesting(voter2_id, core.amount(100), vesting_balance_type::gpos);
generate_block();
// vote for worker
vote_for(voter1_id, worker.vote_for, voter1_private_key);
// first maint pass, coefficient will be 1
generate_blocks(GPOS_HARDFORK_TIME + fc::hours(12)); //forward 1/2 sub-period so that it consider only gpos votes
worker = worker_id_type()(db);
BOOST_CHECK_EQUAL(worker.total_votes_for, 100);
// here dividends are paid to voter1 and voter2
// voter1 get paid full dividend share as coefficent is at 1 here
BOOST_CHECK_EQUAL(get_balance(voter1_id(db), core), 950);
// voter2 didnt voted so he dont get paid
BOOST_CHECK_EQUAL(get_balance(voter2_id(db), core), 900);
// send some asset to the reserve pool so the worker can get paid
fill_reserve_pool(account_id_type(), asset(GRAPHENE_MAX_SHARE_SUPPLY/2));
BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 0);
BOOST_CHECK_EQUAL(worker.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 0);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// worker is getting paid
BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 5);
BOOST_CHECK_EQUAL(worker.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 5);
// second maint pass, coefficient will be 0.75
worker = worker_id_type()(db);
BOOST_CHECK_EQUAL(worker.total_votes_for, 75);
// more decay
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
worker = worker_id_type()(db);
BOOST_CHECK_EQUAL(worker.total_votes_for, 50);
transfer( committee_account, dividend_distribution_account.id, core.amount( 100 ) );
generate_block();
BOOST_CHECK_EQUAL(get_balance(committee_account(db), core), 499999999996850);
// more decay
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
worker = worker_id_type()(db);
BOOST_CHECK_EQUAL(worker.total_votes_for, 25);
// here voter1 get paid again but less money by vesting coefficient
BOOST_CHECK_EQUAL(get_balance(voter1_id(db), core), 962);
BOOST_CHECK_EQUAL(get_balance(voter2_id(db), core), 900);
// remaining dividends not paid by coeffcient are sent to committee account
BOOST_CHECK_EQUAL(get_balance(committee_account(db), core), 499999999996938);
}
catch (fc::exception &e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( account_multiple_vesting )
{
try {
// advance to HF
fc::time_point_sec GPOS_HARDFORK_TIME =
fc::time_point_sec(1581976800); // Use mainnet GPOS hardfork time
generate_blocks(GPOS_HARDFORK_TIME);
generate_block();
set_expiration(db, trx);
// update default gpos global parameters to 4 days
auto now = db.head_block_time();
update_gpos_global(345600, 86400, now);
ACTORS((sam)(patty));
const auto& core = asset_id_type()(db);
transfer( committee_account, sam_id, core.amount( 300 ) );
transfer( committee_account, patty_id, core.amount( 100 ) );
// add some vesting to sam
create_vesting(sam_id, core.amount(100), vesting_balance_type::gpos);
// have another balance with 200 more
create_vesting(sam_id, core.amount(200), vesting_balance_type::gpos);
// patty also have vesting balance
create_vesting(patty_id, core.amount(100), vesting_balance_type::gpos);
// get core asset object
const auto& dividend_holder_asset_object = get_asset(GRAPHENE_SYMBOL);
const auto& dividend_data = dividend_holder_asset_object.dividend_data(db);
// update the payout interval
update_payout_interval(core.symbol, db.head_block_time() + fc::minutes(1), 60 * 60 * 24); // 1 day
// get the dividend distribution account
const account_object& dividend_distribution_account = dividend_data.dividend_distribution_account(db);
// transfering some coins to distribution account.
transfer( committee_account, dividend_distribution_account.id, core.amount( 100 ) );
generate_block();
// vote for a votable object
auto witness1 = witness_id_type(1)(db);
vote_for(sam_id, witness1.vote_id, sam_private_key);
vote_for(patty_id, witness1.vote_id, patty_private_key);
generate_blocks(GPOS_HARDFORK_TIME + fc::hours(12)); //forward 1/2 sub-period so that it consider only gpos votes
// amount in vested balanced will sum up as voting power
witness1 = witness_id_type(1)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 400);
// sam get paid dividends
BOOST_CHECK_EQUAL(get_balance(sam_id(db), core), 75);
// patty also
BOOST_CHECK_EQUAL(get_balance(patty_id(db), core), 25);
// total vote not decaying
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
witness1 = witness_id_type(1)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 300);
}
catch (fc::exception &e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( Withdraw_gpos_vesting_balance )
{
try {
// advance to HF
generate_blocks(HARDFORK_GPOS_TIME);
generate_block();
set_expiration(db, trx);
// update default gpos global parameters to 4 days
auto now = db.head_block_time();
update_gpos_global(345600, 86400, now);
ACTORS((alice)(bob));
graphene::app::database_api db_api1(db);
const auto& core = asset_id_type()(db);
transfer( committee_account, alice_id, core.amount( 500 ) );
transfer( committee_account, bob_id, core.amount( 99 ) );
// add some vesting to Alice, Bob
vesting_balance_object vbo1, vbo2;
vbo1 = create_vesting(alice_id, core.amount(150), vesting_balance_type::gpos);
vbo2 = create_vesting(bob_id, core.amount(99), vesting_balance_type::gpos);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_blocks(db.get_global_properties().parameters.gpos_vesting_lockin_period());
BOOST_CHECK_EQUAL(get_balance(alice_id(db), core), 350);
withdraw_gpos_vesting(vbo1.id, alice_id, core.amount(50), /*vesting_balance_type::gpos, */alice_private_key);
withdraw_gpos_vesting(vbo2.id, bob_id, core.amount(99), /*vesting_balance_type::gpos, */bob_private_key);
generate_block();
// verify charles balance
BOOST_CHECK_EQUAL(get_balance(alice_id(db), core), 400);
BOOST_CHECK_EQUAL(get_balance(bob_id(db), core), 99);
// Add more 50 and 73 vesting objects and withdraw 90 from
// total vesting balance of user
vbo1 = create_vesting(alice_id, core.amount(50), vesting_balance_type::gpos);
vbo2 = create_vesting(alice_id, core.amount(73), vesting_balance_type::gpos);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
vector<vesting_balance_object> vbos = db_api1.get_vesting_balances("alice");
asset total_vesting;
for (const vesting_balance_object& vbo : vbos)
{
if (vbo.balance_type == vesting_balance_type::gpos && vbo.balance.asset_id == asset_id_type())
total_vesting += vbo.balance;
}
// total vesting balance of alice
BOOST_CHECK_EQUAL(total_vesting.amount.value, core.amount(223).amount.value);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_blocks(db.get_global_properties().parameters.gpos_vesting_lockin_period());
BOOST_CHECK_EQUAL(get_balance(alice_id(db), core), 277);
withdraw_gpos_vesting(vbo1.id, alice_id, core.amount(90), /*vesting_balance_type::gpos,*/ alice_private_key);
generate_block();
// verify alice balance
BOOST_CHECK_EQUAL(get_balance(alice_id(db), core), 367);
// verify remaining vesting balance
vbos = db_api1.get_vesting_balances("alice");
asset remaining_vesting;
for (const vesting_balance_object& vbo : vbos)
{
if (vbo.balance_type == vesting_balance_type::gpos && vbo.balance.asset_id == asset_id_type())
remaining_vesting += vbo.balance;
}
// remaining vesting balance of alice
BOOST_CHECK_EQUAL(remaining_vesting.amount.value, core.amount(133).amount.value);
}
catch (fc::exception &e) {
edump((e.to_detail_string()));
throw;
}
}
/*
BOOST_AUTO_TEST_CASE( competing_proposals )
{
try {
// advance to HF
generate_blocks(HARDFORK_GPOS_TIME);
generate_block();
set_expiration(db, trx);
ACTORS((voter1)(voter2)(worker1)(worker2));
const auto& core = asset_id_type()(db);
transfer( committee_account, worker1_id, core.amount( 1000 ) );
transfer( committee_account, worker2_id, core.amount( 1000 ) );
transfer( committee_account, voter1_id, core.amount( 1000 ) );
transfer( committee_account, voter2_id, core.amount( 1000 ) );
create_vesting(voter1_id, core.amount(200), vesting_balance_type::gpos);
create_vesting(voter2_id, core.amount(300), vesting_balance_type::gpos);
generate_block();
auto now = db.head_block_time();
update_gpos_global(518400, 86400, now);
update_payout_interval(core.symbol, fc::time_point::now() + fc::minutes(1), 60 * 60 * 24); // 1 day
upgrade_to_lifetime_member(worker1_id);
upgrade_to_lifetime_member(worker2_id);
// create 2 competing proposals asking a lot of token
// todo: maybe a refund worker here so we can test with smaller numbers
auto w1 = create_worker(worker1_id, 100000000000, fc::days(10));
auto w1_id_instance = w1.id.instance();
auto w2 = create_worker(worker2_id, 100000000000, fc::days(10));
auto w2_id_instance = w2.id.instance();
fill_reserve_pool(account_id_type(), asset(GRAPHENE_MAX_SHARE_SUPPLY/2));
// vote for the 2 workers
vote_for(voter1_id, w1.vote_for, voter1_private_key);
vote_for(voter2_id, w2.vote_for, voter2_private_key);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
w1 = worker_id_type(w1_id_instance)(db);
w2 = worker_id_type(w2_id_instance)(db);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
// only w2 is getting paid as it haves more votes and money is only enough for 1
BOOST_CHECK_EQUAL(w1.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 0);
BOOST_CHECK_EQUAL(w2.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 100000000000);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
BOOST_CHECK_EQUAL(w1.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 0);
BOOST_CHECK_EQUAL(w2.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 150000000000);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
w1 = worker_id_type(w1_id_instance)(db);
w2 = worker_id_type(w2_id_instance)(db);
// as votes decay w1 is still getting paid as it always have more votes than w1
BOOST_CHECK_EQUAL(w1.total_votes_for, 100);
BOOST_CHECK_EQUAL(w2.total_votes_for, 150);
BOOST_CHECK_EQUAL(w1.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 0);
BOOST_CHECK_EQUAL(w2.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 200000000000);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
w1 = worker_id_type(w1_id_instance)(db);
w2 = worker_id_type(w2_id_instance)(db);
BOOST_CHECK_EQUAL(w1.total_votes_for, 66);
BOOST_CHECK_EQUAL(w2.total_votes_for, 100);
// worker is sil getting paid as days pass
BOOST_CHECK_EQUAL(w1.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 0);
BOOST_CHECK_EQUAL(w2.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 250000000000);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
w1 = worker_id_type(w1_id_instance)(db);
w2 = worker_id_type(w2_id_instance)(db);
BOOST_CHECK_EQUAL(w1.total_votes_for, 33);
BOOST_CHECK_EQUAL(w2.total_votes_for, 50);
BOOST_CHECK_EQUAL(w1.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 0);
BOOST_CHECK_EQUAL(w2.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 300000000000);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
w1 = worker_id_type(w1_id_instance)(db);
w2 = worker_id_type(w2_id_instance)(db);
// worker2 will not get paid anymore as it haves 0 votes
BOOST_CHECK_EQUAL(w1.total_votes_for, 0);
BOOST_CHECK_EQUAL(w2.total_votes_for, 0);
BOOST_CHECK_EQUAL(w1.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 0);
BOOST_CHECK_EQUAL(w2.worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 300000000000);
}
catch (fc::exception &e) {
edump((e.to_detail_string()));
throw;
}
}
*/
BOOST_AUTO_TEST_CASE( proxy_voting )
{
ACTORS((alice)(bob));
try {
// move to hardfork
generate_blocks( HARDFORK_GPOS_TIME );
generate_block();
// database api
graphene::app::database_api db_api(db);
const auto& core = asset_id_type()(db);
// send some asset to alice and bob
transfer( committee_account, alice_id, core.amount( 1000 ) );
transfer( committee_account, bob_id, core.amount( 1000 ) );
generate_block();
// add some vesting to alice and bob
create_vesting(alice_id, core.amount(100), vesting_balance_type::gpos);
generate_block();
// total balance is 100 rest of data at 0
auto gpos_info = db_api.get_gpos_info(alice_id);
BOOST_CHECK_EQUAL(gpos_info.vesting_factor, 0);
BOOST_CHECK_EQUAL(gpos_info.award.amount.value, 0);
BOOST_CHECK_EQUAL(gpos_info.total_amount.value, 100);
create_vesting(bob_id, core.amount(100), vesting_balance_type::gpos);
generate_block();
gpos_info = db_api.get_gpos_info(bob_id);
BOOST_CHECK_EQUAL(gpos_info.vesting_factor, 0);
BOOST_CHECK_EQUAL(gpos_info.award.amount.value, 0);
BOOST_CHECK_EQUAL(gpos_info.total_amount.value, 200);
auto now = db.head_block_time();
update_gpos_global(518400, 86400, now);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period(), 518400);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_subperiod(), 86400);
BOOST_CHECK_EQUAL(db.get_global_properties().parameters.gpos_period_start(), now.sec_since_epoch());
// alice assign bob as voting account
graphene::chain::account_update_operation op;
op.account = alice_id;
op.new_options = alice_id(db).options;
op.new_options->voting_account = bob_id;
trx.operations.push_back(op);
set_expiration(db, trx);
trx.validate();
sign(trx, alice_private_key);
PUSH_TX( db, trx, ~0 );
trx.clear();
generate_block();
// vote for witness1
auto witness1 = witness_id_type(1)(db);
vote_for(bob_id, witness1.vote_id, bob_private_key);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// check vesting factor of current subperiod
BOOST_CHECK_EQUAL(db_api.get_gpos_info(alice_id).vesting_factor, 1);
BOOST_CHECK_EQUAL(db_api.get_gpos_info(bob_id).vesting_factor, 1);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
// GPOS 2nd subperiod started.
// vesting factor decay
BOOST_CHECK_EQUAL(db_api.get_gpos_info(alice_id).vesting_factor, 0.83333333333333337);
BOOST_CHECK_EQUAL(db_api.get_gpos_info(bob_id).vesting_factor, 0.83333333333333337);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
// GPOS 3rd subperiod started
// vesting factor decay
BOOST_CHECK_EQUAL(db_api.get_gpos_info(alice_id).vesting_factor, 0.66666666666666663);
BOOST_CHECK_EQUAL(db_api.get_gpos_info(bob_id).vesting_factor, 0.66666666666666663);
// vote for witness2
auto witness2 = witness_id_type(2)(db);
vote_for(bob_id, witness2.vote_id, bob_private_key);
// vesting factor should be 1 for both alice and bob for the current subperiod
BOOST_CHECK_EQUAL(db_api.get_gpos_info(alice_id).vesting_factor, 1);
BOOST_CHECK_EQUAL(db_api.get_gpos_info(bob_id).vesting_factor, 1);
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
generate_block();
// vesting factor decay
BOOST_CHECK_EQUAL(db_api.get_gpos_info(alice_id).vesting_factor, 0.83333333333333337);
BOOST_CHECK_EQUAL(db_api.get_gpos_info(bob_id).vesting_factor, 0.83333333333333337);
}
catch (fc::exception &e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( no_proposal )
{
try {
}
catch (fc::exception &e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_CASE( database_api )
{
ACTORS((alice)(bob));
try {
// move to hardfork
generate_blocks( HARDFORK_GPOS_TIME );
generate_block();
// database api
graphene::app::database_api db_api(db);
const auto& core = asset_id_type()(db);
// send some asset to alice and bob
transfer( committee_account, alice_id, core.amount( 1000 ) );
transfer( committee_account, bob_id, core.amount( 1000 ) );
generate_block();
// add some vesting to alice and bob
create_vesting(alice_id, core.amount(100), vesting_balance_type::gpos);
generate_block();
// total balance is 100 rest of data at 0
auto gpos_info = db_api.get_gpos_info(alice_id);
BOOST_CHECK_EQUAL(gpos_info.vesting_factor, 0);
BOOST_CHECK_EQUAL(gpos_info.award.amount.value, 0);
BOOST_CHECK_EQUAL(gpos_info.total_amount.value, 100);
create_vesting(bob_id, core.amount(100), vesting_balance_type::gpos);
generate_block();
// total gpos balance is now 200
gpos_info = db_api.get_gpos_info(alice_id);
BOOST_CHECK_EQUAL(gpos_info.total_amount.value, 200);
// update default gpos and dividend interval to 10 days
auto now = db.head_block_time();
update_gpos_global(5184000, 864000, now); // 10 days subperiods
update_payout_interval(core.symbol, now + fc::minutes(1), 60 * 60 * 24 * 10); // 10 days
generate_block();
// no votes for witness 1
auto witness1 = witness_id_type(1)(db);
BOOST_CHECK_EQUAL(witness1.total_votes, 0);
// no votes for witness 2
auto witness2 = witness_id_type(2)(db);
BOOST_CHECK_EQUAL(witness2.total_votes, 0);
// transfering some coins to distribution account.
const auto& dividend_holder_asset_object = get_asset(GRAPHENE_SYMBOL);
const auto& dividend_data = dividend_holder_asset_object.dividend_data(db);
const account_object& dividend_distribution_account = dividend_data.dividend_distribution_account(db);
transfer( committee_account, dividend_distribution_account.id, core.amount( 100 ) );
generate_block();
// award balance is now 100
gpos_info = db_api.get_gpos_info(alice_id);
BOOST_CHECK_EQUAL(gpos_info.vesting_factor, 0);
BOOST_CHECK_EQUAL(gpos_info.award.amount.value, 100);
BOOST_CHECK_EQUAL(gpos_info.total_amount.value, 200);
// vote for witness1
vote_for(alice_id, witness1.vote_id, alice_private_key);
vote_for(bob_id, witness1.vote_id, bob_private_key);
// go to maint
generate_blocks(db.get_dynamic_global_properties().next_maintenance_time);
// payment for alice and bob is done, distribution account is back in 0
gpos_info = db_api.get_gpos_info(alice_id);
BOOST_CHECK_EQUAL(gpos_info.vesting_factor, 1);
BOOST_CHECK_EQUAL(gpos_info.award.amount.value, 0);
BOOST_CHECK_EQUAL(gpos_info.total_amount.value, 200);
advance_x_maint(10);
// alice vesting coeffcient decay
gpos_info = db_api.get_gpos_info(alice_id);
BOOST_CHECK_EQUAL(gpos_info.vesting_factor, 0.83333333333333337);
BOOST_CHECK_EQUAL(gpos_info.award.amount.value, 0);
BOOST_CHECK_EQUAL(gpos_info.total_amount.value, 200);
advance_x_maint(10);
// vesting factor for alice decaying more
gpos_info = db_api.get_gpos_info(alice_id);
BOOST_CHECK_EQUAL(gpos_info.vesting_factor, 0.66666666666666663);
BOOST_CHECK_EQUAL(gpos_info.award.amount.value, 0);
BOOST_CHECK_EQUAL(gpos_info.total_amount.value, 200);
}
catch (fc::exception &e) {
edump((e.to_detail_string()));
throw;
}
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device_adapter.h"
#include <lib/sync/completion.h>
#include <lib/syslog/global.h>
#include <zircon/status.h>
#include <fbl/auto_lock.h>
namespace network {
namespace tun {
zx::status<std::unique_ptr<DeviceAdapter>> DeviceAdapter::Create(async_dispatcher_t* dispatcher,
DeviceAdapterParent* parent) {
fbl::AllocChecker ac;
std::unique_ptr<DeviceAdapter> adapter(new (&ac) DeviceAdapter(parent));
if (!ac.check()) {
return zx::error(ZX_ERR_NO_MEMORY);
}
network_device_impl_protocol_t proto = {
.ops = &adapter->network_device_impl_protocol_ops_,
.ctx = adapter.get(),
};
zx::status device = NetworkDeviceInterface::Create(
dispatcher, ddk::NetworkDeviceImplProtocolClient(&proto), "network-tun");
if (device.is_error()) {
return device.take_error();
}
adapter->device_ = std::move(device.value());
return zx::ok(std::move(adapter));
}
zx_status_t DeviceAdapter::Bind(fidl::ServerEnd<netdev::Device> req) {
return device_->Bind(std::move(req));
}
zx_status_t DeviceAdapter::NetworkDeviceImplInit(const network_device_ifc_protocol_t* iface) {
device_iface_ = ddk::NetworkDeviceIfcProtocolClient(iface);
return ZX_OK;
}
void DeviceAdapter::NetworkDeviceImplStart(network_device_impl_start_callback callback,
void* cookie) {
{
fbl::AutoLock lock(&rx_lock_);
rx_available_ = true;
}
{
fbl::AutoLock lock(&tx_lock_);
tx_available_ = true;
}
callback(cookie, ZX_OK);
}
void DeviceAdapter::NetworkDeviceImplStop(network_device_impl_stop_callback callback,
void* cookie) {
{
// Return all rx buffers.
fbl::AutoLock lock(&rx_lock_);
rx_available_ = false;
while (!rx_buffers_.empty()) {
const rx_space_buffer_t& buffer = rx_buffers_.front();
rx_buffer_part_t part = {
.id = buffer.id,
.length = 0,
};
rx_buffer_t return_buffer = {
.data_list = &part,
.data_count = 1,
};
device_iface_.CompleteRx(&return_buffer, 1);
rx_buffers_.pop();
}
}
{
// Return all tx buffers.
fbl::AutoLock lock(&tx_lock_);
tx_available_ = false;
while (!tx_buffers_.empty()) {
const TxBuffer& buffer = tx_buffers_.front();
tx_result_t result = {
.id = buffer.id(),
.status = ZX_ERR_UNAVAILABLE,
};
device_iface_.CompleteTx(&result, 1);
tx_buffers_.pop();
}
}
callback(cookie);
}
void DeviceAdapter::NetworkDeviceImplGetInfo(device_info_t* out_info) { *out_info = device_info_; }
void DeviceAdapter::NetworkDeviceImplQueueTx(const tx_buffer_t* buf_list, size_t buf_count) {
{
fbl::AutoLock tx_lock(&tx_lock_);
fbl::Span buffers(buf_list, buf_count);
if (!tx_available_) {
FX_VLOGF(1, "tun", "Discarding %d tx buffers, tx queue is invalid", tx_available_);
for (const tx_buffer_t& b : buffers) {
EnqueueTx(b.id, ZX_ERR_UNAVAILABLE);
}
CommitTx();
return;
}
for (const tx_buffer_t& b : buffers) {
if (b.meta.port >= port_online_status_.size() || !port_online_status_[b.meta.port]) {
EnqueueTx(b.id, ZX_ERR_UNAVAILABLE);
continue;
}
tx_buffers_.emplace(vmos_.MakeTxBuffer(b, parent_->config().report_metadata));
}
CommitTx();
}
parent_->OnTxAvail(this);
}
void DeviceAdapter::NetworkDeviceImplQueueRxSpace(const rx_space_buffer_t* buf_list,
size_t buf_count) {
bool has_buffers;
{
fbl::AutoLock lock(&rx_lock_);
fbl::Span buffers(buf_list, buf_count);
if (!rx_available_) {
for (const rx_space_buffer_t& space : buffers) {
rx_buffer_part_t part = {
.id = space.id,
.length = 0,
};
rx_buffer_t buffer = {
.data_list = &part,
.data_count = 1,
};
device_iface_.CompleteRx(&buffer, 1);
}
return;
}
for (const rx_space_buffer_t& space : buffers) {
rx_buffers_.push(space);
}
has_buffers = !rx_buffers_.empty();
}
if (has_buffers) {
parent_->OnRxAvail(this);
}
}
void DeviceAdapter::NetworkDeviceImplPrepareVmo(uint8_t vmo_id, zx::vmo vmo) {
zx_status_t status = vmos_.RegisterVmo(vmo_id, std::move(vmo));
if (status != ZX_OK) {
FX_LOGF(ERROR, "tun", "DeviceAdapter failed to register vmo: %s", zx_status_get_string(status));
}
}
void DeviceAdapter::NetworkDeviceImplReleaseVmo(uint8_t vmo_id) {
zx_status_t status = vmos_.UnregisterVmo(vmo_id);
if (status != ZX_OK) {
FX_LOGF(ERROR, "tun", "DeviceAdapter failed to unregister vmo: %s",
zx_status_get_string(status));
}
}
bool DeviceAdapter::TryGetTxBuffer(fit::callback<zx_status_t(TxBuffer&, size_t)> callback) {
uint32_t id;
fbl::AutoLock lock(&tx_lock_);
if (tx_buffers_.empty()) {
return false;
}
auto& buff = tx_buffers_.front();
auto avail = tx_buffers_.size() - 1;
zx_status_t status = callback(buff, avail);
id = buff.id();
tx_buffers_.pop();
EnqueueTx(id, status);
CommitTx();
return true;
}
void DeviceAdapter::RetainTxBuffers(fit::function<zx_status_t(TxBuffer&)> func) {
fbl::AutoLock lock(&tx_lock_);
for (size_t size = tx_buffers_.size(); size > 0; size--) {
TxBuffer& buffer = tx_buffers_.front();
zx_status_t status = func(buffer);
if (status == ZX_OK) {
tx_buffers_.push(std::move(buffer));
} else {
EnqueueTx(buffer.id(), status);
}
tx_buffers_.pop();
}
CommitTx();
}
zx::status<size_t> DeviceAdapter::WriteRxFrame(
PortAdapter& port, fuchsia_hardware_network::wire::FrameType frame_type, const uint8_t* data,
size_t count, const std::optional<fuchsia_net_tun::wire::FrameMetadata>& meta) {
if (!port.online()) {
return zx::error(ZX_ERR_BAD_STATE);
}
if (count > port.mtu()) {
return zx::error(ZX_ERR_INVALID_ARGS);
}
fbl::AutoLock lock(&rx_lock_);
if (rx_buffers_.empty()) {
return zx::error(ZX_ERR_SHOULD_WAIT);
}
zx::status alloc = AllocRxSpace(count);
if (alloc.is_error()) {
return alloc.take_error();
}
RxBuffer buffer = std::move(alloc.value());
if (zx_status_t status = buffer.Write(data, count); status != ZX_OK) {
ReclaimRxSpace(std::move(buffer));
return zx::error(status);
}
EnqueueRx(port.id(), frame_type, std::move(buffer), count, meta);
CommitRx();
return zx::ok(rx_buffers_.size());
}
zx::status<size_t> DeviceAdapter::WriteRxFrame(
PortAdapter& port, fuchsia_hardware_network::wire::FrameType frame_type,
const fidl::VectorView<uint8_t>& data,
const std::optional<fuchsia_net_tun::wire::FrameMetadata>& meta) {
return WriteRxFrame(port, frame_type, data.data(), data.count(), meta);
}
zx::status<size_t> DeviceAdapter::WriteRxFrame(
PortAdapter& port, fuchsia_hardware_network::wire::FrameType frame_type,
const std::vector<uint8_t>& data,
const std::optional<fuchsia_net_tun::wire::FrameMetadata>& meta) {
return WriteRxFrame(port, frame_type, data.data(), data.size(), meta);
}
void DeviceAdapter::CopyTo(DeviceAdapter* other, bool return_failed_buffers) {
fbl::AutoLock tx_lock(&tx_lock_);
fbl::AutoLock rx_lock(&other->rx_lock_);
while (!tx_buffers_.empty()) {
TxBuffer& tx_buff = tx_buffers_.front();
zx::status alloc_rx = other->AllocRxSpace(tx_buff.length());
if (alloc_rx.is_error()) {
if (!return_failed_buffers) {
// stop once we run out of rx buffers to copy to
FX_VLOG(1, "tun", "DeviceAdapter:CopyTo: no more rx buffers");
break;
}
EnqueueTx(tx_buff.id(), ZX_ERR_NO_RESOURCES);
tx_buffers_.pop();
continue;
}
RxBuffer rx_buff = std::move(alloc_rx.value());
zx::status status = rx_buff.CopyFrom(tx_buff);
if (status.is_error()) {
FX_LOGF(ERROR, "tun", "DeviceAdapter:CopyTo: Failed to copy buffer: %s",
status.status_string());
EnqueueTx(tx_buff.id(), status.status_value());
other->ReclaimRxSpace(std::move(rx_buff));
} else {
size_t length = status.value();
// Enqueue the data to be returned in other, and enqueue the complete tx in self.
std::optional meta = tx_buff.TakeMetadata();
if (meta.has_value()) {
meta->flags = 0;
}
other->EnqueueRx(tx_buff.port_id(), tx_buff.frame_type(), std::move(rx_buff), length, meta);
EnqueueTx(tx_buff.id(), ZX_OK);
}
tx_buffers_.pop();
}
CommitTx();
other->CommitRx();
}
void DeviceAdapter::Teardown(fit::function<void()> callback) {
device_->Teardown([cb = std::move(callback)]() mutable { cb(); });
}
void DeviceAdapter::TeardownSync() {
sync_completion_t completion;
Teardown([&completion]() { sync_completion_signal(&completion); });
sync_completion_wait_deadline(&completion, ZX_TIME_INFINITE);
}
void DeviceAdapter::EnqueueRx(uint8_t port_id, fuchsia_hardware_network::wire::FrameType frame_type,
RxBuffer buffer, size_t length,
const std::optional<fuchsia_net_tun::wire::FrameMetadata>& meta)
__TA_REQUIRES(rx_lock_) {
// Written length must always fit the buffer.
ZX_DEBUG_ASSERT(buffer.length() >= length);
size_t old_rx_parts_count = return_rx_parts_count_;
buffer.WithReturn(length, [this](const rx_buffer_part_t& part) {
// WithReturn is called inline.
[]() __TA_ASSERT(rx_lock_) {}();
// We should not be producing zero-length parts.
ZX_DEBUG_ASSERT(part.length != 0);
// Can't accumulate more parts than can fit in our array.
ZX_ASSERT(return_rx_parts_count_ <= return_rx_parts_.size());
return_rx_parts_[return_rx_parts_count_++] = part;
});
rx_buffer_t& ret = return_rx_list_.emplace_back(rx_buffer_t{
.meta =
{
.port = port_id,
.info_type = static_cast<uint32_t>(fuchsia_hardware_network::wire::InfoType::kNoInfo),
.frame_type = static_cast<uint8_t>(frame_type),
},
.data_list = &return_rx_parts_[old_rx_parts_count],
.data_count = return_rx_parts_count_ - old_rx_parts_count,
});
if (meta) {
ret.meta.flags = meta->flags;
ret.meta.info_type = static_cast<uint32_t>(meta->info_type);
if (meta->info_type != fuchsia_hardware_network::wire::InfoType::kNoInfo) {
FX_LOGF(WARNING, "tun", "Unrecognized info type %d", ret.meta.info_type);
}
}
}
void DeviceAdapter::CommitRx() {
if (!return_rx_list_.empty()) {
device_iface_.CompleteRx(return_rx_list_.data(), return_rx_list_.size());
return_rx_list_.clear();
return_rx_parts_count_ = 0;
}
}
void DeviceAdapter::EnqueueTx(uint32_t id, zx_status_t status) {
auto& tx = return_tx_list_.emplace_back();
tx.id = id;
tx.status = status;
}
void DeviceAdapter::CommitTx() {
if (!return_tx_list_.empty()) {
device_iface_.CompleteTx(return_tx_list_.data(), return_tx_list_.size());
return_tx_list_.clear();
}
}
DeviceAdapter::DeviceAdapter(DeviceAdapterParent* parent)
: ddk::NetworkDeviceImplProtocol<DeviceAdapter>(),
parent_(parent),
device_info_(device_info_t{
.tx_depth = kFifoDepth,
.rx_depth = kFifoDepth,
.rx_threshold = kFifoDepth / 2,
.max_buffer_length = fuchsia_net_tun::wire::kMaxMtu,
.buffer_alignment = 1,
.min_rx_buffer_length = parent->config().min_rx_buffer_length,
.min_tx_buffer_length = parent->config().min_tx_buffer_length,
}) {
for (std::atomic_bool& p : port_online_status_) {
p = false;
}
}
zx::status<RxBuffer> DeviceAdapter::AllocRxSpace(size_t length) __TA_REQUIRES(rx_lock_) {
RxBuffer buffer = vmos_.MakeEmptyRxBuffer();
while (!rx_buffers_.empty()) {
const rx_space_buffer_t& space = rx_buffers_.front();
buffer.PushRxSpace(space);
uint32_t space_length = space.region.length;
rx_buffers_.pop();
if (space_length >= length) {
return zx::ok(std::move(buffer));
}
length -= space_length;
}
// Ran out of rx buffers and didn't find what we wanted, need to reclaim the space from buffer.
ReclaimRxSpace(std::move(buffer));
return zx::error(ZX_ERR_SHOULD_WAIT);
}
void DeviceAdapter::ReclaimRxSpace(RxBuffer buffer) __TA_REQUIRES(rx_lock_) {
buffer.WithSpace([this](const rx_space_buffer_t& space) {
// WithSpace is called inline.
[]() __TA_ASSERT(rx_lock_) {}();
rx_buffers_.push(space);
});
}
void DeviceAdapter::OnPortStatusChanged(uint8_t port_id, const port_status_t& new_status) {
port_online_status_[port_id] =
static_cast<bool>(static_cast<netdev::wire::StatusFlags>(new_status.flags) &
netdev::wire::StatusFlags::kOnline);
device_iface_.PortStatusChanged(port_id, &new_status);
}
void DeviceAdapter::AddPort(PortAdapter& port) {
network_port_protocol_t proto = port.proto();
device_iface_.AddPort(port.id(), proto.ctx, proto.ops);
}
void DeviceAdapter::RemovePort(uint8_t port_id) { device_iface_.RemovePort(port_id); }
} // namespace tun
} // namespace network
|
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QVariantMap>
#include <QDebug>
#include "OAIHelpers.h"
#include "OAIUserApiRequest.h"
namespace OpenAPI {
OAIUserApiRequest::OAIUserApiRequest(QHttpEngine::Socket *s, OAIUserApiHandler* hdl) : QObject(s), socket(s), handler(hdl) {
auto headers = s->headers();
for(auto itr = headers.begin(); itr != headers.end(); itr++) {
requestHeaders.insert(QString(itr.key()), QString(itr.value()));
}
}
OAIUserApiRequest::~OAIUserApiRequest(){
disconnect(this, nullptr, nullptr, nullptr);
qDebug() << "OAIUserApiRequest::~OAIUserApiRequest()";
}
QMap<QString, QString>
OAIUserApiRequest::getRequestHeaders() const {
return requestHeaders;
}
void OAIUserApiRequest::setResponseHeaders(const QMultiMap<QString, QString>& headers){
for(auto itr = headers.begin(); itr != headers.end(); ++itr) {
responseHeaders.insert(itr.key(), itr.value());
}
}
QHttpEngine::Socket* OAIUserApiRequest::getRawSocket(){
return socket;
}
void OAIUserApiRequest::createUserRequest(){
qDebug() << "/v2/user";
connect(this, &OAIUserApiRequest::createUser, handler, &OAIUserApiHandler::createUser);
QJsonDocument doc;
socket->readJson(doc);
QJsonObject obj = doc.object();
OAIUser oai_user;
::OpenAPI::fromJsonValue(oai_user, obj);
emit createUser(oai_user);
}
void OAIUserApiRequest::createUsersWithArrayInputRequest(){
qDebug() << "/v2/user/createWithArray";
connect(this, &OAIUserApiRequest::createUsersWithArrayInput, handler, &OAIUserApiHandler::createUsersWithArrayInput);
QJsonDocument doc;
QList<OAIUser> oai_user;
if(socket->readJson(doc)){
QJsonArray jsonArray = doc.array();
foreach(QJsonValue obj, jsonArray) {
OAIUser o;
::OpenAPI::fromJsonValue(o, obj);
oai_user.append(o);
}
}
emit createUsersWithArrayInput(oai_user);
}
void OAIUserApiRequest::createUsersWithListInputRequest(){
qDebug() << "/v2/user/createWithList";
connect(this, &OAIUserApiRequest::createUsersWithListInput, handler, &OAIUserApiHandler::createUsersWithListInput);
QJsonDocument doc;
QList<OAIUser> oai_user;
if(socket->readJson(doc)){
QJsonArray jsonArray = doc.array();
foreach(QJsonValue obj, jsonArray) {
OAIUser o;
::OpenAPI::fromJsonValue(o, obj);
oai_user.append(o);
}
}
emit createUsersWithListInput(oai_user);
}
void OAIUserApiRequest::deleteUserRequest(const QString& usernamestr){
qDebug() << "/v2/user/{username}";
connect(this, &OAIUserApiRequest::deleteUser, handler, &OAIUserApiHandler::deleteUser);
QString username;
fromStringValue(usernamestr, username);
emit deleteUser(username);
}
void OAIUserApiRequest::getUserByNameRequest(const QString& usernamestr){
qDebug() << "/v2/user/{username}";
connect(this, &OAIUserApiRequest::getUserByName, handler, &OAIUserApiHandler::getUserByName);
QString username;
fromStringValue(usernamestr, username);
emit getUserByName(username);
}
void OAIUserApiRequest::loginUserRequest(){
qDebug() << "/v2/user/login";
connect(this, &OAIUserApiRequest::loginUser, handler, &OAIUserApiHandler::loginUser);
QString username;
if(socket->queryString().keys().contains("username")){
fromStringValue(socket->queryString().value("username"), username);
}
QString password;
if(socket->queryString().keys().contains("password")){
fromStringValue(socket->queryString().value("password"), password);
}
emit loginUser(username, password);
}
void OAIUserApiRequest::logoutUserRequest(){
qDebug() << "/v2/user/logout";
connect(this, &OAIUserApiRequest::logoutUser, handler, &OAIUserApiHandler::logoutUser);
emit logoutUser();
}
void OAIUserApiRequest::updateUserRequest(const QString& usernamestr){
qDebug() << "/v2/user/{username}";
connect(this, &OAIUserApiRequest::updateUser, handler, &OAIUserApiHandler::updateUser);
QString username;
fromStringValue(usernamestr, username);
QJsonDocument doc;
socket->readJson(doc);
QJsonObject obj = doc.object();
OAIUser oai_user;
::OpenAPI::fromJsonValue(oai_user, obj);
emit updateUser(username, oai_user);
}
void OAIUserApiRequest::createUserResponse(){
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::createUsersWithArrayInputResponse(){
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::createUsersWithListInputResponse(){
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::deleteUserResponse(){
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::getUserByNameResponse(const OAIUser& res){
writeResponseHeaders();
QJsonDocument resDoc(::OpenAPI::toJsonValue(res).toObject());
socket->writeJson(resDoc);
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::loginUserResponse(const QString& res){
writeResponseHeaders();
socket->write(::OpenAPI::toStringValue(res).toUtf8());
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::logoutUserResponse(){
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::updateUserResponse(){
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::OK);
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::createUserError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::createUsersWithArrayInputError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::createUsersWithListInputError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::deleteUserError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::getUserByNameError(const OAIUser& res, QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
Q_UNUSED(error_str); // response will be used instead of error string
QJsonDocument resDoc(::OpenAPI::toJsonValue(res).toObject());
socket->writeJson(resDoc);
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::loginUserError(const QString& res, QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
Q_UNUSED(error_str); // response will be used instead of error string
socket->write(::OpenAPI::toStringValue(res).toUtf8());
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::logoutUserError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::updateUserError(QNetworkReply::NetworkError error_type, QString& error_str){
Q_UNUSED(error_type); // TODO: Remap error_type to QHttpEngine::Socket errors
writeResponseHeaders();
socket->setStatusCode(QHttpEngine::Socket::NotFound);
socket->write(error_str.toUtf8());
if(socket->isOpen()){
socket->close();
}
}
void OAIUserApiRequest::sendCustomResponse(QByteArray & res, QNetworkReply::NetworkError error_type){
Q_UNUSED(res); // TODO
Q_UNUSED(error_type); // TODO
}
void OAIUserApiRequest::sendCustomResponse(QIODevice *res, QNetworkReply::NetworkError error_type){
Q_UNUSED(res); // TODO
Q_UNUSED(error_type); // TODO
}
}
|
#pragma once
#include "Screen.hh"
#include "stdint.h"
#include "spilcd16bit.hh"
#include "printf/printf.hh"
class CVScreen:public Screen {
public:
CVScreen(SPILCD16bit *lcd);
virtual ~CVScreen();
protected:
void RedrawCompletely() override;
void OnRotaryTurn(uint32_t rotaryKnobFlags, int16_t rotarySteps) override;
void OnTouch(int16_t x, int16_t y) override;
void OnButtonShort(uint32_t buttonFlags) override;
void OnButtonLong(uint32_t buttonFlags) override;
private:
uint32_t VoltageSet=421;
};
|
//
// Copyright (c) 2008-2017 the Urho3D project.
//
// 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 "Text3D.h"
#include "UIBatch.h"
#include "Text.h"
#include "Font.h"
#include "Lutefisk3D/Graphics/Camera.h"
#include "Lutefisk3D/Core/Context.h"
#include "Lutefisk3D/Graphics/Geometry.h"
#include "Lutefisk3D/Graphics/Texture.h"
#include "Lutefisk3D/IO/Log.h"
#include "Lutefisk3D/Graphics/Material.h"
#include "Lutefisk3D/Scene/Node.h"
#include "Lutefisk3D/Resource/ResourceCache.h"
#include "Lutefisk3D/Graphics/Technique.h"
#include "Lutefisk3D/Graphics/VertexBuffer.h"
namespace Urho3D
{
extern const char* horizontalAlignments[];
extern const char* verticalAlignments[];
extern const char* textEffects[];
extern const char* faceCameraModeNames[];
extern const char* GEOMETRY_CATEGORY;
static const float TEXT_SCALING = 1.0f / 128.0f;
static const float DEFAULT_EFFECT_DEPTH_BIAS = 0.1f;
Text3D::Text3D(Context* context) :
Drawable(context, DRAWABLE_GEOMETRY),
text_(context),
vertexBuffer_(new VertexBuffer(context_)),
customWorldTransform_(Matrix3x4::IDENTITY),
faceCameraMode_(FC_NONE),
minAngle_(0.0f),
fixedScreenSize_(false),
textDirty_(true),
geometryDirty_(true),
usingSDFShader_(false),
fontDataLost_(false)
{
text_.SetEffectDepthBias(DEFAULT_EFFECT_DEPTH_BIAS);
}
Text3D::~Text3D()
{
}
void Text3D::RegisterObject(Context* context)
{
context->RegisterFactory<Text3D>(GEOMETRY_CATEGORY);
URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Font", GetFontAttr, SetFontAttr, ResourceRef, {Font::GetTypeStatic()}, AM_DEFAULT);
URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, {Material::GetTypeStatic()}, AM_DEFAULT);
URHO3D_ATTRIBUTE("Font Size", float, text_.fontSize_, DEFAULT_FONT_SIZE, AM_DEFAULT);
URHO3D_ATTRIBUTE("Text", QString, text_.text_, QString(), AM_DEFAULT);
URHO3D_ENUM_ATTRIBUTE("Text Alignment", text_.textAlignment_, horizontalAlignments, HA_LEFT, AM_DEFAULT);
URHO3D_ATTRIBUTE("Row Spacing", float, text_.rowSpacing_, 1.0f, AM_DEFAULT);
URHO3D_ATTRIBUTE("Word Wrap", bool, text_.wordWrap_, false, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Fixed Screen Size", IsFixedScreenSize, SetFixedScreenSize, bool, false, AM_DEFAULT);
URHO3D_ENUM_ATTRIBUTE("Face Camera Mode", faceCameraMode_, faceCameraModeNames, FC_NONE, AM_DEFAULT);
URHO3D_ATTRIBUTE("Min Angle", float, minAngle_, 0.0f, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Width", GetWidth, SetWidth, int, 0, AM_DEFAULT);
URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Horiz Alignment", GetHorizontalAlignment, SetHorizontalAlignment, HorizontalAlignment, horizontalAlignments, HA_LEFT, AM_DEFAULT);
URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Vert Alignment", GetVerticalAlignment, SetVerticalAlignment, VerticalAlignment, verticalAlignments, VA_TOP, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Opacity", GetOpacity, SetOpacity, float, 1.0f, AM_FILE);
URHO3D_ACCESSOR_ATTRIBUTE("Color", GetColorAttr, SetColor, Color, Color::WHITE, AM_DEFAULT);
URHO3D_ATTRIBUTE("Top Left Color", Color, text_.colors_[0], Color::WHITE, AM_DEFAULT);
URHO3D_ATTRIBUTE("Top Right Color", Color, text_.colors_[1], Color::WHITE, AM_DEFAULT);
URHO3D_ATTRIBUTE("Bottom Left Color", Color, text_.colors_[2], Color::WHITE, AM_DEFAULT);
URHO3D_ATTRIBUTE("Bottom Right Color", Color, text_.colors_[3], Color::WHITE, AM_DEFAULT);
URHO3D_ENUM_ATTRIBUTE("Text Effect", text_.textEffect_, textEffects, TE_NONE, AM_DEFAULT);
URHO3D_ATTRIBUTE("Shadow Offset", IntVector2, text_.shadowOffset_, IntVector2(1, 1), AM_DEFAULT);
URHO3D_ATTRIBUTE("Stroke Thickness", int, text_.strokeThickness_, 1, AM_DEFAULT);
URHO3D_ATTRIBUTE("Round Stroke", bool, text_.roundStroke_, false, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Effect Color", GetEffectColor, SetEffectColor, Color, Color::BLACK, AM_DEFAULT);
URHO3D_ATTRIBUTE("Effect Depth Bias", float, text_.effectDepthBias_, DEFAULT_EFFECT_DEPTH_BIAS, AM_DEFAULT);
URHO3D_COPY_BASE_ATTRIBUTES(Drawable);
}
void Text3D::ApplyAttributes()
{
text_.ApplyAttributes();
MarkTextDirty();
UpdateTextBatches();
UpdateTextMaterials();
}
void Text3D::UpdateBatches(const FrameInfo& frame)
{
distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
if (faceCameraMode_ != FC_NONE || fixedScreenSize_)
CalculateFixedScreenSize(frame);
for (SourceBatch &sbatch : batches_)
{
sbatch.distance_ = distance_;
sbatch.worldTransform_ = faceCameraMode_ != FC_NONE ? &customWorldTransform_ : &node_->GetWorldTransform();
}
for (UIBatch &uibatch : uiBatches_)
{
if (uibatch.texture_ && uibatch.texture_->IsDataLost())
{
fontDataLost_ = true;
break;
}
}
}
void Text3D::UpdateGeometry(const FrameInfo& frame)
{
if (fontDataLost_)
{
// Re-evaluation of the text triggers the font face to reload itself
UpdateTextBatches();
UpdateTextMaterials();
fontDataLost_ = false;
}
// In case is being rendered from multiple views, recalculate camera facing & fixed size
if (faceCameraMode_ != FC_NONE || fixedScreenSize_)
CalculateFixedScreenSize(frame);
if (geometryDirty_)
{
for (unsigned i = 0; i < batches_.size() && i < uiBatches_.size(); ++i)
{
Geometry* geometry = geometries_[i];
geometry->SetDrawRange(TRIANGLE_LIST, 0, 0, uiBatches_[i].vertexStart_ / UI_VERTEX_SIZE,
(uiBatches_[i].vertexEnd_ - uiBatches_[i].vertexStart_) / UI_VERTEX_SIZE);
}
}
if ((geometryDirty_ || vertexBuffer_->IsDataLost()) && uiVertexData_.size())
{
unsigned vertexCount = uiVertexData_.size() / UI_VERTEX_SIZE;
if (vertexBuffer_->GetVertexCount() != vertexCount)
vertexBuffer_->SetSize(vertexCount, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1);
vertexBuffer_->SetData(&uiVertexData_[0]);
}
geometryDirty_ = false;
}
UpdateGeometryType Text3D::GetUpdateGeometryType()
{
if (geometryDirty_ || fontDataLost_ || vertexBuffer_->IsDataLost() || faceCameraMode_ != FC_NONE || fixedScreenSize_)
return UPDATE_MAIN_THREAD;
else
return UPDATE_NONE;
}
void Text3D::SetMaterial(Material* material)
{
material_ = material;
UpdateTextMaterials(true);
}
bool Text3D::SetFont(const QString& fontName, float size)
{
bool success = text_.SetFont(fontName, size);
// Changing font requires materials to be re-evaluated. Material evaluation can not be done in worker threads,
// so UI batches must be brought up-to-date immediately
MarkTextDirty();
UpdateTextBatches();
UpdateTextMaterials();
return success;
}
bool Text3D::SetFont(Font* font, float size)
{
bool success = text_.SetFont(font, size);
MarkTextDirty();
UpdateTextBatches();
UpdateTextMaterials();
return success;
}
bool Text3D::SetFontSize(float size)
{
bool success = text_.SetFontSize(size);
MarkTextDirty();
UpdateTextBatches();
UpdateTextMaterials();
return success;
}
void Text3D::SetText(const QString& text)
{
text_.SetText(text);
// Changing text requires materials to be re-evaluated, in case the font is multi-page
MarkTextDirty();
UpdateTextBatches();
UpdateTextMaterials();
}
void Text3D::SetAlignment(HorizontalAlignment hAlign, VerticalAlignment vAlign)
{
text_.SetAlignment(hAlign, vAlign);
MarkTextDirty();
}
void Text3D::SetHorizontalAlignment(HorizontalAlignment align)
{
text_.SetHorizontalAlignment(align);
MarkTextDirty();
}
void Text3D::SetVerticalAlignment(VerticalAlignment align)
{
text_.SetVerticalAlignment(align);
MarkTextDirty();
}
void Text3D::SetTextAlignment(HorizontalAlignment align)
{
text_.SetTextAlignment(align);
MarkTextDirty();
}
void Text3D::SetRowSpacing(float spacing)
{
text_.SetRowSpacing(spacing);
MarkTextDirty();
}
void Text3D::SetWordwrap(bool enable)
{
text_.SetWordwrap(enable);
MarkTextDirty();
}
void Text3D::SetTextEffect(TextEffect textEffect)
{
text_.SetTextEffect(textEffect);
MarkTextDirty();
UpdateTextMaterials(true);
}
void Text3D::SetEffectShadowOffset(const IntVector2& offset)
{
text_.SetEffectShadowOffset(offset);
}
void Text3D::SetEffectStrokeThickness(int thickness)
{
text_.SetEffectStrokeThickness(thickness);
}
void Text3D::SetEffectRoundStroke(bool roundStroke)
{
text_.SetEffectRoundStroke(roundStroke);
}
void Text3D::SetEffectColor(const Color& effectColor)
{
text_.SetEffectColor(effectColor);
MarkTextDirty();
UpdateTextMaterials();
}
void Text3D::SetEffectDepthBias(float bias)
{
text_.SetEffectDepthBias(bias);
MarkTextDirty();
}
void Text3D::SetWidth(int width)
{
text_.SetMinWidth(width);
text_.SetWidth(width);
MarkTextDirty();
}
void Text3D::SetColor(const Color& color)
{
float oldAlpha = text_.GetColor(C_TOPLEFT).a_;
text_.SetColor(color);
MarkTextDirty();
// If alpha changes from zero to nonzero or vice versa, amount of text batches changes (optimization), so do full update
if ((oldAlpha == 0.0f && color.a_ != 0.0f) || (oldAlpha != 0.0f && color.a_ == 0.0f))
{
UpdateTextBatches();
UpdateTextMaterials();
}
}
void Text3D::SetColor(Corner corner, const Color& color)
{
text_.SetColor(corner, color);
MarkTextDirty();
}
void Text3D::SetOpacity(float opacity)
{
float oldOpacity = text_.GetOpacity();
text_.SetOpacity(opacity);
float newOpacity = text_.GetOpacity();
MarkTextDirty();
// If opacity changes from zero to nonzero or vice versa, amount of text batches changes (optimization), so do full update
if ((oldOpacity == 0.0f && newOpacity != 0.0f) || (oldOpacity != 0.0f && newOpacity == 0.0f))
{
UpdateTextBatches();
UpdateTextMaterials();
}
}
void Text3D::SetFixedScreenSize(bool enable)
{
if (enable != fixedScreenSize_)
{
fixedScreenSize_ = enable;
// Bounding box must be recalculated
OnMarkedDirty(node_);
MarkNetworkUpdate();
}
}
void Text3D::SetFaceCameraMode(FaceCameraMode mode)
{
if (mode != faceCameraMode_)
{
faceCameraMode_ = mode;
// Bounding box must be recalculated
OnMarkedDirty(node_);
MarkNetworkUpdate();
}
}
Material* Text3D::GetMaterial() const
{
return material_;
}
Font* Text3D::GetFont() const
{
return text_.GetFont();
}
float Text3D::GetFontSize() const
{
return text_.GetFontSize();
}
const QString& Text3D::GetText() const
{
return text_.GetText();
}
HorizontalAlignment Text3D::GetHorizontalAlignment() const
{
return text_.GetHorizontalAlignment();
}
VerticalAlignment Text3D::GetVerticalAlignment() const
{
return text_.GetVerticalAlignment();
}
HorizontalAlignment Text3D::GetTextAlignment() const
{
return text_.GetTextAlignment();
}
float Text3D::GetRowSpacing() const
{
return text_.GetRowSpacing();
}
bool Text3D::GetWordwrap() const
{
return text_.GetWordwrap();
}
TextEffect Text3D::GetTextEffect() const
{
return text_.GetTextEffect();
}
const IntVector2& Text3D::GetEffectShadowOffset() const
{
return text_.GetEffectShadowOffset();
}
int Text3D::GetEffectStrokeThickness() const
{
return text_.GetEffectStrokeThickness();
}
bool Text3D::GetEffectRoundStroke() const
{
return text_.GetEffectRoundStroke();
}
const Color& Text3D::GetEffectColor() const
{
return text_.GetEffectColor();
}
float Text3D::GetEffectDepthBias() const
{
return text_.GetEffectDepthBias();
}
int Text3D::GetWidth() const
{
return text_.GetWidth();
}
int Text3D::GetHeight() const
{
return text_.GetHeight();
}
int Text3D::GetRowHeight() const
{
return text_.GetRowHeight();
}
unsigned Text3D::GetNumRows() const
{
return text_.GetNumRows();
}
unsigned Text3D::GetNumChars() const
{
return text_.GetNumChars();
}
int Text3D::GetRowWidth(unsigned index) const
{
return text_.GetRowWidth(index);
}
Vector2 Text3D::GetCharPosition(unsigned index)
{
return text_.GetCharPosition(index);
}
Vector2 Text3D::GetCharSize(unsigned index)
{
return text_.GetCharSize(index);
}
const Color& Text3D::GetColor(Corner corner) const
{
return text_.GetColor(corner);
}
float Text3D::GetOpacity() const
{
return text_.GetOpacity();
}
void Text3D::OnNodeSet(Node* node)
{
Drawable::OnNodeSet(node);
if (node)
customWorldTransform_ = node->GetWorldTransform();
}
void Text3D::OnWorldBoundingBoxUpdate()
{
if (textDirty_)
UpdateTextBatches();
// In face camera mode, use the last camera rotation to build the world bounding box
if (faceCameraMode_ != FC_NONE || fixedScreenSize_)
{
worldBoundingBox_ = boundingBox_.Transformed(Matrix3x4(node_->GetWorldPosition(),
customWorldTransform_.Rotation(), customWorldTransform_.Scale()));
}
else
worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
}
void Text3D::MarkTextDirty()
{
textDirty_ = true;
OnMarkedDirty(node_);
MarkNetworkUpdate();
}
void Text3D::SetMaterialAttr(const ResourceRef& value)
{
SetMaterial(context_->m_ResourceCache->GetResource<Material>(value.name_));
}
void Text3D::SetFontAttr(const ResourceRef& value)
{
text_.font_ = context_->m_ResourceCache->GetResource<Font>(value.name_);
}
void Text3D::SetTextAttr(const QString& value)
{
text_.SetTextAttr(value);
}
QString Text3D::GetTextAttr() const
{
return text_.GetTextAttr();
}
ResourceRef Text3D::GetMaterialAttr() const
{
return GetResourceRef(material_, Material::GetTypeStatic());
}
ResourceRef Text3D::GetFontAttr() const
{
return GetResourceRef(text_.font_, Font::GetTypeStatic());
}
void Text3D::UpdateTextBatches()
{
uiBatches_.clear();
uiVertexData_.clear();
text_.GetBatches(uiBatches_, uiVertexData_, IntRect::ZERO);
Vector3 offset(Vector3::ZERO);
switch (text_.GetHorizontalAlignment())
{
case HA_LEFT:
break;
case HA_CENTER:
offset.x_ -= (float)text_.GetWidth() * 0.5f;
break;
case HA_RIGHT:
offset.x_ -= (float)text_.GetWidth();
break;
}
switch (text_.GetVerticalAlignment())
{
case VA_TOP:
break;
case VA_CENTER:
offset.y_ -= (float)text_.GetHeight() * 0.5f;
break;
case VA_BOTTOM:
offset.y_ -= (float)text_.GetHeight();
break;
}
if (!uiVertexData_.empty())
{
boundingBox_.Clear();
for (unsigned i = 0; i < uiVertexData_.size(); i += UI_VERTEX_SIZE)
{
Vector3& position = *(reinterpret_cast<Vector3*>(&uiVertexData_[i]));
position += offset;
position *= TEXT_SCALING;
position.y_ = -position.y_;
boundingBox_.Merge(position);
}
}
else
boundingBox_.Define(Vector3::ZERO, Vector3::ZERO);
textDirty_ = false;
geometryDirty_ = true;
}
void Text3D::UpdateTextMaterials(bool forceUpdate)
{
Font* font = GetFont();
bool isSDFFont = font ? font->IsSDFFont() : false;
batches_.resize(uiBatches_.size());
geometries_.resize(uiBatches_.size());
for (unsigned i = 0; i < batches_.size(); ++i)
{
if (!geometries_[i])
{
Geometry* geometry = new Geometry(context_);
geometry->SetVertexBuffer(0, vertexBuffer_);
batches_[i].geometry_ = geometries_[i] = geometry;
}
if (!batches_[i].material_ || forceUpdate || isSDFFont != usingSDFShader_)
{
// If material not defined, create a reasonable default from scratch
if (!material_)
{
Material* material = new Material(context_);
Technique* tech = new Technique(context_);
Pass* pass = tech->CreatePass("alpha");
pass->SetVertexShader("Text");
pass->SetPixelShader("Text");
pass->SetBlendMode(BLEND_ALPHA);
pass->SetDepthWrite(false);
material->SetTechnique(0, tech);
material->SetCullMode(CULL_NONE);
batches_[i].material_ = material;
}
else
batches_[i].material_ = material_->Clone();
usingSDFShader_ = isSDFFont;
}
Material* material = batches_[i].material_;
Texture* texture = uiBatches_[i].texture_;
material->SetTexture(TU_DIFFUSE, texture);
if (isSDFFont)
{
// Note: custom defined material is assumed to have right shader defines; they aren't modified here
if (!material_)
{
Technique* tech = material->GetTechnique(0);
Pass* pass = tech ? tech->GetPass("alpha") : (Pass*)0;
if (pass)
{
switch (GetTextEffect())
{
case TE_NONE:
pass->SetPixelShaderDefines("SIGNED_DISTANCE_FIELD");
break;
case TE_SHADOW:
pass->SetPixelShaderDefines("SIGNED_DISTANCE_FIELD TEXT_EFFECT_SHADOW");
break;
case TE_STROKE:
pass->SetPixelShaderDefines("SIGNED_DISTANCE_FIELD TEXT_EFFECT_STROKE");
break;
}
}
}
switch (GetTextEffect())
{
case TE_SHADOW:
if (texture)
{
Vector2 shadowOffset(0.5f / texture->GetWidth(), 0.5f / texture->GetHeight());
material->SetShaderParameter("ShadowOffset", shadowOffset);
}
material->SetShaderParameter("ShadowColor", GetEffectColor());
break;
case TE_STROKE:
material->SetShaderParameter("StrokeColor", GetEffectColor());
break;
default:
break;
}
}
else
{
// If not SDF, set shader defines based on whether font texture is full RGB or just alpha
if (!material_)
{
Technique* tech = material->GetTechnique(0);
Pass* pass = tech ? tech->GetPass("alpha") : (Pass*)0;
if (pass)
{
if (texture && texture->GetFormat() == Graphics::GetAlphaFormat())
pass->SetPixelShaderDefines("ALPHAMAP");
else
pass->SetPixelShaderDefines("");
}
}
}
}
}
void Text3D::CalculateFixedScreenSize(const FrameInfo& frame)
{
Vector3 worldPosition = node_->GetWorldPosition();
Vector3 worldScale = node_->GetWorldScale();
if (fixedScreenSize_)
{
float textScaling = 2.0f / TEXT_SCALING / frame.viewSize_.y_;
float halfViewWorldSize = frame.camera_->GetHalfViewSize();
if (frame.camera_->getProjectionType()==PT_PERSPECTIVE)
{
Matrix4 viewProj(frame.camera_->GetProjection() * frame.camera_->GetView());
Vector4 projPos(viewProj * Vector4(worldPosition, 1.0f));
worldScale *= textScaling * halfViewWorldSize * projPos.w_;
}
else
worldScale *= textScaling * halfViewWorldSize;
}
customWorldTransform_ = Matrix3x4(worldPosition, frame.camera_->GetFaceCameraRotation(
worldPosition, node_->GetWorldRotation(), faceCameraMode_, minAngle_), worldScale);
worldBoundingBoxDirty_ = true;
}
}
|
// Guo Wanqi 2019
#include "TankMovementComponent.h"
#include "TankTrack.h"
void UTankMovementComponent::IntendMoveForward(float verticalThrow) {
//UE_LOG(LogTemp, Warning, TEXT("vertical throw %f"), verticalThrow);
if (!ensure(leftTrack) || !ensure(rightTrack)) return;
leftTrack->SetThrottle(verticalThrow);
rightTrack->SetThrottle(verticalThrow);
}
void UTankMovementComponent::IntendTurnRight(float horizontalThrow) {
if (!ensure(leftTrack)|| !ensure(rightTrack)) return;
leftTrack->SetThrottle(horizontalThrow);
rightTrack->SetThrottle(-horizontalThrow);
}
void UTankMovementComponent::Initialise(UTankTrack* leftTrackToSet, UTankTrack* rightTrackToSet) {
if (!ensure(leftTrackToSet) || !ensure(rightTrackToSet)) return;
leftTrack = leftTrackToSet;
rightTrack = rightTrackToSet;
}
void UTankMovementComponent::RequestDirectMove(const FVector & MoveVelocity, bool bForceMaxSpeed)
{
//FName name = GetOwner()->GetFName();
FVector tankForward = GetOwner()->GetActorForwardVector().GetSafeNormal();
FVector moveVelocityNormal = MoveVelocity.GetSafeNormal();
float angle = FVector::DotProduct(tankForward, moveVelocityNormal);
FVector turnVector = FVector::CrossProduct(tankForward, moveVelocityNormal);
//UE_LOG(LogTemp, Warning, TEXT("%s move velocity %s"), *name.ToString(), *MoveVelocity.GetSafeNormal().ToString())
//UE_LOG(LogTemp, Warning, TEXT("angle %f turn %f"), angle, turnVector.Z)
IntendMoveForward(angle);
IntendTurnRight(turnVector.Z);
}
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <algorithm>
#include <limits>
#include <list>
#include <memory>
#include <vector>
#include <ngraph/ngraph.hpp>
#include <ngraph/pass/graph_rewrite.hpp>
#include "transformation_context.hpp"
#include "quantization_details.hpp"
#include "low_precision/common/ie_lpt_exception.hpp"
#include "common/fake_quantize_dequantization.hpp"
/*****************************************************
* Debug capability
* - ORIGINAL_MODEL_PATH : Specify with existing folder name
* to serialize original model into it (XML & BIN extensions were added)
* - TRANSFORMED_MODEL_PATH : Specify with existing folder name
* to serialize original model into it (XML & BIN extensions were added)
* - LPT_PRINT_DEQUANTIZATION_INFO : Define it to enable
* dequantization layers printing
* - LPT_DISPLAY_PRECISION : Define it to to display precision info
* during low precision transformations
*
*****************************************************/
// #define LPT_ORIGINAL_MODEL_PATH "/localdisk/orig.model"
// #define LPT_TRANSFORMED_MODEL_PATH "/localdisk/transformed.model"
// #define LPT_PRINT_DEQUANTIZATION_INFO
// #define LPT_DISPLAY_PRECISION
namespace ngraph {
namespace pass {
namespace low_precision {
namespace precision_set {
const std::vector<element::Type> int8_support = {
ngraph::element::u8, ngraph::element::i8
};
const std::vector<element::Type> int8_int16_int32_support = {
ngraph::element::u8, ngraph::element::i8,
ngraph::element::u16, ngraph::element::i16,
ngraph::element::u32, ngraph::element::i32
};
}
enum levels : size_t {
int4 = 16,
int4_narrow_range = 15,
int8 = 256,
int8_narrow_range = 255,
int16 = 65536,
int16_narrow_range = 65535,
int32 = size_t(4294967296), // for ARM and ia32 platforms where this number bigger than size_t but never used
int32_narrow_range = 4294967295
};
class LP_TRANSFORMATIONS_API DataPrecision {
public:
DataPrecision() : precision(element::undefined), min(0.f), max(0.f), hasZeroPoint(false) {}
explicit DataPrecision(const element::Type& precision) {
this->precision = precision;
min = getMinValue(precision, levels::int8);
max = getMaxValue(precision, levels::int8);
hasZeroPoint = false;
}
DataPrecision(const element::Type precision, const float min, const float max, const bool hasZeroPoint) :
precision(precision),
min(min),
max(max),
hasZeroPoint(hasZeroPoint) {}
bool empty() const noexcept {
return (precision == element::undefined) && (min == 0.f) && (max == 0.f) && (!hasZeroPoint);
}
static bool isSupported(const element::Type& precision) {
static const std::set<element::Type_t> lowPrecision = {
element::i8, element::u8,
element::i16, element::u16,
element::i32, element::u32
};
return lowPrecision.find(precision) != lowPrecision.end();
}
static float getMinValue(const element::Type precision, const size_t levels) {
switch (precision) {
case element::u4:
case element::u8:
case element::u16:
case element::u32:
return 0.f;
case element::i4:
return -8.f;
case element::i8:
switch (levels) {
case low_precision::levels::int4:
return -8.f;
case low_precision::levels::int4_narrow_range:
return -7.f;
case low_precision::levels::int8:
return -128.f;
case low_precision::levels::int8_narrow_range:
return -127.f;
}
case element::i16:
switch (levels) {
case low_precision::levels::int16:
return -32768.f;
case low_precision::levels::int16_narrow_range:
return -32767.f;
}
break;
case element::i32:
switch (levels) {
case low_precision::levels::int32:
return -2147483648.f;
case low_precision::levels::int32_narrow_range:
return -2147483647.f;
}
break;
case element::f16:
return -1.0e15f;
case element::f32:
return std::numeric_limits<float>::lowest();
default:
NGRAPH_CHECK(false, "unexpected precision ", precision);
}
NGRAPH_CHECK(false, "unexpected levels ", levels, " for precision ", precision);
}
static float getMaxValue(const element::Type precision, const size_t levels) {
switch (precision) {
case element::u4:
return 15.f;
case element::u8:
switch (levels) {
case 16:
return 15.f;
default:
return 255.f;
}
case element::u16:
return 65535.f;
case element::u32:
return 4294967296.f; // 4294967296.f == 4294967295.f
case element::i4:
return 7.f;
case element::i8:
switch (levels) {
case 16:
return 7.f;
default:
return 127.f;
}
case element::i16:
return 32767.f;
case element::i32:
return 2147483648.f; // 2147483648.f == 2147483647.f
case element::f16:
return 1.0e15f;
case element::f32:
return std::numeric_limits<float>::max();
default:
NGRAPH_CHECK(false, "unexpected precision ", precision);
}
}
// Return maximum value for quantization level. Quantization level is maximum value for precision.
static float getMaxValue(const size_t maxLevelsForPrecision) {
std::set<size_t> validLevels = {
levels::int4, levels::int4_narrow_range,
levels::int8, levels::int8_narrow_range,
levels::int16, levels::int16_narrow_range,
levels::int32, levels::int32_narrow_range
};
if (validLevels.find(maxLevelsForPrecision) != validLevels.end()) {
return maxLevelsForPrecision - 1.f;
} else {
THROW_TRANSFORMATION_EXCEPTION << "unexpected quantization level " << maxLevelsForPrecision;
}
}
static bool hasNegativeValues(const std::vector<float>& values) {
for (const float value : values) {
if (value < 0.0) {
return true;
}
}
return false;
}
element::Type precision;
float min;
float max;
bool hasZeroPoint;
static element::Type getPrecision(const std::vector<float>& outputLowValues, const std::vector<float>& outputHighValues) {
return (hasNegativeValues(outputLowValues) || hasNegativeValues(outputHighValues)) ? element::i8 : element::u8;
}
static element::Type getPrecision(const size_t /* quantizationLevels */, const bool signedInterval) {
return signedInterval ? element::i8 : element::u8;
}
};
inline bool operator==(const DataPrecision& value1, const DataPrecision& value2) {
return
(value1.precision == value2.precision) &&
(value1.min == value1.min) &&
(value1.max == value1.max);
}
inline bool operator!=(const DataPrecision& value1, const DataPrecision& value2) {
return !(value1 == value2);
}
inline std::ostream &operator << (std::ostream &os, const DataPrecision& value) {
os << value.precision << ", min: " << value.min << ", max: " << value.max;
return os;
}
/**
* @ingroup ie_transformation_common_api
* @brief Base class for low precision transformation.
*/
class LP_TRANSFORMATIONS_API LayerTransformation : public ngraph::pass::MatcherPass {
static std::vector<ngraph::element::Type> defaultPrecisions;
static std::mutex defaultPrecisionsMutex;
public:
class Params {
public:
Params(
const bool updatePrecisions = true,
element::Type deqPrecision = element::f32) :
updatePrecisions(updatePrecisions),
deqPrecision(deqPrecision) {}
Params& setUpdatePrecisions(const bool updatePrecisions) {
this->updatePrecisions = updatePrecisions;
return *this;
}
Params& setDeqPrecision(const element::Type& deqPrecision) {
this->deqPrecision = deqPrecision;
return *this;
}
bool updatePrecisions;
element::Type deqPrecision;
};
class PrecisionDetails {
public:
PrecisionDetails(const element::Type& precision, const bool hasNegativeOutput, const bool hasZeroPoint) :
precision(precision),
hasNegativeOutput(hasNegativeOutput),
hasZeroPoint(hasZeroPoint) {}
element::Type precision;
bool hasNegativeOutput;
bool hasZeroPoint;
};
LayerTransformation(const Params& params);
virtual ~LayerTransformation() = default;
virtual bool transform(TransformationContext& context, ngraph::pattern::Matcher &m) = 0;
void setContext(TransformationContext* context) noexcept;
void setUpdatePrecisions(const bool updatePrecisions);
virtual bool canBeTransformed(const TransformationContext& context, std::shared_ptr<Node> layer) const;
static bool canBeTransformedStatic(const std::shared_ptr<Node>& layer);
bool canSubtractBeHandled(const std::shared_ptr<Node>& op, const FakeQuantizeDequantization& dequantization) const;
// Get precision based on FakeQuantize operation.
// Undefined value is expected. In this case the accuracy has to be defined by the calling code.
// TODO: LPT: INT8 specific here
static PrecisionDetails getPrecisionDetails(
const size_t quantizationLevels,
const std::vector<float>& outputLowValues,
const std::vector<float>& outputHighValues);
static PrecisionDetails getPrecisionDetails(const QuantizationDetails& quantizationDetails);
static bool isAsymmetricQuantization(const std::shared_ptr<const Node>& node);
// return true if operation can be quantized and false otherwise
// for example: if convolution operation weights are not quantized, then isQuantize returns false and true otherwise
// note: dequantization operations on activations are absent during method execution
virtual bool isQuantized(const std::shared_ptr<const Node>& layer) const;
// return true if operation can be preserved for precision
// note: dequantization operations on activations are absent during method execution
virtual bool isPrecisionPreserved(std::shared_ptr<Node> layer) const = 0;
// weights specific
static DataPrecision getDataPrecision(
const std::shared_ptr<Node>& layer,
const QuantizationDetails& quantizationDetails,
const std::vector<element::Type>& precisions);
static void setDefaultPrecisions(const std::vector<ngraph::element::Type>& precisions);
static std::vector<ngraph::element::Type> getDefaultPrecisions();
protected:
#ifdef LPT_PRINT_DEQUANTIZATION_INFO
static void printDequantizationInfo(const std::shared_ptr<Node>& layer);
static void printDequantizationInfo(const DataPrecision& dataPrecision);
static void printDequantizationValues(
const std::vector<float>& dequantizationScales,
const std::vector<float>& dequantizationShifts);
#endif
bool updatePrecisions;
element::Type deqPrecision;
static constexpr char originalLayerPostfix[] = "_original";
TransformationContext* context;
protected:
std::shared_ptr<ngraph::Node> moveDequantizationAfter(
TransformationContext &context,
const std::shared_ptr<ngraph::Node>& operation,
const FakeQuantizeDequantization& dequantization,
const bool updatePrecision,
const bool moveSubtract = true) const;
void updateOutput(
TransformationContext &context,
std::shared_ptr<ngraph::Node> lastNode,
std::shared_ptr<ngraph::Node> originalNode) const;
void updateOutput(
TransformationContext& context,
std::shared_ptr<ngraph::Node> lastNode,
std::string originalName) const;
void addPattern(ngraph::pass::GraphRewrite& pass, TransformationContext& context, std::shared_ptr<Node> patternRoot);
//TODO: replace with canBeTransformed when quantization by special dimension is supported for all transformations
bool canBeTransformedSpatialDimension(const TransformationContext& context, std::shared_ptr<Node> layer) const;
template <typename Operation>
void addSingleNodePattern(ngraph::pass::GraphRewrite& pass, TransformationContext& context) const {
using namespace ngraph;
auto is_op_type = [](std::shared_ptr<Node> n) {
return !!as_type_ptr<Operation>(n);
};
auto p_node = std::make_shared<pattern::op::Label>(element::f32, Shape{}, is_op_type);
addPattern(pass, context, p_node);
}
};
typedef std::shared_ptr<LayerTransformation> LayerTransformationPtr;
} // namespace low_precision
} // namespace pass
} // namespace ngraph
|
/*
-- MAGMA (version 2.5.4) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date October 2020
@precisions normal z -> c d s
@author Hartwig Anzt
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
// includes, project
#include "magma_v2.h"
#include "magmasparse.h"
#include "magma_operators.h"
#include "testings.h"
/* ////////////////////////////////////////////////////////////////////////////
-- testing any solver
*/
int main( int argc, char** argv )
{
magma_int_t info = 0;
/* Initialize */
TESTING_CHECK( magma_init() );
magma_print_environment();
magma_queue_t queue=NULL;
magma_queue_create( 0, &queue );
magma_int_t i, n=100;
magma_index_t *x=NULL;
magmaDoubleComplex *y=NULL;
magma_z_matrix A={Magma_CSR};
TESTING_CHECK( magma_index_malloc_cpu( &x, n ));
printf("unsorted:\n");
srand(time(NULL));
for(i = 0; i < n; i++ ){
int r = rand()%100;
x[i] = r;
printf("%d ", x[i]);
}
printf("\n\n");
printf("sorting...");
TESTING_CHECK( magma_zindexsort(x, 0, n-1, queue ));
printf("done.\n\n");
printf("sorted:\n");
for(i = 0; i < n; i++ ){
printf("%d ", x[i]);
}
printf("\n\n");
magma_free_cpu( x );
TESTING_CHECK( magma_zmalloc_cpu( &y, n ));
printf("unsorted:\n");
srand(time(NULL));
for(i = 0; i < n; i++ ){
double r = (double) rand()/(double) 10.;
y[i] = MAGMA_Z_MAKE( r, 0.0);
if (i % 5 == 0)
y[i] = - y[i];
printf("%2.2f + %2.2f ", MAGMA_Z_REAL(y[i]), MAGMA_Z_IMAG(y[i]) );
}
printf("\n\n");
printf("sorting...");
TESTING_CHECK( magma_zsort(y, 0, n-1, queue ));
printf("done.\n\n");
printf("sorted:\n");
for(i = 0; i < n; i++ ){
printf("%2.2f + %2.2f ", MAGMA_Z_REAL(y[i]), MAGMA_Z_IMAG(y[i]) );
}
printf("\n\n");
magma_free_cpu( y );
i=1;
while( i < argc ) {
if ( strcmp("LAPLACE2D", argv[i]) == 0 && i+1 < argc ) { // Laplace test
i++;
magma_int_t laplace_size = atoi( argv[i] );
TESTING_CHECK( magma_zm_5stencil( laplace_size, &A, queue ));
} else { // file-matrix test
TESTING_CHECK( magma_z_csr_mtx( &A, argv[i], queue ));
}
printf( "\n# matrix info: %lld-by-%lld with %lld nonzeros\n\n",
(long long) A.num_rows, (long long) A.num_cols, (long long) A.nnz);
TESTING_CHECK( magma_index_malloc_cpu( &x, A.num_rows*10 ));
magma_int_t num_ind = 0;
TESTING_CHECK( magma_zdomainoverlap( A.num_rows, &num_ind, A.row, A.col, x, queue ));
printf("domain overlap indices:\n");
for(magma_int_t j = 0; j < num_ind; j++ ){
printf("%d ", x[j] );
}
printf("\n\n");
magma_free_cpu( x );
magma_zmfree(&A, queue);
i++;
}
magma_queue_destroy( queue );
magma_finalize();
return info;
}
|
#include "Library.h"
void Library::parse()
{
std::regex pattern("(.*):(.*)[\\n\\r]*");
std::smatch result{};
std::ifstream file(path);
std::string line;
for (int i = 0; std::getline(file, line); ++i)
{
if (!std::regex_match(line, result, pattern))
{
std::ostringstream oss;
oss << "Failed to parse \"";
oss << path << "\" at line (";
oss << i << ")";
throw std::exception(oss.str().c_str());
}
environment[result[0]] = result[1];
}
}
|
/*
Copyright (C) 2018-2020 Theodorus Software
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 <Common/StringArray.h>
#include <Common/StringLib.h>
#include <Common/Allocator.h>
#include <Compress/Archive.h>
#include <Common/FileAccess.h>
#include <Common/TextStream.h>
#include "ArchiveArg.h"
#if TAA_PLATFORM == TAA_PLATFORM_WINDOWS
#include <Common/platform/swindows.h>
#include <FileManager/FileManagerDef.h>
#include <FileManager/FileManager.h>
#elif TAA_PLATFORM == TAA_PLATFORM_LINUX
#include <unistd.h>
#include <sys/time.h>
#endif
using namespace tas;
ArchiveArg* args = 0;
void findModule();
String parserCmdLine(String srcCmdLine);
#ifdef TAA_ARCHIVARIUS_GUI_NATIVE
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE prevInstance, wchar_t* lpCmdLine, int nShowCmd)
#else
int wmain(int argc, wchar_t* argv[])
#endif
{
allocatorSetClientMemoryRoutines();
allocatorInit();
// allocatorSetTableMode(0x40); // memory leak table
allocatorSetMemorySize(1 * MB, 64 * KB);
args = new ArchiveArg;
findModule();
{
FileManager fileManager;
#ifdef TAA_ARCHIVARIUS_GUI_NATIVE
if(stwlen(lpCmdLine))
{
String cmdLine = parserCmdLine(lpCmdLine);
fileManager.create(cmdLine);
}
else
fileManager.create(L"");
#else
fileManager.create(argc > 1 ? argv[1] : 0);
#endif
}
createFolder(args->logDirName, 1);
safe_delete(args);
allocatorInfo();
allocatorClean();
return 0;
}
String parserCmdLine(String srcCmdLine)
{
// trim quotes
String dstCmdLine = srcCmdLine;
int quote = dstCmdLine.find(0x22);
if(quote != -1)
{
dstCmdLine.substrs(quote + 1);
dstCmdLine.trim(0x22, 1);
}
return dstCmdLine;
}
void findModule()
{
// full module path with '\' end
String mol;
String tol;
mol.reserve(0x400);
tol.reserve(0x400);
#if TAA_PLATFORM == TAA_PLATFORM_WINDOWS
GetModuleFileName(0, mol.p(), 0x400);
mol.update();
int bs = mol.findr(PATH_SEP);
assert(bs != -1);
mol.resize(bs+1);
args->module = mol;
#elif TAA_PLATFORM == TAA_PLATFORM_LINUX
#if TAA_PLATFORM_TYPE == TAA_PLATFORM_MOBILE
mol = "/sdcard/android/data/com.archiver/";
#else
readlink("/proc/self/exe", mol.p(), 0x400);
int bs = mol.findr(PATH_SEP);
assert(bs != -1);
mol.resize(bs+1);
#endif
#endif
tol.format("%sNotification%cAllocator.log", mol.p(), PATH_SEP);
allocatorSetLog(tol.p());
tol.format("%sNotification%cArchivarius.log", mol.p(), PATH_SEP);
args->logName = tol;
tol.format("%sNotification", mol.p());
args->logDirName = tol;
createFolder(tol, 1);
}
namespace tas
{
String& getLogName()
{
return args->logName;
}
}
|
/*******************************************************************************
* Copyright 2018 Intel Corporation
*
* 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 <assert.h>
#include <math.h>
#include "c_types_map.hpp"
#include "type_helpers.hpp"
#include "cpu_batch_normalization_utils.hpp"
#include "jit_generator.hpp"
#include "nspc_batch_normalization.hpp"
// clang 6 and 7 generate incorrect code with OMP_SIMD in some particular cases
#if (defined __clang_major__) && (__clang_major__ >= 6)
#define SAFE_TO_USE_OMP_SIMD 0
#else
#define SAFE_TO_USE_OMP_SIMD 1
#endif
namespace mkldnn {
namespace impl {
namespace cpu {
using namespace memory_tracking::names;
void nspc_batch_normalization_fwd_t::execute_forward() const {
auto src = reinterpret_cast<const data_t *>(this->input_memory(0));
const bool save_stats = pd()->is_training();
const bool is_training = pd()->is_training();
const bool fuse_bn_relu = pd()->fuse_bn_relu();
const bool calculate_stats = !pd()->stats_is_src();
const bool with_relu = pd()->with_relu_post_op();
auto scratchpad = this->scratchpad();
auto tmp_mean = scratchpad.get<data_t>(key_bnorm_tmp_mean);
auto tmp_var = scratchpad.get<data_t>(key_bnorm_tmp_var);
data_t *mean, *variance;
if (!calculate_stats) {
mean = reinterpret_cast<data_t *>(
const_cast<char *>(this->input_memory(1)));
variance = reinterpret_cast<data_t *>(
const_cast<char *>(this->input_memory(2)));
} else {
if (save_stats) {
mean = reinterpret_cast<data_t *>(this->memory(1));
variance = reinterpret_cast<data_t *>(this->memory(2));
} else {
mean = tmp_mean;
variance = tmp_var;
}
}
auto idx_scaleshift = 1 + 2 * pd()->stats_is_src();
auto scaleshift = reinterpret_cast<const data_t *>(
this->input_memory(idx_scaleshift));
auto dst = reinterpret_cast<data_t *>(this->memory(0));
auto ws = reinterpret_cast<uint8_t *>(this->memory(pd()->ws_idx()));
auto *ws_reduce = scratchpad.get<data_t>(key_bnorm_reduction);
const int N = pd()->MB();
const int C = pd()->C();
const int SP = pd()->H() * pd()->W() * pd()->D();
const float eps = pd()->desc()->batch_norm_epsilon;
const bool use_scaleshift = pd()->use_scaleshift();
auto maybe_post_op
= [&](data_t res) { return (with_relu && res < 0) ? 0 : res; };
assert(mkldnn_thr_syncable());
parallel(0, [&](const int ithr, const int nthr) {
int N_s = 0, N_e = 0, C_s = 0, C_e = 0;
balance211(N, nthr, ithr, N_s, N_e);
balance211(C, nthr, ithr, C_s, C_e);
data_t *mean_loc = tmp_mean + nstl::max(C, 16) * ithr;
data_t *variance_loc = tmp_var + nstl::max(C, 16) * ithr;
if (calculate_stats) {
for (int c = 0; c < C; c++)
ws_reduce[C * ithr + c] = 0.;
for (int n = N_s; n < N_e; n++)
for (int sp = 0; sp < SP; sp++)
PRAGMA_OMP_SIMD()
for (int c = 0; c < C; c++)
ws_reduce[C * ithr + c] += src[(size_t)n * SP * C
+ sp * C + c];
mkldnn_thr_barrier();
for (int c = C_s; c < C_e; c++) {
mean[c] = 0;
for (int n = 0; n < nthr; n++)
mean[c] += ws_reduce[C * n + c];
mean[c] /= SP * N;
}
mkldnn_thr_barrier();
for (int c = 0; c < C; c++) {
mean_loc[c] = mean[c];
ws_reduce[C * ithr + c] = 0.;
}
for (int n = N_s; n < N_e; n++)
for (int sp = 0; sp < SP; sp++)
PRAGMA_OMP_SIMD()
for (int c = 0; c < C; c++) {
data_t m = src[(size_t)n * SP * C + sp * C + c]
- mean_loc[c];
ws_reduce[C * ithr + c] += m * m;
}
mkldnn_thr_barrier();
for (int c = C_s; c < C_e; c++) {
variance[c] = 0;
for (int n = 0; n < nthr; n++)
variance[c] += ws_reduce[C * n + c];
variance[c] /= SP * N;
}
mkldnn_thr_barrier();
for (int c = 0; c < C; c++)
variance_loc[c] = variance[c];
} else {
variance_loc = variance;
mean_loc = mean;
}
for (int n = N_s; n < N_e; n++) {
for (int sp = 0; sp < SP; sp++) {
#if SAFE_TO_USE_OMP_SIMD
PRAGMA_OMP_SIMD()
#endif
for (int c = 0; c < C; c++) {
data_t sqrt_variance = static_cast<data_t>(
1.0f / sqrtf(variance_loc[c] + eps));
data_t sm = use_scaleshift ? scaleshift[c] : 1;
data_t sv = use_scaleshift ? scaleshift[C + c] : 0;
data_t bn_res
= sm * (src[(size_t)n * SP * C + sp * C + c]
- mean_loc[c]) * sqrt_variance + sv;
if (fuse_bn_relu) {
if (bn_res <= 0) {
bn_res = 0;
if (is_training)
ws[(size_t)n * SP * C + sp * C + c] = 0;
} else {
if (is_training)
ws[(size_t)n * SP * C + sp * C + c] = 1;
}
}
dst[(size_t)n * SP * C + sp * C + c] = maybe_post_op(bn_res);
}
}
}
});
}
void nspc_batch_normalization_bwd_t::execute_backward() const {
auto src = reinterpret_cast<const data_t *>(this->input_memory(0));
auto mean = reinterpret_cast<const data_t *>(this->input_memory(1));
auto variance = reinterpret_cast<const data_t *>(this->input_memory(2));
auto diff_dst = reinterpret_cast<const data_t *>(this->input_memory(3));
auto scaleshift = reinterpret_cast<const data_t *>(this->input_memory(4));
auto ws = reinterpret_cast<const uint8_t *>(
this->input_memory(pd()->ws_idx()));
auto scratchpad = this->scratchpad();
auto tmp_diff_ss = scratchpad.get<data_t>(key_bnorm_tmp_diff_ss);
auto diff_src = reinterpret_cast<data_t *>(this->memory(0));
auto diff_scaleshift = this->memory(1)
? reinterpret_cast<data_t *>(this->memory(1)) : tmp_diff_ss;
const int N = pd()->MB();
const int C = pd()->C();
const int SP = pd()->D() * pd()->H() * pd()->W();
data_t *diff_gamma = diff_scaleshift, *diff_beta = diff_scaleshift + C;
auto *ws_reduce = scratchpad.get<data_t>(key_bnorm_reduction);
const float eps = pd()->desc()->batch_norm_epsilon;
const bool use_scaleshift = pd()->use_scaleshift();
const bool calculate_diff_stats = !pd()->use_global_stats();
const bool fuse_bn_relu = pd()->fuse_bn_relu();
assert(mkldnn_thr_syncable());
parallel(0, [&](const int ithr, const int nthr) {
int N_s = 0, N_e = 0, C_s = 0, C_e = 0;
balance211(N, nthr, ithr, N_s, N_e);
balance211(C, nthr, ithr, C_s, C_e);
data_t *diff_gamma_loc = tmp_diff_ss + 2 * C + C * ithr;
data_t *diff_beta_loc = tmp_diff_ss + 2 * C + C * (nthr + ithr);
for (int c = 0; c < C; c++) {
ws_reduce[C * ithr + c] = 0.;
ws_reduce[C * nthr + C * ithr + c] = 0.;
}
for (int n = N_s; n < N_e; n++)
for (int sp = 0; sp < SP; sp++)
#if SAFE_TO_USE_OMP_SIMD
PRAGMA_OMP_SIMD()
#endif
for (int c = 0; c < C; c++) {
const size_t d_off = (size_t)n * SP * C + sp * C + c;
data_t dd;
if (fuse_bn_relu)
dd = (!ws[d_off]) ? 0 : diff_dst[d_off];
else
dd = diff_dst[d_off];
ws_reduce[C * ithr + c] += (src[d_off] - mean[c]) * dd;
ws_reduce[C * nthr + C * ithr + c] += dd;
}
mkldnn_thr_barrier();
for (int c = C_s; c < C_e; c++) {
data_t sqrt_variance
= static_cast<data_t>(1.0f / sqrtf(variance[c] + eps));
diff_gamma[c] = 0;
diff_beta[c] = 0;
for (int n = 0; n < nthr; n++) {
diff_gamma[c] += ws_reduce[C * n + c];
diff_beta[c] += ws_reduce[C * nthr + C * n + c];
}
diff_gamma[c] *= sqrt_variance;
}
mkldnn_thr_barrier();
for (int c = 0; c < C; c++) {
diff_gamma_loc[c] = diff_gamma[c];
diff_beta_loc[c] = diff_beta[c];
}
for (int n = N_s; n < N_e; n++) {
for (int sp = 0; sp < SP; sp++) {
#if SAFE_TO_USE_OMP_SIMD
PRAGMA_OMP_SIMD()
#endif
for (int c = 0; c < C; c++) {
const size_t d_off = (size_t)n * SP * C + sp * C + c;
data_t gamma = use_scaleshift ? scaleshift[c] : 1;
data_t sqrt_variance
= static_cast<data_t>(1.0f / sqrtf(variance[c] + eps));
data_t v_diff_src;
if (fuse_bn_relu)
v_diff_src = (!ws[d_off]) ? 0 : diff_dst[d_off];
else
v_diff_src = diff_dst[d_off];
if (calculate_diff_stats) {
v_diff_src -= diff_beta_loc[c] / (SP * N)
+ (src[d_off] - mean[c]) * diff_gamma_loc[c]
* sqrt_variance / (SP * N);
}
v_diff_src *= gamma * sqrt_variance;
diff_src[d_off] = v_diff_src;
}
}
}
});
}
}
}
}
// vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
|
//
// _
// ___/_)
// (, / ,_ _
// / (_(_/ (_(_(_
// CX________________
// )
//
// Luna
// A web application and API framework in modern C++
//
// Copyright © 2016–2018 D.E. Goodman-Wilson
//
#include <gtest/gtest.h>
#include <luna/luna.h>
#include <cpr/cpr.h>
TEST(put, default_404)
{
luna::server server;
server.start_async();
auto res = cpr::Put(cpr::Url{"http://localhost:8080/"});
ASSERT_EQ(404, res.status_code);
}
TEST(put, default_200)
{
luna::server server;
auto router = server.create_router("/");
router->handle_request(luna::request_method::PUT,
"/test",
[](auto req) -> luna::response
{
return {"hello"};
});
server.start_async();
auto res = cpr::Put(cpr::Url{"http://localhost:8080/test"}, cpr::Payload{});
ASSERT_EQ(200, res.status_code);
ASSERT_EQ("hello", res.text);
}
TEST(put, default_200_check_params)
{
luna::server server;
auto router = server.create_router("/");
router->handle_request(luna::request_method::PUT,
"/test",
[](auto req) -> luna::response
{
EXPECT_EQ(1, req.params.count("key"));
EXPECT_EQ("value", req.params.at("key"));
EXPECT_EQ(1, req.params.count("key2"));
EXPECT_EQ("", req.params.at("key2"));
return {"hello"};
});
server.start_async();
auto res = cpr::Put(cpr::Url{"http://localhost:8080/test"},
cpr::Payload{{"key2", ""},
{"key", "value"}});
ASSERT_EQ(200, res.status_code);
ASSERT_EQ("hello", res.text);
}
|
#include "tree.h"
#include <tomlplusplus/toml.h>
#include <sstream>
using namespace tog;
namespace tog {
Tree::Tree(std::unordered_map<std::string, Handle<Blob>> &&blobs,
std::unordered_map<std::string, Handle<Tree>> &&trees)
: _blobs{std::move(blobs)}, _trees{std::move(trees)} {}
const std::vector<unsigned char> &Tree::serialize() {
// serialize lazily
if (_serialized) {
return *_serialized;
}
// encode as toml
auto blobs_toml = toml::table();
for (const auto &[name, blob] : _blobs) {
blobs_toml.insert(name, blob.hash());
}
auto trees_toml = toml::table();
for (const auto &[name, tree] : _trees) {
trees_toml.insert(name, tree.hash());
}
auto tree_toml = toml::table{{
{"blobs", blobs_toml},
{"trees", trees_toml},
}};
// Serialize to string
std::stringstream stream{};
stream << tree_toml;
std::string tree_str = stream.str();
_serialized.emplace(tree_str.begin(), tree_str.end());
return *_serialized;
}
} // namespace tog
|
//===-- TypeHierarchyTests.cpp ---------------------------*- C++ -*-------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Annotations.h"
#include "Compiler.h"
#include "Matchers.h"
#include "ParsedAST.h"
#include "SyncAPI.h"
#include "TestFS.h"
#include "TestTU.h"
#include "XRefs.h"
#include "index/FileIndex.h"
#include "index/SymbolCollector.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/Index/IndexingAction.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace clang {
namespace clangd {
namespace {
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::Field;
using ::testing::IsEmpty;
using ::testing::Matcher;
using ::testing::UnorderedElementsAre;
// GMock helpers for matching TypeHierarchyItem.
MATCHER_P(withName, N, "") { return arg.name == N; }
MATCHER_P(withKind, Kind, "") { return arg.kind == Kind; }
MATCHER_P(selectionRangeIs, R, "") { return arg.selectionRange == R; }
template <class... ParentMatchers>
::testing::Matcher<TypeHierarchyItem> parents(ParentMatchers... ParentsM) {
return Field(&TypeHierarchyItem::parents,
HasValue(UnorderedElementsAre(ParentsM...)));
}
template <class... ChildMatchers>
::testing::Matcher<TypeHierarchyItem> children(ChildMatchers... ChildrenM) {
return Field(&TypeHierarchyItem::children,
HasValue(UnorderedElementsAre(ChildrenM...)));
}
// Note: "not resolved" is different from "resolved but empty"!
MATCHER(parentsNotResolved, "") { return !arg.parents; }
MATCHER(childrenNotResolved, "") { return !arg.children; }
TEST(FindRecordTypeAt, TypeOrVariable) {
Annotations Source(R"cpp(
struct Ch^ild2 {
int c;
};
using A^lias = Child2;
int main() {
Ch^ild2 ch^ild2;
ch^ild2.c = 1;
}
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
for (Position Pt : Source.points()) {
const CXXRecordDecl *RD = findRecordTypeAt(AST, Pt);
EXPECT_EQ(&findDecl(AST, "Child2"), static_cast<const NamedDecl *>(RD));
}
}
TEST(FindRecordTypeAt, Method) {
Annotations Source(R"cpp(
struct Child2 {
void met^hod ();
void met^hod (int x);
};
int main() {
Child2 child2;
child2.met^hod(5);
}
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
for (Position Pt : Source.points()) {
const CXXRecordDecl *RD = findRecordTypeAt(AST, Pt);
EXPECT_EQ(&findDecl(AST, "Child2"), static_cast<const NamedDecl *>(RD));
}
}
TEST(FindRecordTypeAt, Field) {
Annotations Source(R"cpp(
struct Child2 {
int fi^eld;
};
int main() {
Child2 child2;
child2.fi^eld = 5;
}
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
for (Position Pt : Source.points()) {
const CXXRecordDecl *RD = findRecordTypeAt(AST, Pt);
// A field does not unambiguously specify a record type
// (possible associated reocrd types could be the field's type,
// or the type of the record that the field is a member of).
EXPECT_EQ(nullptr, RD);
}
}
TEST(TypeParents, SimpleInheritance) {
Annotations Source(R"cpp(
struct Parent {
int a;
};
struct Child1 : Parent {
int b;
};
struct Child2 : Child1 {
int c;
};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
const CXXRecordDecl *Parent =
dyn_cast<CXXRecordDecl>(&findDecl(AST, "Parent"));
const CXXRecordDecl *Child1 =
dyn_cast<CXXRecordDecl>(&findDecl(AST, "Child1"));
const CXXRecordDecl *Child2 =
dyn_cast<CXXRecordDecl>(&findDecl(AST, "Child2"));
EXPECT_THAT(typeParents(Parent), ElementsAre());
EXPECT_THAT(typeParents(Child1), ElementsAre(Parent));
EXPECT_THAT(typeParents(Child2), ElementsAre(Child1));
}
TEST(TypeParents, MultipleInheritance) {
Annotations Source(R"cpp(
struct Parent1 {
int a;
};
struct Parent2 {
int b;
};
struct Parent3 : Parent2 {
int c;
};
struct Child : Parent1, Parent3 {
int d;
};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
const CXXRecordDecl *Parent1 =
dyn_cast<CXXRecordDecl>(&findDecl(AST, "Parent1"));
const CXXRecordDecl *Parent2 =
dyn_cast<CXXRecordDecl>(&findDecl(AST, "Parent2"));
const CXXRecordDecl *Parent3 =
dyn_cast<CXXRecordDecl>(&findDecl(AST, "Parent3"));
const CXXRecordDecl *Child = dyn_cast<CXXRecordDecl>(&findDecl(AST, "Child"));
EXPECT_THAT(typeParents(Parent1), ElementsAre());
EXPECT_THAT(typeParents(Parent2), ElementsAre());
EXPECT_THAT(typeParents(Parent3), ElementsAre(Parent2));
EXPECT_THAT(typeParents(Child), ElementsAre(Parent1, Parent3));
}
TEST(TypeParents, ClassTemplate) {
Annotations Source(R"cpp(
struct Parent {};
template <typename T>
struct Child : Parent {};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
const CXXRecordDecl *Parent =
dyn_cast<CXXRecordDecl>(&findDecl(AST, "Parent"));
const CXXRecordDecl *Child =
dyn_cast<ClassTemplateDecl>(&findDecl(AST, "Child"))->getTemplatedDecl();
EXPECT_THAT(typeParents(Child), ElementsAre(Parent));
}
MATCHER_P(implicitSpecOf, ClassTemplate, "") {
const ClassTemplateSpecializationDecl *CTS =
dyn_cast<ClassTemplateSpecializationDecl>(arg);
return CTS &&
CTS->getSpecializedTemplate()->getTemplatedDecl() == ClassTemplate &&
CTS->getSpecializationKind() == TSK_ImplicitInstantiation;
}
// This is similar to findDecl(AST, QName), but supports using
// a template-id as a query.
const NamedDecl &findDeclWithTemplateArgs(ParsedAST &AST,
llvm::StringRef Query) {
return findDecl(AST, [&Query](const NamedDecl &ND) {
std::string QName;
llvm::raw_string_ostream OS(QName);
PrintingPolicy Policy(ND.getASTContext().getLangOpts());
// Use getNameForDiagnostic() which includes the template
// arguments in the printed name.
ND.getNameForDiagnostic(OS, Policy, /*Qualified=*/true);
OS.flush();
return QName == Query;
});
}
TEST(TypeParents, TemplateSpec1) {
Annotations Source(R"cpp(
template <typename T>
struct Parent {};
template <>
struct Parent<int> {};
struct Child1 : Parent<float> {};
struct Child2 : Parent<int> {};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
const CXXRecordDecl *Parent =
dyn_cast<ClassTemplateDecl>(&findDecl(AST, "Parent"))->getTemplatedDecl();
const CXXRecordDecl *ParentSpec =
dyn_cast<CXXRecordDecl>(&findDeclWithTemplateArgs(AST, "Parent<int>"));
const CXXRecordDecl *Child1 =
dyn_cast<CXXRecordDecl>(&findDecl(AST, "Child1"));
const CXXRecordDecl *Child2 =
dyn_cast<CXXRecordDecl>(&findDecl(AST, "Child2"));
EXPECT_THAT(typeParents(Child1), ElementsAre(implicitSpecOf(Parent)));
EXPECT_THAT(typeParents(Child2), ElementsAre(ParentSpec));
}
TEST(TypeParents, TemplateSpec2) {
Annotations Source(R"cpp(
struct Parent {};
template <typename T>
struct Child {};
template <>
struct Child<int> : Parent {};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
const CXXRecordDecl *Parent =
dyn_cast<CXXRecordDecl>(&findDecl(AST, "Parent"));
const CXXRecordDecl *Child =
dyn_cast<ClassTemplateDecl>(&findDecl(AST, "Child"))->getTemplatedDecl();
const CXXRecordDecl *ChildSpec =
dyn_cast<CXXRecordDecl>(&findDeclWithTemplateArgs(AST, "Child<int>"));
EXPECT_THAT(typeParents(Child), ElementsAre());
EXPECT_THAT(typeParents(ChildSpec), ElementsAre(Parent));
}
TEST(TypeParents, DependentBase) {
Annotations Source(R"cpp(
template <typename T>
struct Parent {};
template <typename T>
struct Child1 : Parent<T> {};
template <typename T>
struct Child2 : Parent<T>::Type {};
template <typename T>
struct Child3 : T {};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
const CXXRecordDecl *Parent =
dyn_cast<ClassTemplateDecl>(&findDecl(AST, "Parent"))->getTemplatedDecl();
const CXXRecordDecl *Child1 =
dyn_cast<ClassTemplateDecl>(&findDecl(AST, "Child1"))->getTemplatedDecl();
const CXXRecordDecl *Child2 =
dyn_cast<ClassTemplateDecl>(&findDecl(AST, "Child2"))->getTemplatedDecl();
const CXXRecordDecl *Child3 =
dyn_cast<ClassTemplateDecl>(&findDecl(AST, "Child3"))->getTemplatedDecl();
// For "Parent<T>", use the primary template as a best-effort guess.
EXPECT_THAT(typeParents(Child1), ElementsAre(Parent));
// For "Parent<T>::Type", there is nothing we can do.
EXPECT_THAT(typeParents(Child2), ElementsAre());
// Likewise for "T".
EXPECT_THAT(typeParents(Child3), ElementsAre());
}
TEST(TypeParents, IncompleteClass) {
Annotations Source(R"cpp(
class Incomplete;
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
const CXXRecordDecl *Incomplete =
dyn_cast<CXXRecordDecl>(&findDecl(AST, "Incomplete"));
EXPECT_THAT(typeParents(Incomplete), IsEmpty());
}
// Parts of getTypeHierarchy() are tested in more detail by the
// FindRecordTypeAt.* and TypeParents.* tests above. This test exercises the
// entire operation.
TEST(TypeHierarchy, Parents) {
Annotations Source(R"cpp(
struct $Parent1Def[[Parent1]] {
int a;
};
struct $Parent2Def[[Parent2]] {
int b;
};
struct $Parent3Def[[Parent3]] : Parent2 {
int c;
};
struct Ch^ild : Parent1, Parent3 {
int d;
};
int main() {
Ch^ild ch^ild;
ch^ild.a = 1;
}
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
for (Position Pt : Source.points()) {
// Set ResolveLevels to 0 because it's only used for Children;
// for Parents, getTypeHierarchy() always returns all levels.
llvm::Optional<TypeHierarchyItem> Result = getTypeHierarchy(
AST, Pt, /*ResolveLevels=*/0, TypeHierarchyDirection::Parents);
ASSERT_TRUE(bool(Result));
EXPECT_THAT(
*Result,
AllOf(
withName("Child"), withKind(SymbolKind::Struct),
parents(AllOf(withName("Parent1"), withKind(SymbolKind::Struct),
selectionRangeIs(Source.range("Parent1Def")),
parents()),
AllOf(withName("Parent3"), withKind(SymbolKind::Struct),
selectionRangeIs(Source.range("Parent3Def")),
parents(AllOf(
withName("Parent2"), withKind(SymbolKind::Struct),
selectionRangeIs(Source.range("Parent2Def")),
parents()))))));
}
}
TEST(TypeHierarchy, RecursiveHierarchyUnbounded) {
Annotations Source(R"cpp(
template <int N>
struct $SDef[[S]] : S<N + 1> {};
S^<0> s; // error-ok
)cpp");
TestTU TU = TestTU::withCode(Source.code());
TU.ExtraArgs.push_back("-ftemplate-depth=10");
auto AST = TU.build();
// The compiler should produce a diagnostic for hitting the
// template instantiation depth.
ASSERT_TRUE(!AST.getDiagnostics()->empty());
// Make sure getTypeHierarchy() doesn't get into an infinite recursion.
// The parent is reported as "S" because "S<0>" is an invalid instantiation.
// We then iterate once more and find "S" again before detecting the
// recursion.
llvm::Optional<TypeHierarchyItem> Result = getTypeHierarchy(
AST, Source.points()[0], 0, TypeHierarchyDirection::Parents);
ASSERT_TRUE(bool(Result));
EXPECT_THAT(
*Result,
AllOf(withName("S<0>"), withKind(SymbolKind::Struct),
parents(
AllOf(withName("S"), withKind(SymbolKind::Struct),
selectionRangeIs(Source.range("SDef")),
parents(AllOf(withName("S"), withKind(SymbolKind::Struct),
selectionRangeIs(Source.range("SDef")),
parents()))))));
}
TEST(TypeHierarchy, RecursiveHierarchyBounded) {
Annotations Source(R"cpp(
template <int N>
struct $SDef[[S]] : S<N - 1> {};
template <>
struct S<0>{};
S$SRefConcrete^<2> s;
template <int N>
struct Foo {
S$SRefDependent^<N> s;
};)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
// Make sure getTypeHierarchy() doesn't get into an infinite recursion
// for either a concrete starting point or a dependent starting point.
llvm::Optional<TypeHierarchyItem> Result = getTypeHierarchy(
AST, Source.point("SRefConcrete"), 0, TypeHierarchyDirection::Parents);
ASSERT_TRUE(bool(Result));
EXPECT_THAT(
*Result,
AllOf(withName("S<2>"), withKind(SymbolKind::Struct),
parents(AllOf(
withName("S<1>"), withKind(SymbolKind::Struct),
selectionRangeIs(Source.range("SDef")),
parents(AllOf(withName("S<0>"), withKind(SymbolKind::Struct),
parents()))))));
Result = getTypeHierarchy(AST, Source.point("SRefDependent"), 0,
TypeHierarchyDirection::Parents);
ASSERT_TRUE(bool(Result));
EXPECT_THAT(
*Result,
AllOf(withName("S"), withKind(SymbolKind::Struct),
parents(AllOf(withName("S"), withKind(SymbolKind::Struct),
selectionRangeIs(Source.range("SDef")), parents()))));
}
TEST(TypeHierarchy, DeriveFromImplicitSpec) {
Annotations Source(R"cpp(
template <typename T>
struct Parent {};
struct Child1 : Parent<int> {};
struct Child2 : Parent<char> {};
Parent<int> Fo^o;
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
auto Index = TU.index();
llvm::Optional<TypeHierarchyItem> Result = getTypeHierarchy(
AST, Source.points()[0], 2, TypeHierarchyDirection::Children, Index.get(),
testPath(TU.Filename));
ASSERT_TRUE(bool(Result));
EXPECT_THAT(*Result,
AllOf(withName("Parent"), withKind(SymbolKind::Struct),
children(AllOf(withName("Child1"),
withKind(SymbolKind::Struct), children()),
AllOf(withName("Child2"),
withKind(SymbolKind::Struct), children()))));
}
TEST(TypeHierarchy, DeriveFromPartialSpec) {
Annotations Source(R"cpp(
template <typename T> struct Parent {};
template <typename T> struct Parent<T*> {};
struct Child : Parent<int*> {};
Parent<int> Fo^o;
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
auto Index = TU.index();
llvm::Optional<TypeHierarchyItem> Result = getTypeHierarchy(
AST, Source.points()[0], 2, TypeHierarchyDirection::Children, Index.get(),
testPath(TU.Filename));
ASSERT_TRUE(bool(Result));
EXPECT_THAT(*Result, AllOf(withName("Parent"), withKind(SymbolKind::Struct),
children()));
}
TEST(TypeHierarchy, DeriveFromTemplate) {
Annotations Source(R"cpp(
template <typename T>
struct Parent {};
template <typename T>
struct Child : Parent<T> {};
Parent<int> Fo^o;
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
auto Index = TU.index();
// FIXME: We'd like this to show the implicit specializations Parent<int>
// and Child<int>, but currently libIndex does not expose relationships
// between implicit specializations.
llvm::Optional<TypeHierarchyItem> Result = getTypeHierarchy(
AST, Source.points()[0], 2, TypeHierarchyDirection::Children, Index.get(),
testPath(TU.Filename));
ASSERT_TRUE(bool(Result));
EXPECT_THAT(*Result,
AllOf(withName("Parent"), withKind(SymbolKind::Struct),
children(AllOf(withName("Child"),
withKind(SymbolKind::Struct), children()))));
}
TEST(TypeHierarchy, Preamble) {
Annotations SourceAnnotations(R"cpp(
struct Ch^ild : Parent {
int b;
};)cpp");
Annotations HeaderInPreambleAnnotations(R"cpp(
struct [[Parent]] {
int a;
};)cpp");
TestTU TU = TestTU::withCode(SourceAnnotations.code());
TU.HeaderCode = HeaderInPreambleAnnotations.code().str();
auto AST = TU.build();
llvm::Optional<TypeHierarchyItem> Result = getTypeHierarchy(
AST, SourceAnnotations.point(), 1, TypeHierarchyDirection::Parents);
ASSERT_TRUE(Result);
EXPECT_THAT(
*Result,
AllOf(withName("Child"),
parents(AllOf(withName("Parent"),
selectionRangeIs(HeaderInPreambleAnnotations.range()),
parents()))));
}
SymbolID findSymbolIDByName(SymbolIndex *Index, llvm::StringRef Name,
llvm::StringRef TemplateArgs = "") {
SymbolID Result;
FuzzyFindRequest Request;
Request.Query = std::string(Name);
Request.AnyScope = true;
bool GotResult = false;
Index->fuzzyFind(Request, [&](const Symbol &S) {
if (TemplateArgs == S.TemplateSpecializationArgs) {
EXPECT_FALSE(GotResult);
Result = S.ID;
GotResult = true;
}
});
EXPECT_TRUE(GotResult);
return Result;
}
std::vector<SymbolID> collectSubtypes(SymbolID Subject, SymbolIndex *Index) {
std::vector<SymbolID> Result;
RelationsRequest Req;
Req.Subjects.insert(Subject);
Req.Predicate = RelationKind::BaseOf;
Index->relations(Req,
[&Result](const SymbolID &Subject, const Symbol &Object) {
Result.push_back(Object.ID);
});
return Result;
}
TEST(Subtypes, SimpleInheritance) {
Annotations Source(R"cpp(
struct Parent {};
struct Child1a : Parent {};
struct Child1b : Parent {};
struct Child2 : Child1a {};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto Index = TU.index();
SymbolID Parent = findSymbolIDByName(Index.get(), "Parent");
SymbolID Child1a = findSymbolIDByName(Index.get(), "Child1a");
SymbolID Child1b = findSymbolIDByName(Index.get(), "Child1b");
SymbolID Child2 = findSymbolIDByName(Index.get(), "Child2");
EXPECT_THAT(collectSubtypes(Parent, Index.get()),
UnorderedElementsAre(Child1a, Child1b));
EXPECT_THAT(collectSubtypes(Child1a, Index.get()), ElementsAre(Child2));
}
TEST(Subtypes, MultipleInheritance) {
Annotations Source(R"cpp(
struct Parent1 {};
struct Parent2 {};
struct Parent3 : Parent2 {};
struct Child : Parent1, Parent3 {};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto Index = TU.index();
SymbolID Parent1 = findSymbolIDByName(Index.get(), "Parent1");
SymbolID Parent2 = findSymbolIDByName(Index.get(), "Parent2");
SymbolID Parent3 = findSymbolIDByName(Index.get(), "Parent3");
SymbolID Child = findSymbolIDByName(Index.get(), "Child");
EXPECT_THAT(collectSubtypes(Parent1, Index.get()), ElementsAre(Child));
EXPECT_THAT(collectSubtypes(Parent2, Index.get()), ElementsAre(Parent3));
EXPECT_THAT(collectSubtypes(Parent3, Index.get()), ElementsAre(Child));
}
TEST(Subtypes, ClassTemplate) {
Annotations Source(R"cpp(
struct Parent {};
template <typename T>
struct Child : Parent {};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto Index = TU.index();
SymbolID Parent = findSymbolIDByName(Index.get(), "Parent");
SymbolID Child = findSymbolIDByName(Index.get(), "Child");
EXPECT_THAT(collectSubtypes(Parent, Index.get()), ElementsAre(Child));
}
TEST(Subtypes, TemplateSpec1) {
Annotations Source(R"cpp(
template <typename T>
struct Parent {};
template <>
struct Parent<int> {};
struct Child1 : Parent<float> {};
struct Child2 : Parent<int> {};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto Index = TU.index();
SymbolID Parent = findSymbolIDByName(Index.get(), "Parent");
SymbolID ParentSpec = findSymbolIDByName(Index.get(), "Parent", "<int>");
SymbolID Child1 = findSymbolIDByName(Index.get(), "Child1");
SymbolID Child2 = findSymbolIDByName(Index.get(), "Child2");
EXPECT_THAT(collectSubtypes(Parent, Index.get()), ElementsAre(Child1));
EXPECT_THAT(collectSubtypes(ParentSpec, Index.get()), ElementsAre(Child2));
}
TEST(Subtypes, TemplateSpec2) {
Annotations Source(R"cpp(
struct Parent {};
template <typename T>
struct Child {};
template <>
struct Child<int> : Parent {};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto Index = TU.index();
SymbolID Parent = findSymbolIDByName(Index.get(), "Parent");
SymbolID ChildSpec = findSymbolIDByName(Index.get(), "Child", "<int>");
EXPECT_THAT(collectSubtypes(Parent, Index.get()), ElementsAre(ChildSpec));
}
TEST(Subtypes, DependentBase) {
Annotations Source(R"cpp(
template <typename T>
struct Parent {};
template <typename T>
struct Child : Parent<T> {};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto Index = TU.index();
SymbolID Parent = findSymbolIDByName(Index.get(), "Parent");
SymbolID Child = findSymbolIDByName(Index.get(), "Child");
EXPECT_THAT(collectSubtypes(Parent, Index.get()), ElementsAre(Child));
}
TEST(Subtypes, LazyResolution) {
Annotations Source(R"cpp(
struct P^arent {};
struct Child1 : Parent {};
struct Child2a : Child1 {};
struct Child2b : Child1 {};
)cpp");
TestTU TU = TestTU::withCode(Source.code());
auto AST = TU.build();
auto Index = TU.index();
llvm::Optional<TypeHierarchyItem> Result = getTypeHierarchy(
AST, Source.point(), /*ResolveLevels=*/1,
TypeHierarchyDirection::Children, Index.get(), testPath(TU.Filename));
ASSERT_TRUE(bool(Result));
EXPECT_THAT(
*Result,
AllOf(withName("Parent"), withKind(SymbolKind::Struct),
parentsNotResolved(),
children(AllOf(withName("Child1"), withKind(SymbolKind::Struct),
parentsNotResolved(), childrenNotResolved()))));
resolveTypeHierarchy((*Result->children)[0], /*ResolveLevels=*/1,
TypeHierarchyDirection::Children, Index.get());
EXPECT_THAT(
(*Result->children)[0],
AllOf(withName("Child1"), withKind(SymbolKind::Struct),
parentsNotResolved(),
children(AllOf(withName("Child2a"), withKind(SymbolKind::Struct),
parentsNotResolved(), childrenNotResolved()),
AllOf(withName("Child2b"), withKind(SymbolKind::Struct),
parentsNotResolved(), childrenNotResolved()))));
}
} // namespace
} // namespace clangd
} // namespace clang
|
#include <iostream>
using namespace std;
class Begin101
{
private:
int i,k;
string s;
public:
Begin101()
{
cin>>s>>k;
for(i=0;i<k;i++)
{cout<<s[s.length()-k+i];}
}
};
int main() {
Begin101 b;
return 0;
}
|
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// 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.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
*****************************************************************************
*
* File: Globals.cpp
* Description: CLI globals. For each process that uses the CLI there
* should be exactly one object of type CliGlobals.
*
* Created: 7/10/95
* Language: C++
*
*
*
*
*****************************************************************************
*/
// -----------------------------------------------------------------------
#include "Platform.h"
#include <stdlib.h>
#include <sys/syscall.h>
#include "cli_stdh.h"
#include "Ipc.h"
#include "ex_stdh.h"
#include "ex_frag_rt.h"
#include "memorymonitor.h"
#include "ExStats.h"
#include "ExUdrServer.h"
#include "ExSqlComp.h"
#include "ExControlArea.h"
#include "Context.h"
#include "ex_transaction.h"
#include "Statement.h"
#include "ex_root.h"
#include "ComRtUtils.h"
#include <semaphore.h>
#include <pthread.h>
#include "HBaseClient_JNI.h"
#include "HdfsClient_JNI.h"
#include "HiveClient_JNI.h"
#include "LmLangManagerC.h"
#include "LmLangManagerJava.h"
#include "CliSemaphore.h"
#include "ExCextdecs.h"
CliGlobals * cli_globals = NULL;
CLISemaphore globalSemaphore ;
#include "CmpContext.h"
CliGlobals::CliGlobals(NABoolean espProcess)
: inConstructor_(TRUE),
executorMemory_((const char *)"Global Executor Memory"),
contextList_(NULL),
envvars_(NULL),
envvarsContext_(0),
sharedArkcmp_(NULL),
arkcmpInitFailed_(arkcmpIS_OK_),
processIsStopping_(FALSE),
totalCliCalls_(0),
savedCompilerVersion_ (COM_VERS_COMPILER_VERSION),
globalSbbCount_(0),
priorityChanged_(FALSE),
currRootTcb_(NULL),
processStats_(NULL),
savedPriority_(148), // Set it to some valid priority to start with
tidList_(NULL),
cliSemaphore_(NULL),
defaultContext_(NULL),
langManC_(NULL),
langManJava_(NULL)
, myVerifier_(-1)
, espProcess_(espProcess)
{
globalsAreInitialized_ = FALSE;
executorMemory_.setThreadSafe();
init(espProcess, NULL);
globalsAreInitialized_ = TRUE;
}
void CliGlobals::init( NABoolean espProcess,
StatsGlobals *statsGlobals
)
{
int threadCount = NAAssertMutexCreate();
if (threadCount != 1) // The main executor thread must be first
abort();
SQLMXLoggingArea::init();
#if !(defined(__SSCP) || defined(__SSMP))
sharedCtrl_ = new(&executorMemory_) ExControlArea(NULL /*context */,
&executorMemory_);
#else
sharedCtrl_ = NULL;
#endif
char *_sqptr = 0;
_sqptr = new (&executorMemory_) char[10];
numCliCalls_ = 0;
nodeName_[0] = '\0';
breakEnabled_ = FALSE;
SPBreakReceived_ = FALSE;
isESPProcess_ = FALSE;
logReclaimEventDone_ = FALSE;
// find and initialize the directory this program is being run from.
// Max length of oss dirname is 1K (process_getinfolist_ limit).
// Also initialize the node, cpu and pin my process is running at.
programDir_ = new (&executorMemory_) char[1024 + 1];
short nodeNameLen;
Lng32 retcomrt = 0;
retcomrt = ComRtGetProgramInfo(programDir_, 1024, processType_,
myCpu_, myPin_,
myNodeNumber_, myNodeName_, nodeNameLen,
myStartTime_, myProcessNameString_,
parentProcessNameString_
, &myVerifier_
);
if (retcomrt)
{
char errStr[128];
sprintf (errStr, "Could not initialize CLI globals.ComRtGetProgramInfo returned an error :%d.", retcomrt);
ex_assert(0,errStr);
}
ComRtGetProcessPriority(myPriority_);
savedPriority_ = (short)myPriority_;
myNumCpus_ = ComRtGetCPUArray(cpuArray_, (NAHeap *)&executorMemory_);
// create global structures for IPC environment
#if !(defined(__SSCP) || defined(__SSMP))
ipcHeap_ = new(&executorMemory_) NAHeap("IPC Heap",
NAMemory::IPC_MEMORY, 2048 * 1024);
ipcHeap_->setThreadSafe();
if (! espProcess)
{
// Create the process global ARKCMP server.
sharedArkcmp_ = NULL;
nextUniqueContextHandle = DEFAULT_CONTEXT_HANDLE;
lastUniqueNumber_ = 0;
sessionUniqueNumber_ = 0;
// It is not thread safe to set the globals cli_globals
// before cli_globals is fully initialized, but it is being done
// here because the code below expects it
cli_globals = this;
int error;
statsGlobals_ = (StatsGlobals *)shareStatsSegment(shmId_);
if (statsGlobals_ == NULL
|| (statsGlobals_ != NULL &&
statsGlobals_->getVersion() != StatsGlobals::CURRENT_SHARED_OBJECTS_VERSION_))
{
statsGlobals_ = NULL;
statsHeap_ = new (getExecutorMemory())
NAHeap("Process Stats Heap", getExecutorMemory(),
8192,
0);
statsHeap_->setThreadSafe();
}
else
{
error = statsGlobals_->openStatsSemaphore(semId_);
// Behave like as if stats is not available
if (error != 0)
{
statsGlobals_ = NULL;
statsHeap_ = getExecutorMemory();
}
else
{
error = statsGlobals_->getStatsSemaphore(semId_, myPin_);
statsHeap_ = (NAHeap *)statsGlobals_->
getStatsHeap()->allocateHeapMemory(sizeof *statsHeap_, FALSE);
// The following assertion may be hit if the RTS shared memory
// segment is full. The stop catcher code will be responsible
// for releasing the RTS semaphore.
ex_assert(statsHeap_, "allocateHeapMemory returned NULL.");
// This next allocation, a placement "new" will not fail.
statsHeap_ = new (statsHeap_, statsGlobals_->getStatsHeap())
NAHeap("Process Stats Heap", statsGlobals_->getStatsHeap(),
8192,
0);
statsGlobals_->addProcess(myPin_, statsHeap_);
processStats_ = statsGlobals_->getExProcessStats(myPin_);
processStats_->setStartTime(myStartTime_);
statsGlobals_->releaseStatsSemaphore(semId_, myPin_);
}
}
// create a default context and make it the current context
cliSemaphore_ = new (&executorMemory_) CLISemaphore();
defaultContext_ = new (&executorMemory_) ContextCli(this);
contextList_ = new(&executorMemory_) HashQueue(&executorMemory_);
tidList_ = new(&executorMemory_) HashQueue(&executorMemory_);
SQLCTX_HANDLE ch = defaultContext_->getContextHandle();
contextList_->insert((char*)&ch, sizeof(SQLCTX_HANDLE), (void*)defaultContext_);
if (statsGlobals_ != NULL)
memMonitor_ = statsGlobals_->getMemoryMonitor();
else
{
// create the process global memory monitor. For now with
// defaults of 10 window entries and sampling every 1 second
Lng32 memMonitorWindowSize = 10;
Lng32 memMonitorSampleInterval = 1; // reduced from 10 (for M5 - May 2011)
memMonitor_ = new (&executorMemory_) MemoryMonitor(memMonitorWindowSize,
memMonitorSampleInterval,
&executorMemory_);
}
} // (!espProcess)
else
{
// For ESPs do not create the default context here. At this point
// the ESP has not created an IpcEnvironment object yet so the
// result context will have an invalid ExSqlComp object that
// points to a NULL IpcEnvironment. In bin/ex_esp_main.cpp, the
// following objects are created at ESP startup time:
// - CliGlobals
// - IpcEnvironment
// - Default ContextCli in CliGlobals
// - MemoryMonitor
// - ExEspFragInstanceDir
// - ExEspControl Message
// - Global UDR server manager
cliSemaphore_ = new (&executorMemory_) CLISemaphore();
statsGlobals_ = NULL;
semId_ = -1;
statsHeap_ = NULL;
lastUniqueNumber_ = 0;
} // if (!espProcess) else ...
#else // (defined(__SSCP) || defined(__SSMP))
cliSemaphore_ = new (&executorMemory_) CLISemaphore();
statsGlobals_ = statsGlobals;
semId_ = -1;
statsHeap_ = NULL;
lastUniqueNumber_ = 0;
#endif
inConstructor_ = FALSE;
//
// could initialize the program file name here but ...
myProgName_[0] = '\0';
}
CliGlobals::~CliGlobals()
{
arkcmpInitFailed_ = arkcmpERROR_; // (it's corrupt after deleting, anyway...)
short error ;
if (sharedArkcmp_)
{
delete sharedArkcmp_;
sharedArkcmp_ = NULL;
}
if (statsGlobals_ != NULL)
{
error = statsGlobals_->getStatsSemaphore(semId_, myPin_);
statsGlobals_->removeProcess(myPin_);
statsGlobals_->releaseStatsSemaphore(semId_, myPin_);
sem_close((sem_t *)semId_);
}
}
Lng32 CliGlobals::getNextUniqueContextHandle()
{
Lng32 contextHandle;
cliSemaphore_->get();
contextHandle = nextUniqueContextHandle++;
cliSemaphore_->release();
return contextHandle;
}
IpcPriority CliGlobals::myCurrentPriority()
{
IpcPriority myPriority;
Lng32 retcode = ComRtGetProcessPriority(myPriority);
if (retcode)
return -2;
return myPriority;
}
// NOTE: Unlike REFPARAM_BOUNDSCHECK, this method does not verify that
// the pointer "startAddress" actually points to a valid address
// in the user address space (means that dereferencing the
// pointer may cause a segmentation violation).
//
// Here are some DEFINEs from files DMEM and JMEMH in product T9050 that
// perform the PRIV address check:
// LOG2_BYTES_IN_T16PAGE = 11, ! 2048 bytes in a T16 page size
// LOG2_T16PAGES_IN_SEGMENT = 6, ! 64 T16 pages in a segment
// LOG2_BYTES_IN_SEGMENT = LOG2_BYTES_IN_T16PAGE +
// LOG2_T16PAGES_IN_SEGMENT,
// SYSTEMDATASEG = 1, ! System Data Segment (always absolute segment 1)
//
// #define ADDR_IS_IN_KSEG0_1_2( a ) \
// ( (int32) (a) < 0 )
//
// #define ADDR_IS_PRIV(a) (ADDR_IS_IN_KSEG0_1_2(a) \
// || ((vaddr_t)(a) >> LOG2_BYTES_IN_SEGMENT) == SYSTEMDATASEG)
//
// NOTE: we'll need to recompile if the NSK architecture changes, which
// should be infrequent as Charles Landau assures me.
Lng32 CliGlobals::boundsCheck(void *startAddress,
ULng32 length,
Lng32 &retcode)
{
// no bounds checking on NT because we're not PRIV
return 0;
}
NAHeap *CliGlobals::getIpcHeap()
{
return currContext()->getIpcHeap();
}
IpcEnvironment *CliGlobals::getEnvironment()
{
ContextCli *currentContext = currContext();
if (currentContext != NULL)
return currentContext->getEnvironment();
else
return NULL;
}
ExEspManager *CliGlobals::getEspManager()
{
return currContext()->getEspManager();
}
ExSsmpManager *CliGlobals::getSsmpManager()
{
return currContext()->getSsmpManager();
}
LmLanguageManager * CliGlobals::getLanguageManager(ComRoutineLanguage language)
{
switch (language)
{
case COM_LANGUAGE_JAVA:
return getLanguageManagerJava();
break;
case COM_LANGUAGE_C:
case COM_LANGUAGE_CPP:
return getLanguageManagerC();
break;
default:
ex_assert(0, "Invalid language in CliGlobals::getLanguageManager()");
}
return NULL;
}
LmLanguageManagerC * CliGlobals::getLanguageManagerC()
{
if (!langManC_)
{
LmResult result;
langManC_ = new(&executorMemory_)
LmLanguageManagerC(result,
FALSE,
&(currContext()->diags()));
if (result != LM_OK)
{
delete langManC_;
langManC_ = NULL;
}
}
return langManC_;
}
LmLanguageManagerJava * CliGlobals::getLanguageManagerJava()
{
if (!langManJava_)
{
LmResult result;
langManJava_ = new(&executorMemory_)
LmLanguageManagerJava(result,
FALSE,
1,
NULL, // Java options should have been
// provided for earlier JNI calls
// in Trafodion
&(currContext()->diags()));
if (result != LM_OK)
{
delete langManJava_;
langManJava_ = NULL;
}
}
return langManJava_;
}
ExeTraceInfo *CliGlobals::getExeTraceInfo()
{
return currContext()->getExeTraceInfo();
}
ExSqlComp * CliGlobals::getArkcmp(short index)
{
//return sharedArkcmp_;
return currContext()->getArkcmp(index);
}
CliGlobals * CliGlobals::createCliGlobals(NABoolean espProcess)
{
CliGlobals *result;
result = new CliGlobals(espProcess);
//pthread_key_create(&thread_key, SQ_CleanupThread);
cli_globals = result;
return result;
}
void * CliGlobals::getSegmentStartAddrOnNSK()
{
// this method should only be called on NSK, return NULL on other platforms
return NULL;
}
CliGlobals *GetCliGlobals()
{ return cli_globals; }
// used by ESP only
void CliGlobals::initiateDefaultContext()
{
// create a default context and make it the current context
defaultContext_ = new (&executorMemory_) ContextCli(this);
contextList_ = new(&executorMemory_) HashQueue(&executorMemory_);
tidList_ = new(&executorMemory_) HashQueue(&executorMemory_);
cliSemaphore_ = new (&executorMemory_) CLISemaphore();
SQLCTX_HANDLE ch = defaultContext_->getContextHandle();
contextList_->insert((char*)&ch, sizeof(SQLCTX_HANDLE),
(void*)defaultContext_);
}
ContextCli *CliGlobals::currContext()
{
if (tsCurrentContextMap == NULL ||
tsCurrentContextMap->context_ == NULL)
{
tsCurrentContextMap = getThreadContext(syscall(SYS_gettid));
//pthread_setspecific(thread_key, tsCurrentContextMap);
if (tsCurrentContextMap == NULL)
return defaultContext_;
}
return tsCurrentContextMap->context_;
}
Lng32 CliGlobals::createContext(ContextCli* &newContext)
{
newContext = new (&executorMemory_) ContextCli(this);
SQLCTX_HANDLE ch = newContext->getContextHandle();
cliSemaphore_->get();
contextList_->insert((char*)&ch, sizeof(SQLCTX_HANDLE), (void*)newContext);
cliSemaphore_->release();
return 0;
}
Lng32 CliGlobals::dropContext(ContextCli* context)
{
if (!context)
return -1;
if (context == getDefaultContext())
return 0;
CLISemaphore *tmpSemaphore = context->getSemaphore();
tmpSemaphore->get();
try
{
context->deleteMe();
}
catch (...)
{
tmpSemaphore->release();
return -1;
}
tmpSemaphore->release();
pid_t tid = syscall(SYS_gettid);
cliSemaphore_->get();
contextList_->remove((void*)context);
tidList_->position();
ContextTidMap *contextTidMap;
while ((contextTidMap = (ContextTidMap *)tidList_->getNext()) != NULL)
{
if (contextTidMap->context_ == context)
{
if (contextTidMap->tid_ == tid)
{
tidList_->remove((char*)&contextTidMap->tid_, sizeof(pid_t),
contextTidMap);
NADELETE(contextTidMap, ContextTidMap, getExecutorMemory());
tsCurrentContextMap = NULL;
}
else
contextTidMap->context_ = NULL;
}
}
delete context;
cliSemaphore_->release();
return 0;
}
ContextCli * CliGlobals::getContext(SQLCTX_HANDLE context_handle,
NABoolean calledFromDrop)
{
ContextCli * context;
cliSemaphore_->get();
contextList_->position((char*)&context_handle, sizeof(SQLCTX_HANDLE));
while ((context = (ContextCli *)contextList_->getNext()) != NULL)
{
if (context_handle == context->getContextHandle())
{
if (context->isDropInProgress())
context = NULL;
else if (calledFromDrop)
context->setDropInProgress();
cliSemaphore_->release();
return context;
}
}
cliSemaphore_->release();
return NULL;
}
ContextTidMap * CliGlobals::getThreadContext(pid_t tid)
{
SQLCTX_HANDLE ch;
ContextTidMap *contextTidMap;
if (tidList_ == NULL)
return NULL;
cliSemaphore_->get();
tidList_->position((char*)&tid, sizeof(pid_t));
while ((contextTidMap = (ContextTidMap *)tidList_->getNext()) != NULL)
{
if (contextTidMap->tid_ == tid)
{
if (contextTidMap->context_ == NULL)
{
NADELETE(contextTidMap, ContextTidMap, getExecutorMemory());
tidList_->remove((char*)&tid, sizeof(pid_t), contextTidMap);
contextTidMap = NULL;
}
cliSemaphore_->release();
return contextTidMap;
}
}
cliSemaphore_->release();
return NULL;
}
Lng32 CliGlobals::switchContext(ContextCli * newContext)
{
Lng32 retcode;
pid_t tid;
SQLCTX_HANDLE ch, currCh;
tid = syscall(SYS_gettid);
if (newContext != defaultContext_ &&
tsCurrentContextMap != NULL &&
newContext == tsCurrentContextMap->context_)
return 0;
retcode = currContext()->getTransaction()->suspendTransaction();
if (retcode != 0)
return retcode;
cliSemaphore_->get();
tidList_->position((char*)&tid, sizeof(pid_t));
ContextTidMap *contextTidMap;
NABoolean tidFound = FALSE;
while ((contextTidMap = (ContextTidMap *)tidList_->getNext()) != NULL)
{
if (tid == contextTidMap->tid_)
{
contextTidMap->context_ = newContext;
tidFound = TRUE;
tsCurrentContextMap = contextTidMap;
break;
}
}
if (! tidFound)
{
contextTidMap = new (getExecutorMemory()) ContextTidMap(tid, newContext);
tidList_->insert((char *)&tid, sizeof(pid_t), (void *)contextTidMap);
tsCurrentContextMap = contextTidMap;
}
cliSemaphore_->release();
retcode = currContext()->getTransaction()->resumeTransaction();
return retcode;
}
Lng32 CliGlobals::sendEnvironToMxcmp()
{
ComDiagsArea & diags = currContext()->diags();
if (NOT getArkcmp()->isConnected())
return 0;
// send the current environment to mxcmp
ExSqlComp::ReturnStatus sendStatus =
getArkcmp()->sendRequest(CmpMessageObj::ENVS_REFRESH, NULL,0);
if (sendStatus != ExSqlComp::SUCCESS)
{
if (sendStatus == ExSqlComp::ERROR)
{
diags << DgSqlCode(-CLI_SEND_REQUEST_ERROR)
<< DgString0("SET ENVIRON");
return -CLI_SEND_REQUEST_ERROR;
// return SQLCLI_ReturnCode(&currContext,-CLI_SEND_REQUEST_ERROR);
}
//else
// retcode = WARNING;
}
if (getArkcmp()->status() != ExSqlComp::FINISHED)
{
diags << DgSqlCode(-CLI_IO_REQUESTS_PENDING)
<< DgString0("SET ENVIRON");
return -CLI_IO_REQUESTS_PENDING;
//return SQLCLI_ReturnCode(&currContext,-CLI_IO_REQUESTS_PENDING);
}
return 0;
}
Lng32 CliGlobals::setEnvVars(char ** envvars)
{
if ((! envvars) || (isESPProcess_))
return 0;
Int32 nEnvs = 0;
if (envvars_)
{
// deallocate the current set of envvars
ipcHeap_->deallocateMemory(envvars_);
envvars_ = NULL;
}
for (nEnvs=0; envvars[nEnvs]; nEnvs++);
// one extra to null terminate envvar list
Lng32 envvarsLen = (nEnvs + 1) * sizeof(char*);
Int32 count;
for (count=0; count < nEnvs; count++)
{
envvarsLen += str_len(envvars[count])+1;
}
// allocate contiguous space for envvars
envvars_ = (char**)(new(ipcHeap_) char[envvarsLen]);
char * envvarsValue = (char *)envvars_ + (nEnvs + 1) * sizeof(char*);
// and copy input envvars to envvars_
for (count=0; count < nEnvs; count++)
{
envvars_[count] = envvarsValue;
Lng32 l = str_len(envvars[count])+1;
str_cpy_all(envvarsValue, envvars[count], l);
envvarsValue = envvarsValue + l;
}
envvars_[nEnvs] = 0;
// also set it in IpcEnvironment so it could be used to send
// it to mxcmp.
getEnvironment()->setEnvVars(envvars_);
getEnvironment()->setEnvVarsLen(envvarsLen);
envvarsContext_++;
return sendEnvironToMxcmp();
}
Lng32 CliGlobals::setEnvVar(const char * name, const char * value,
NABoolean reset)
{
if ((! name) || (! value) || (isESPProcess_))
return 0;
NABoolean found = FALSE;
Lng32 envvarPos = -1;
if (ComRtGetEnvValueFromEnvvars((const char**)envvars_, name, &envvarPos))
found = TRUE;
if ((NOT found) && (reset))
return 0;
Int32 nEnvs = 0;
if (envvars_)
{
for (nEnvs=0; envvars_[nEnvs]; nEnvs++);
}
if (reset)
{
// nEnvs--;
}
else if (NOT found)
{
envvarPos = nEnvs;
nEnvs++;
}
// one extra entry, if envvar not found.
// one extra to null terminate envvar list.
// long envvarsLen = (nEnvs + (NOT found ? 1 : 0) + 1) * sizeof(char*);
Lng32 newEnvvarsLen = (nEnvs + 1) * sizeof(char*);
Int32 count;
for (count=0; count < nEnvs; count++)
{
if (count == envvarPos)
// if ((found) && (count == envvarPos))
{
if (NOT reset)
newEnvvarsLen += strlen(name) + strlen("=") + strlen(value) + 1;
}
else if (NULL != envvars_)
newEnvvarsLen += str_len(envvars_[count])+1;
}
/* if (NOT found)
{
nEnvs++;
newEnvvarsLen += strlen(name) + strlen("=") + strlen(value) + 1;
}
*/
// allocate contiguous space for envvars
char ** newEnvvars = (char**)(new(ipcHeap_) char[newEnvvarsLen]);
char * newEnvvarsValue =
(char*)(newEnvvars +
((reset ? (nEnvs-1) : nEnvs) + 1));
// and copy envvars_ to newEnvvars
Int32 tgtCount = 0;
for (count=0; count < nEnvs; count++)
{
newEnvvars[tgtCount] = newEnvvarsValue;
Lng32 l = 0;
if (count == envvarPos)
{
if (NOT reset)
{
strcpy(newEnvvarsValue, name);
strcat(newEnvvarsValue, "=");
strcat(newEnvvarsValue, value);
l = strlen(name) + strlen("=") + strlen(value) + 1;
tgtCount++;
}
}
else if (NULL != envvars_)
{
l = str_len(envvars_[count])+1;
str_cpy_all(newEnvvarsValue, envvars_[count], l);
tgtCount++;
}
newEnvvarsValue = newEnvvarsValue + l;
}
if (reset)
{
nEnvs--;
}
newEnvvars[nEnvs] = 0;
if (envvars_)
{
// deallocate the current set of envvars
ipcHeap_->deallocateMemory(envvars_);
envvars_ = NULL;
}
envvars_ = newEnvvars;
// set or reset this envvar in SessionDefaults.
SessionEnvvar * se =
new(ipcHeap_) SessionEnvvar(ipcHeap_, (char*)name, (char*)value);
// remove if an entry exists
currContext()->getSessionDefaults()->sessionEnvvars()->remove(*se);
// insert a new entry, if this is not a RESET operation.
if (NOT reset)
{
currContext()->getSessionDefaults()->sessionEnvvars()->insert(*se);
}
delete se;
// also set it in IpcEnvironment so it could be used to send
// it to mxcmp.
getEnvironment()->setEnvVars(envvars_);
getEnvironment()->setEnvVarsLen(newEnvvarsLen);
envvarsContext_++;
// need to set the env to the embedded compiler too
if (currContext()->isEmbeddedArkcmpInitialized())
{
currContext()->getEmbeddedArkcmpContext()
->setArkcmpEnvDirect(name, value, reset);
}
return sendEnvironToMxcmp();
}
char * CliGlobals::getEnv(const char * name)
{
return (char*)ComRtGetEnvValueFromEnvvars((const char**)envvars_, name);
}
//
Lng32 CliGlobals::resetContext(ContextCli *theContext, void *contextMsg)
{
theContext->reset(contextMsg);
return SUCCESS;
}
NAHeap *CliGlobals::getCurrContextHeap()
{
return currContext()->exHeap();
}
ExUdrServerManager *CliGlobals::getUdrServerManager()
{ return currContext()->getUdrServerManager(); }
NABoolean CliGlobals::getUdrErrorChecksEnabled()
{ return currContext()->getUdrErrorChecksEnabled(); }
Lng32 CliGlobals::getUdrSQLAccessMode()
{ return currContext()->getUdrSQLAccessMode(); }
NABoolean CliGlobals::getUdrAccessModeViolation()
{ return currContext()->getUdrAccessModeViolation(); }
NABoolean CliGlobals::getUdrXactViolation()
{ return currContext()->getUdrXactViolation(); }
NABoolean CliGlobals::getUdrXactAborted()
{ return currContext()->getUdrXactAborted(); }
void CliGlobals::setUdrErrorChecksEnabled(NABoolean b)
{ currContext()->setUdrErrorChecksEnabled(b); }
void CliGlobals::setUdrSQLAccessMode(Lng32 mode)
{ currContext()->setUdrSQLAccessMode(mode); }
void CliGlobals::setUdrAccessModeViolation(NABoolean b)
{ currContext()->setUdrAccessModeViolation(b); }
void CliGlobals::setUdrXactViolation(NABoolean b)
{ currContext()->setUdrXactViolation(b); }
void CliGlobals::setUdrXactAborted(Int64 currTransId, NABoolean b)
{ currContext()->setUdrXactAborted(currTransId, b); }
void CliGlobals::clearUdrErrorFlags()
{ currContext()->clearUdrErrorFlags(); }
NABoolean CliGlobals::sqlAccessAllowed()
{ return currContext()->sqlAccessAllowed(); }
void CliGlobals::getUdrErrorFlags(NABoolean &sqlViolation,
NABoolean &xactViolation,
NABoolean &xactAborted)
{
currContext()->getUdrErrorFlags(sqlViolation, xactViolation,
xactAborted);
}
void CliGlobals::updateTransMode(TransMode *transMode)
{
currContext()->getTransaction()->getTransMode()->
updateTransMode(transMode);
}
void CliGlobals::initMyProgName()
{
char statusFileName[128];
FILE *status_file = 0;
size_t bytesRead, bytesCopy;
char buf[1024];
char *beginPtr, *endPtr;
sprintf(statusFileName, "/proc/%d/status",getpid());
status_file = fopen(statusFileName, "r");
if (status_file == NULL)
return; //ignore error and return
buf[0] = 0;
if (fseek(status_file, 0, SEEK_SET))
{
fclose(status_file);
return; //ignore error and return
}
bytesRead = fread(buf, 1, 1024, status_file);
if (ferror(status_file))
{
fclose(status_file);
return; //ignore error and return
}
fclose(status_file);
beginPtr = strstr(buf, "Name:\t");
if (!beginPtr)
return; //not found, return
beginPtr += 6;
endPtr = strstr(beginPtr, "\n");
if (!endPtr || beginPtr == endPtr)
return; //no name found, return
// myProgName_ is 64 bytes long, see Globals.h
bytesCopy = (endPtr - beginPtr) < PROGRAM_NAME_LEN ?
(endPtr - beginPtr) : PROGRAM_NAME_LEN - 1;
memcpy(myProgName_, beginPtr, bytesCopy);
*(myProgName_ + bytesCopy) = '\0'; // null terminates
}
#ifdef _DEBUG
// Delete the default context and all associated embedded CMP contexts
// This eventually causes dumping of all heap debug info if enabled
// Should ONLY be called right before process exits
void CliGlobals::deleteContexts()
{
if (defaultContext_)
{
defaultContext_->deleteMe();
delete defaultContext_;
defaultContext_ = NULL;
}
}
#endif // _DEBUG
// The unused BMO memory quota can now be utilized by the other
// BMO instances from the same or different fragment
// In case of ESP process, the unused memory quota is maintained
// at the default context. In case of master process, the ununsed
// memory quota is maintained in statement globals
NABoolean CliGlobals::grabMemoryQuotaIfAvailable(ULng32 size)
{
ContextCli *context;
if (espProcess_)
context = defaultContext_;
else
context = currContext();
return context->grabMemoryQuotaIfAvailable(size);
}
void CliGlobals::resetMemoryQuota()
{
ContextCli *context;
if (espProcess_)
context = defaultContext_;
else
context = currContext();
return context->resetMemoryQuota();
}
ULng32 CliGlobals::unusedMemoryQuota()
{
ContextCli *context;
if (espProcess_)
context = defaultContext_;
else
context = currContext();
return context->unusedMemoryQuota();
}
void CliGlobals::yieldMemoryQuota(ULng32 size)
{
ContextCli *context;
if (espProcess_)
context = defaultContext_;
else
context = currContext();
return context->yieldMemoryQuota(size);
}
void SQ_CleanupThread(void *arg)
{
HBaseClient_JNI::deleteInstance();
HiveClient_JNI::deleteInstance();
}
|
// Sieve of Eratosthenes
#include <vector>
#include <utility>
using namespace std;
using ll = long long;
/*snippet-begin*/
struct sieve {
const int maxn;
vector<int> f, primes;
sieve(int maxn) : maxn(maxn), f(maxn) {
for (int i=2; i<maxn; i++) {
if (f[i] == 0) {
f[i] = i;
primes.push_back(i);
}
for (int p : primes) {
if (p > f[i] || i * p >= maxn) {
break;
}
f[i*p] = p;
}
}
}
vector<pair<int, int>> factor_small(int x) const {
vector<pair<int, int>> v;
while (x > 1) {
int p = f[x], c = 0;
while (x % p == 0) {
x /= p;
c++;
}
v.emplace_back(p, c);
}
return v;
}
template<class T>
vector<pair<T, int>> factor(T x) const {
vector<pair<T, int>> v;
for (int p : primes) {
if ((ll)p*p > x) {
break;
}
if (x % p == 0) {
int c = 0;
while (x % p == 0) {
x /= p;
c++;
}
v.emplace_back(p, c);
}
}
if (x > 1) {
v.emplace_back(x, 1);
}
return v;
}
};
/*snippet-end*/
int main() {
sieve sv(1000);
return sv.primes.size() != 168;
}
|
// Copyright (c) 2017 The Zcash developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2018 The nint developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "torcontrol.cpp"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(torcontrol_tests)
void CheckSplitTorReplyLine(std::string input, std::string command, std::string args)
{
BOOST_TEST_MESSAGE(std::string("CheckSplitTorReplyLine(") + input + ")");
auto ret = SplitTorReplyLine(input);
BOOST_CHECK_EQUAL(ret.first, command);
BOOST_CHECK_EQUAL(ret.second, args);
}
BOOST_AUTO_TEST_CASE(util_SplitTorReplyLine)
{
// Data we should receive during normal usage
CheckSplitTorReplyLine(
"PROTOCOLINFO PIVERSION",
"PROTOCOLINFO", "PIVERSION");
CheckSplitTorReplyLine(
"AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE=\"/home/x/.tor/control_auth_cookie\"",
"AUTH", "METHODS=COOKIE,SAFECOOKIE COOKIEFILE=\"/home/x/.tor/control_auth_cookie\"");
CheckSplitTorReplyLine(
"AUTH METHODS=NULL",
"AUTH", "METHODS=NULL");
CheckSplitTorReplyLine(
"AUTH METHODS=HASHEDPASSWORD",
"AUTH", "METHODS=HASHEDPASSWORD");
CheckSplitTorReplyLine(
"VERSION Tor=\"0.2.9.8 (git-a0df013ea241b026)\"",
"VERSION", "Tor=\"0.2.9.8 (git-a0df013ea241b026)\"");
CheckSplitTorReplyLine(
"AUTHCHALLENGE SERVERHASH=aaaa SERVERNONCE=bbbb",
"AUTHCHALLENGE", "SERVERHASH=aaaa SERVERNONCE=bbbb");
// Other valid inputs
CheckSplitTorReplyLine("COMMAND", "COMMAND", "");
CheckSplitTorReplyLine("COMMAND SOME ARGS", "COMMAND", "SOME ARGS");
// These inputs are valid because PROTOCOLINFO accepts an OtherLine that is
// just an OptArguments, which enables multiple spaces to be present
// between the command and arguments.
CheckSplitTorReplyLine("COMMAND ARGS", "COMMAND", " ARGS");
CheckSplitTorReplyLine("COMMAND EVEN+more ARGS", "COMMAND", " EVEN+more ARGS");
}
void CheckParseTorReplyMapping(std::string input, std::map<std::string,std::string> expected)
{
BOOST_TEST_MESSAGE(std::string("CheckParseTorReplyMapping(") + input + ")");
auto ret = ParseTorReplyMapping(input);
BOOST_CHECK_EQUAL(ret.size(), expected.size());
auto r_it = ret.begin();
auto e_it = expected.begin();
while (r_it != ret.end() && e_it != expected.end()) {
BOOST_CHECK_EQUAL(r_it->first, e_it->first);
BOOST_CHECK_EQUAL(r_it->second, e_it->second);
r_it++;
e_it++;
}
}
BOOST_AUTO_TEST_CASE(util_ParseTorReplyMapping)
{
// Data we should receive during normal usage
CheckParseTorReplyMapping(
"METHODS=COOKIE,SAFECOOKIE COOKIEFILE=\"/home/x/.tor/control_auth_cookie\"", {
{"METHODS", "COOKIE,SAFECOOKIE"},
{"COOKIEFILE", "/home/x/.tor/control_auth_cookie"},
});
CheckParseTorReplyMapping(
"METHODS=NULL", {
{"METHODS", "NULL"},
});
CheckParseTorReplyMapping(
"METHODS=HASHEDPASSWORD", {
{"METHODS", "HASHEDPASSWORD"},
});
CheckParseTorReplyMapping(
"Tor=\"0.2.9.8 (git-a0df013ea241b026)\"", {
{"Tor", "0.2.9.8 (git-a0df013ea241b026)"},
});
CheckParseTorReplyMapping(
"SERVERHASH=aaaa SERVERNONCE=bbbb", {
{"SERVERHASH", "aaaa"},
{"SERVERNONCE", "bbbb"},
});
CheckParseTorReplyMapping(
"ServiceID=exampleonion1234", {
{"ServiceID", "exampleonion1234"},
});
CheckParseTorReplyMapping(
"PrivateKey=RSA1024:BLOB", {
{"PrivateKey", "RSA1024:BLOB"},
});
CheckParseTorReplyMapping(
"ClientAuth=bob:BLOB", {
{"ClientAuth", "bob:BLOB"},
});
// Other valid inputs
CheckParseTorReplyMapping(
"Foo=Bar=Baz Spam=Eggs", {
{"Foo", "Bar=Baz"},
{"Spam", "Eggs"},
});
CheckParseTorReplyMapping(
"Foo=\"Bar=Baz\"", {
{"Foo", "Bar=Baz"},
});
CheckParseTorReplyMapping(
"Foo=\"Bar Baz\"", {
{"Foo", "Bar Baz"},
});
// Escapes
CheckParseTorReplyMapping(
"Foo=\"Bar\\ Baz\"", {
{"Foo", "Bar Baz"},
});
CheckParseTorReplyMapping(
"Foo=\"Bar\\Baz\"", {
{"Foo", "BarBaz"},
});
CheckParseTorReplyMapping(
"Foo=\"Bar\\@Baz\"", {
{"Foo", "Bar@Baz"},
});
CheckParseTorReplyMapping(
"Foo=\"Bar\\\"Baz\" Spam=\"\\\"Eggs\\\"\"", {
{"Foo", "Bar\"Baz"},
{"Spam", "\"Eggs\""},
});
CheckParseTorReplyMapping(
"Foo=\"Bar\\\\Baz\"", {
{"Foo", "Bar\\Baz"},
});
// C escapes
CheckParseTorReplyMapping(
"Foo=\"Bar\\nBaz\\t\" Spam=\"\\rEggs\" Octals=\"\\1a\\11\\17\\18\\81\\377\\378\\400\\2222\" Final=Check", {
{"Foo", "Bar\nBaz\t"},
{"Spam", "\rEggs"},
{"Octals", "\1a\11\17\1" "881\377\37" "8\40" "0\222" "2"},
{"Final", "Check"},
});
CheckParseTorReplyMapping(
"Valid=Mapping Escaped=\"Escape\\\\\"", {
{"Valid", "Mapping"},
{"Escaped", "Escape\\"},
});
CheckParseTorReplyMapping(
"Valid=Mapping Bare=\"Escape\\\"", {});
CheckParseTorReplyMapping(
"OneOctal=\"OneEnd\\1\" TwoOctal=\"TwoEnd\\11\"", {
{"OneOctal", "OneEnd\1"},
{"TwoOctal", "TwoEnd\11"},
});
// Special handling for null case
// (needed because string comparison reads the null as end-of-string)
BOOST_TEST_MESSAGE(std::string("CheckParseTorReplyMapping(Null=\"\\0\")"));
auto ret = ParseTorReplyMapping("Null=\"\\0\"");
BOOST_CHECK_EQUAL(ret.size(), 1);
auto r_it = ret.begin();
BOOST_CHECK_EQUAL(r_it->first, "Null");
BOOST_CHECK_EQUAL(r_it->second.size(), 1);
BOOST_CHECK_EQUAL(r_it->second[0], '\0');
// A more complex valid grammar. PROTOCOLINFO accepts a VersionLine that
// takes a key=value pair followed by an OptArguments, making this valid.
// Because an OptArguments contains no semantic data, there is no point in
// parsing it.
CheckParseTorReplyMapping(
"SOME=args,here MORE optional=arguments here", {
{"SOME", "args,here"},
});
// Inputs that are effectively invalid under the target grammar.
// PROTOCOLINFO accepts an OtherLine that is just an OptArguments, which
// would make these inputs valid. However,
// - This parser is never used in that situation, because the
// SplitTorReplyLine parser enables OtherLine to be skipped.
// - Even if these were valid, an OptArguments contains no semantic data,
// so there is no point in parsing it.
CheckParseTorReplyMapping("ARGS", {});
CheckParseTorReplyMapping("MORE ARGS", {});
CheckParseTorReplyMapping("MORE ARGS", {});
CheckParseTorReplyMapping("EVEN more=ARGS", {});
CheckParseTorReplyMapping("EVEN+more ARGS", {});
}
BOOST_AUTO_TEST_SUITE_END()
|
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the countSwaps function below.
void countSwaps(vector<int> a) {
int n = a.size(), count=0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
// Swap adjacent elements if they are in decreasing order
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
count++;
}
}
}
cout << "Array is sorted in " << count << " swaps.\n"
<< "First Element: " << *a.begin() << "\n"
<< "Last Element: " << *(a.end()-1) << endl;
return;
}
int main()
{
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string a_temp_temp;
getline(cin, a_temp_temp);
vector<string> a_temp = split_string(a_temp_temp);
vector<int> a(n);
for (int i = 0; i < n; i++) {
int a_item = stoi(a_temp[i]);
a[i] = a_item;
}
countSwaps(a);
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
|
/***************************************************************************
* Copyright (C) by GFZ Potsdam *
* *
* You can redistribute and/or modify this program under the *
* terms of the SeisComP Public License. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* SeisComP Public License for more details. *
***************************************************************************/
#define SEISCOMP_COMPONENT DataModel
#include <seiscomp3/datamodel/stationgroup.h>
#include <seiscomp3/datamodel/inventory.h>
#include <algorithm>
#include <seiscomp3/datamodel/metadata.h>
#include <seiscomp3/logging/log.h>
namespace Seiscomp {
namespace DataModel {
IMPLEMENT_SC_CLASS_DERIVED(StationGroup, PublicObject, "StationGroup");
namespace {
static Seiscomp::Core::MetaEnumImpl<StationGroupType> metaStationGroupType;
}
StationGroup::MetaObject::MetaObject(const Core::RTTI* rtti) : Seiscomp::Core::MetaObject(rtti) {
addProperty(enumProperty("type", "StationGroupType", false, true, &metaStationGroupType, &StationGroup::setType, &StationGroup::type));
addProperty(Core::simpleProperty("code", "string", false, false, true, false, false, false, NULL, &StationGroup::setCode, &StationGroup::code));
addProperty(Core::simpleProperty("start", "datetime", false, false, false, false, true, false, NULL, &StationGroup::setStart, &StationGroup::start));
addProperty(Core::simpleProperty("end", "datetime", false, false, false, false, true, false, NULL, &StationGroup::setEnd, &StationGroup::end));
addProperty(Core::simpleProperty("description", "string", false, false, false, false, false, false, NULL, &StationGroup::setDescription, &StationGroup::description));
addProperty(Core::simpleProperty("latitude", "float", false, false, false, false, true, false, NULL, &StationGroup::setLatitude, &StationGroup::latitude));
addProperty(Core::simpleProperty("longitude", "float", false, false, false, false, true, false, NULL, &StationGroup::setLongitude, &StationGroup::longitude));
addProperty(Core::simpleProperty("elevation", "float", false, false, false, false, true, false, NULL, &StationGroup::setElevation, &StationGroup::elevation));
addProperty(arrayClassProperty<StationReference>("stationReference", "StationReference", &StationGroup::stationReferenceCount, &StationGroup::stationReference, static_cast<bool (StationGroup::*)(StationReference*)>(&StationGroup::add), &StationGroup::removeStationReference, static_cast<bool (StationGroup::*)(StationReference*)>(&StationGroup::remove)));
}
IMPLEMENT_METAOBJECT(StationGroup)
StationGroupIndex::StationGroupIndex() {
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationGroupIndex::StationGroupIndex(const std::string& code_) {
code = code_;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationGroupIndex::StationGroupIndex(const StationGroupIndex& idx) {
code = idx.code;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroupIndex::operator==(const StationGroupIndex& idx) const {
return code == idx.code;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroupIndex::operator!=(const StationGroupIndex& idx) const {
return !operator==(idx);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationGroup::StationGroup() {
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationGroup::StationGroup(const StationGroup& other)
: PublicObject() {
*this = other;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationGroup::StationGroup(const std::string& publicID)
: PublicObject(publicID) {
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationGroup::~StationGroup() {
std::for_each(_stationReferences.begin(), _stationReferences.end(),
std::compose1(std::bind2nd(std::mem_fun(&StationReference::setParent),
(PublicObject*)NULL),
std::mem_fun_ref(&StationReferencePtr::get)));
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationGroup* StationGroup::Create() {
StationGroup* object = new StationGroup();
return static_cast<StationGroup*>(GenerateId(object));
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationGroup* StationGroup::Create(const std::string& publicID) {
if ( PublicObject::IsRegistrationEnabled() && Find(publicID) != NULL ) {
SEISCOMP_ERROR(
"There exists already a PublicObject with Id '%s'",
publicID.c_str()
);
return NULL;
}
return new StationGroup(publicID);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationGroup* StationGroup::Find(const std::string& publicID) {
return StationGroup::Cast(PublicObject::Find(publicID));
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::operator==(const StationGroup& rhs) const {
if ( _index != rhs._index ) return false;
if ( _type != rhs._type ) return false;
if ( _start != rhs._start ) return false;
if ( _end != rhs._end ) return false;
if ( _description != rhs._description ) return false;
if ( _latitude != rhs._latitude ) return false;
if ( _longitude != rhs._longitude ) return false;
if ( _elevation != rhs._elevation ) return false;
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::operator!=(const StationGroup& rhs) const {
return !operator==(rhs);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::equal(const StationGroup& other) const {
return *this == other;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void StationGroup::setType(const OPT(StationGroupType)& type) {
_type = type;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationGroupType StationGroup::type() const {
if ( _type )
return *_type;
throw Seiscomp::Core::ValueException("StationGroup.type is not set");
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void StationGroup::setCode(const std::string& code) {
_index.code = code;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const std::string& StationGroup::code() const {
return _index.code;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void StationGroup::setStart(const OPT(Seiscomp::Core::Time)& start) {
_start = start;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Seiscomp::Core::Time StationGroup::start() const {
if ( _start )
return *_start;
throw Seiscomp::Core::ValueException("StationGroup.start is not set");
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void StationGroup::setEnd(const OPT(Seiscomp::Core::Time)& end) {
_end = end;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Seiscomp::Core::Time StationGroup::end() const {
if ( _end )
return *_end;
throw Seiscomp::Core::ValueException("StationGroup.end is not set");
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void StationGroup::setDescription(const std::string& description) {
_description = description;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const std::string& StationGroup::description() const {
return _description;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void StationGroup::setLatitude(const OPT(double)& latitude) {
_latitude = latitude;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
double StationGroup::latitude() const {
if ( _latitude )
return *_latitude;
throw Seiscomp::Core::ValueException("StationGroup.latitude is not set");
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void StationGroup::setLongitude(const OPT(double)& longitude) {
_longitude = longitude;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
double StationGroup::longitude() const {
if ( _longitude )
return *_longitude;
throw Seiscomp::Core::ValueException("StationGroup.longitude is not set");
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void StationGroup::setElevation(const OPT(double)& elevation) {
_elevation = elevation;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
double StationGroup::elevation() const {
if ( _elevation )
return *_elevation;
throw Seiscomp::Core::ValueException("StationGroup.elevation is not set");
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const StationGroupIndex& StationGroup::index() const {
return _index;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::equalIndex(const StationGroup* lhs) const {
if ( lhs == NULL ) return false;
return lhs->index() == index();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Inventory* StationGroup::inventory() const {
return static_cast<Inventory*>(parent());
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationGroup& StationGroup::operator=(const StationGroup& other) {
PublicObject::operator=(other);
_index = other._index;
_type = other._type;
_start = other._start;
_end = other._end;
_description = other._description;
_latitude = other._latitude;
_longitude = other._longitude;
_elevation = other._elevation;
return *this;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::assign(Object* other) {
StationGroup* otherStationGroup = StationGroup::Cast(other);
if ( other == NULL )
return false;
*this = *otherStationGroup;
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::attachTo(PublicObject* parent) {
if ( parent == NULL ) return false;
// check all possible parents
Inventory* inventory = Inventory::Cast(parent);
if ( inventory != NULL )
return inventory->add(this);
SEISCOMP_ERROR("StationGroup::attachTo(%s) -> wrong class type", parent->className());
return false;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::detachFrom(PublicObject* object) {
if ( object == NULL ) return false;
// check all possible parents
Inventory* inventory = Inventory::Cast(object);
if ( inventory != NULL ) {
// If the object has been added already to the parent locally
// just remove it by pointer
if ( object == parent() )
return inventory->remove(this);
// The object has not been added locally so it must be looked up
else {
StationGroup* child = inventory->findStationGroup(publicID());
if ( child != NULL )
return inventory->remove(child);
else {
SEISCOMP_DEBUG("StationGroup::detachFrom(Inventory): stationGroup has not been found");
return false;
}
}
}
SEISCOMP_ERROR("StationGroup::detachFrom(%s) -> wrong class type", object->className());
return false;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::detach() {
if ( parent() == NULL )
return false;
return detachFrom(parent());
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Object* StationGroup::clone() const {
StationGroup* clonee = new StationGroup();
*clonee = *this;
return clonee;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::updateChild(Object* child) {
StationReference* stationReferenceChild = StationReference::Cast(child);
if ( stationReferenceChild != NULL ) {
StationReference* stationReferenceElement = stationReference(stationReferenceChild->index());
if ( stationReferenceElement != NULL ) {
*stationReferenceElement = *stationReferenceChild;
return true;
}
return false;
}
return false;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void StationGroup::accept(Visitor* visitor) {
if ( visitor->traversal() == Visitor::TM_TOPDOWN )
if ( !visitor->visit(this) )
return;
for ( std::vector<StationReferencePtr>::iterator it = _stationReferences.begin(); it != _stationReferences.end(); ++it )
(*it)->accept(visitor);
if ( visitor->traversal() == Visitor::TM_BOTTOMUP )
visitor->visit(this);
else
visitor->finished();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
size_t StationGroup::stationReferenceCount() const {
return _stationReferences.size();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationReference* StationGroup::stationReference(size_t i) const {
return _stationReferences[i].get();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
StationReference* StationGroup::stationReference(const StationReferenceIndex& i) const {
for ( std::vector<StationReferencePtr>::const_iterator it = _stationReferences.begin(); it != _stationReferences.end(); ++it )
if ( i == (*it)->index() )
return (*it).get();
return NULL;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::add(StationReference* stationReference) {
if ( stationReference == NULL )
return false;
// Element has already a parent
if ( stationReference->parent() != NULL ) {
SEISCOMP_ERROR("StationGroup::add(StationReference*) -> element has already a parent");
return false;
}
// Duplicate index check
for ( std::vector<StationReferencePtr>::iterator it = _stationReferences.begin(); it != _stationReferences.end(); ++it ) {
if ( (*it)->index() == stationReference->index() ) {
SEISCOMP_ERROR("StationGroup::add(StationReference*) -> an element with the same index has been added already");
return false;
}
}
// Add the element
_stationReferences.push_back(stationReference);
stationReference->setParent(this);
// Create the notifiers
if ( Notifier::IsEnabled() ) {
NotifierCreator nc(OP_ADD);
stationReference->accept(&nc);
}
// Notify registered observers
childAdded(stationReference);
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::remove(StationReference* stationReference) {
if ( stationReference == NULL )
return false;
if ( stationReference->parent() != this ) {
SEISCOMP_ERROR("StationGroup::remove(StationReference*) -> element has another parent");
return false;
}
std::vector<StationReferencePtr>::iterator it;
it = std::find(_stationReferences.begin(), _stationReferences.end(), stationReference);
// Element has not been found
if ( it == _stationReferences.end() ) {
SEISCOMP_ERROR("StationGroup::remove(StationReference*) -> child object has not been found although the parent pointer matches???");
return false;
}
// Create the notifiers
if ( Notifier::IsEnabled() ) {
NotifierCreator nc(OP_REMOVE);
(*it)->accept(&nc);
}
(*it)->setParent(NULL);
childRemoved((*it).get());
_stationReferences.erase(it);
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::removeStationReference(size_t i) {
// index out of bounds
if ( i >= _stationReferences.size() )
return false;
// Create the notifiers
if ( Notifier::IsEnabled() ) {
NotifierCreator nc(OP_REMOVE);
_stationReferences[i]->accept(&nc);
}
_stationReferences[i]->setParent(NULL);
childRemoved(_stationReferences[i].get());
_stationReferences.erase(_stationReferences.begin() + i);
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool StationGroup::removeStationReference(const StationReferenceIndex& i) {
StationReference* object = stationReference(i);
if ( object == NULL ) return false;
return remove(object);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void StationGroup::serialize(Archive& ar) {
// Do not read/write if the archive's version is higher than
// currently supported
if ( ar.isHigherVersion<0,11>() ) {
SEISCOMP_ERROR("Archive version %d.%d too high: StationGroup skipped",
ar.versionMajor(), ar.versionMinor());
ar.setValidity(false);
return;
}
PublicObject::serialize(ar);
if ( !ar.success() ) return;
ar & NAMED_OBJECT_HINT("type", _type, Archive::XML_ELEMENT);
ar & NAMED_OBJECT_HINT("code", _index.code, Archive::INDEX_ATTRIBUTE);
if ( ar.supportsVersion<0,10>() )
ar & NAMED_OBJECT_HINT("start", _start, Archive::XML_ELEMENT | Archive::SPLIT_TIME);
else
ar & NAMED_OBJECT_HINT("start", _start, Archive::XML_ELEMENT);
if ( ar.supportsVersion<0,10>() )
ar & NAMED_OBJECT_HINT("end", _end, Archive::XML_ELEMENT | Archive::SPLIT_TIME);
else
ar & NAMED_OBJECT_HINT("end", _end, Archive::XML_ELEMENT);
ar & NAMED_OBJECT_HINT("description", _description, Archive::XML_ELEMENT);
ar & NAMED_OBJECT_HINT("latitude", _latitude, Archive::XML_ELEMENT);
ar & NAMED_OBJECT_HINT("longitude", _longitude, Archive::XML_ELEMENT);
ar & NAMED_OBJECT_HINT("elevation", _elevation, Archive::XML_ELEMENT);
if ( ar.hint() & Archive::IGNORE_CHILDS ) return;
ar & NAMED_OBJECT_HINT("stationReference",
Seiscomp::Core::Generic::containerMember(_stationReferences,
Seiscomp::Core::Generic::bindMemberFunction<StationReference>(static_cast<bool (StationGroup::*)(StationReference*)>(&StationGroup::add), this)),
Archive::STATIC_TYPE);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}
}
|
#include "src/enums/webrtc/degradation_preference.h"
#define ENUM(X) DEGRADATON_PREFERENCE ## X
#include "src/enums/macros/impls.h"
#undef ENUM
|
#include <common/app/log/LogContext.h>
#include <common/net/message/storage/quota/SetExceededQuotaRespMsg.h>
#include "program/Program.h"
#include "SetExceededQuotaMsgEx.h"
bool SetExceededQuotaMsgEx::processIncoming(ResponseContext& ctx)
{
bool retVal = true;
FhgfsOpsErr errorCode = FhgfsOpsErr_SUCCESS;
if(Program::getApp()->getConfig()->getQuotaEnableEnforcement() )
{
// get the storage pool for which quota is exceeded
StoragePoolPtr storagePool =
Program::getApp()->getStoragePoolStore()->getPool(getStoragePoolId());
if (!storagePool)
{
LOG(QUOTA, WARNING, "Couldn't set exceeded quota, "
"because requested storage pool doesn't exist on storage server.",
("storagePoolId", getStoragePoolId()));
errorCode = FhgfsOpsErr_UNKNOWNPOOL;
goto send_response;
}
// see if any of our targets belong to this pool and, if yes, set exceeded quota info
for (const auto& mapping : Program::getApp()->getStorageTargets()->getTargets())
{
if (storagePool->hasTarget(mapping.first))
{
// update exceeded quota
Program::getApp()->getExceededQuotaStores()->get(mapping.first)->
updateExceededQuota(getExceededQuotaIDs(), getQuotaDataType(), getExceededType() );
}
}
}
else
{
LOG(QUOTA, ERR, "Unable to set exceeded quota IDs. Configuration problem detected. "
"The management daemon on " + ctx.peerName() + " has quota enforcement enabled, "
"but not this storage daemon. Fix this configuration problem or quota enforcement "
"will not work correctly. If quota enforcement settings have changed recently in the "
"mgmtd configuration, please restart all BeeGFS services.");
errorCode = FhgfsOpsErr_INTERNAL;
}
send_response:
ctx.sendResponse(SetExceededQuotaRespMsg(errorCode) );
return retVal;
}
|
#include <stan/math.hpp>
#include <gtest/gtest.h>
TEST(MathFunctions, logInt) {
using stan::math::log;
using std::log;
EXPECT_FLOAT_EQ(std::log(3), log(3));
EXPECT_FLOAT_EQ(std::log(3.0), log(3.0));
}
TEST(MathFunctions, log_works_with_other_functions) {
Eigen::VectorXd a(5);
a << 1.1, 1.2, 1.3, 1.4, 1.5;
Eigen::RowVectorXd b(5);
b << 1.1, 1.2, 1.3, 1.4, 1.5;
stan::math::multiply(a, stan::math::log(b));
}
|
/*
* Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "It_vfs_jffs.h"
static UINT32 Testcase(VOID)
{
INT32 fd1, fd2, fd3;
INT32 ret, len;
INT32 flags;
ssize_t lenV = 0;
CHAR readbuf[JFFS_STANDARD_NAME_LENGTH] = "liteos";
CHAR pathname1[JFFS_STANDARD_NAME_LENGTH] = { JFFS_PATH_NAME0 };
CHAR pathname2[JFFS_STANDARD_NAME_LENGTH] = { JFFS_PATH_NAME0 };
CHAR pathname3[JFFS_STANDARD_NAME_LENGTH] = { JFFS_MAIN_DIR0 };
CHAR bufW1[JFFS_SHORT_ARRAY_LENGTH + 1] = "0123456789";
CHAR bufW2[JFFS_SHORT_ARRAY_LENGTH + 1] = "abcefghijk";
CHAR bufW3[JFFS_STANDARD_NAME_LENGTH] = "lalalalala";
off_t off;
ret = mkdir(pathname1, S_IRWXU | S_IRWXG | S_IRWXO);
ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT);
ret = chdir(pathname1);
ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT);
JffsStrcat2(pathname1, "/1491_1", JFFS_STANDARD_NAME_LENGTH);
fd1 = open(pathname1, O_NONBLOCK | O_CREAT | O_RDWR | O_EXCL, S_IRWXU | S_IRWXG | S_IRWXO);
ICUNIT_GOTO_NOT_EQUAL(fd1, -1, fd1, EXIT2);
JffsStrcat2(pathname1, "/1491_2", JFFS_STANDARD_NAME_LENGTH);
fd2 = open(pathname1, O_NONBLOCK | O_CREAT | O_RDWR | O_EXCL, S_IRWXU | S_IRWXG | S_IRWXO);
ICUNIT_GOTO_NOT_EQUAL(fd2, -1, fd2, EXIT4);
JffsStrcat2(pathname1, "/1491_3", JFFS_STANDARD_NAME_LENGTH);
fd3 = open(pathname1, O_NONBLOCK | O_CREAT | O_RDWR | O_EXCL, S_IRWXU | S_IRWXG | S_IRWXO);
ICUNIT_GOTO_NOT_EQUAL(fd3, -1, fd3, EXIT6);
len = write(fd1, bufW1, JFFS_SHORT_ARRAY_LENGTH);
ICUNIT_GOTO_EQUAL(len, 10, len, EXIT6); // compare ret len with target len 10
len = write(fd2, bufW2, JFFS_SHORT_ARRAY_LENGTH);
ICUNIT_GOTO_EQUAL(len, 10, len, EXIT6); // compare ret len with target len 10
ret = close(fd1);
ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT6);
ret = close(fd2);
ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT6);
JffsStrcat2(pathname1, "/1491_1", JFFS_STANDARD_NAME_LENGTH);
fd1 = open(pathname1, O_NONBLOCK | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO);
ICUNIT_GOTO_NOT_EQUAL(fd1, -1, fd1, EXIT6);
JffsStrcat2(pathname1, "/1491_2", JFFS_STANDARD_NAME_LENGTH);
fd2 = open(pathname1, O_NONBLOCK | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO);
ICUNIT_GOTO_NOT_EQUAL(fd2, -1, fd2, EXIT6);
memset(bufW1, 0, JFFS_SHORT_ARRAY_LENGTH + 1);
memset(bufW2, 0, JFFS_SHORT_ARRAY_LENGTH + 1);
len = read(fd1, bufW1, JFFS_SHORT_ARRAY_LENGTH);
ICUNIT_GOTO_EQUAL(len, 10, len, EXIT6); // compare ret len with target len 10
len = read(fd2, bufW2, JFFS_SHORT_ARRAY_LENGTH);
ICUNIT_GOTO_EQUAL(len, 10, len, EXIT6); // compare ret len with target len 10
g_jffsIov[0].iov_base = bufW1;
g_jffsIov[0].iov_len = JFFS_SHORT_ARRAY_LENGTH;
g_jffsIov[1].iov_base = bufW2;
g_jffsIov[1].iov_len = JFFS_SHORT_ARRAY_LENGTH;
lenV = writev(fd3, g_jffsIov, 2); // writes 2 buffers to the fd
ICUNIT_GOTO_EQUAL(lenV, 20, lenV, EXIT6); // compare ret lenV to target 20 lenV
memset(bufW1, 0, JFFS_SHORT_ARRAY_LENGTH + 1);
memset(bufW2, 0, JFFS_SHORT_ARRAY_LENGTH + 1);
off = lseek(fd3, 0, SEEK_SET);
ICUNIT_GOTO_EQUAL(ret, JFFS_NO_ERROR, ret, EXIT6);
g_jffsIov[0].iov_base = bufW1;
g_jffsIov[0].iov_len = JFFS_SHORT_ARRAY_LENGTH - 1;
g_jffsIov[1].iov_base = bufW2;
g_jffsIov[1].iov_len = JFFS_SHORT_ARRAY_LENGTH - 1;
lenV = readv(fd3, g_jffsIov, 2); // reads 2 buffers from the fd
ICUNIT_GOTO_EQUAL(lenV, 2 * (JFFS_SHORT_ARRAY_LENGTH - 1), lenV, EXIT6);
ret = close(fd3);
ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT6);
JffsStrcat2(pathname1, "/1491_3", JFFS_STANDARD_NAME_LENGTH);
ret = remove(pathname1);
ICUNIT_GOTO_EQUAL(ret, JFFS_NO_ERROR, ret, EXIT5);
ret = close(fd2);
ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT4);
JffsStrcat2(pathname1, "/1491_2", JFFS_STANDARD_NAME_LENGTH);
ret = remove(pathname1);
ICUNIT_GOTO_EQUAL(ret, JFFS_NO_ERROR, ret, EXIT3);
ret = close(fd1);
ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT2);
JffsStrcat2(pathname1, "/1491_1", JFFS_STANDARD_NAME_LENGTH);
ret = remove(pathname1);
ICUNIT_GOTO_EQUAL(ret, JFFS_NO_ERROR, ret, EXIT1);
ret = chdir(JFFS_MAIN_DIR0);
ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT);
ret = rmdir(pathname2);
ICUNIT_GOTO_EQUAL(ret, JFFS_NO_ERROR, ret, EXIT);
return JFFS_NO_ERROR;
EXIT6:
close(fd3);
EXIT5:
JffsStrcat2(pathname1, "/1491_3", JFFS_STANDARD_NAME_LENGTH);
remove(pathname1);
EXIT4:
close(fd2);
EXIT3:
JffsStrcat2(pathname1, "/1491_2", JFFS_STANDARD_NAME_LENGTH);
remove(pathname1);
EXIT2:
close(fd1);
EXIT1:
JffsStrcat2(pathname1, "/1491_1", JFFS_STANDARD_NAME_LENGTH);
remove(pathname1);
EXIT:
remove(pathname2);
return JFFS_NO_ERROR;
}
/*
*
testcase brief in English
*
*/
VOID ItFsJffs429(VOID)
{
TEST_ADD_CASE("IT_FS_JFFS_429", Testcase, TEST_VFS, TEST_JFFS, TEST_LEVEL2, TEST_FUNCTION);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.